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 possession;
29pub mod protocol;
30pub mod pruning;
31pub mod quorum;
32pub mod recent_provers;
33pub mod scheduling;
34pub mod slice;
35pub mod storage_commitment_audit;
36pub mod subtree;
37pub mod types;
38
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::fmt;
41use std::num::NonZeroUsize;
42use std::ops::ControlFlow;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::Arc;
46use std::time::{Duration, Instant, SystemTime};
47
48use lru::LruCache;
49use std::pin::Pin;
50
51use crate::logging::{debug, error, info, warn};
52use futures::stream::FuturesUnordered;
53use futures::{future::join_all, Future, StreamExt};
54use parking_lot::Mutex;
55use rand::rngs::StdRng;
56use rand::{Rng, SeedableRng};
57use tokio::sync::broadcast::error::RecvError;
58use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
59use tokio::task::JoinHandle;
60use tokio_util::sync::CancellationToken;
61use tokio_util::task::TaskTracker;
62
63use crate::ant_protocol::XorName;
64use crate::error::{Error, Result};
65use crate::payment::{
66    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
67    MIN_PAYMENT_PROOF_SIZE_BYTES,
68};
69use crate::replication::audit::AuditTickResult;
70use crate::replication::audit_coordinator::AuditChallengeCoordinator;
71use crate::replication::audit_metrics::{
72    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
73    ReplicationResponderClass, ResponderAdmissionCeiling,
74};
75use crate::replication::commitment::{commitment_hash, StorageCommitment};
76use crate::replication::commitment_state::{
77    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
78};
79use crate::replication::config::{
80    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
81    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
82    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
83    MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
84    REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
85    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
86};
87use crate::replication::paid_list::PaidList;
88use crate::replication::protocol::{
89    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
90    VerificationResponse,
91};
92use crate::replication::quorum::KeyVerificationOutcome;
93use crate::replication::recent_provers::RecentProvers;
94use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
95use crate::replication::types::{
96    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98    VerificationState,
99};
100use crate::storage::{CapacityVerdict, ChunkStore};
101use saorsa_core::identity::{NodeIdentity, PeerId};
102use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
103use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
104
105/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
106/// because it was full (Amendment 2). Process-global because the producer is
107/// the payment verifier (a different module) and the drop happens before the
108/// per-drainer `received` counter. A non-zero value is the rollout signal that
109/// nomination ingress is saturating — benign (penalty-free, lottery/next-
110/// payment covered) but worth watching. `Closed` (engine shut down) is not
111/// counted: it is not a saturation signal.
112static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
113
114/// Record one ingress-full drop. Called by the payment verifier's `try_send`
115/// sites; read by the drainer's periodic summary.
116pub(crate) fn note_monetized_ingress_drop() {
117    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
118}
119
120#[derive(Default)]
121struct FirstAuditObservability {
122    received: AtomicU64,
123    queued: AtomicU64,
124    coalesced: AtomicU64,
125    duplicates: AtomicU64,
126    capacity_evicted: AtomicU64,
127    /// An event targeting the local peer itself, dropped at ingress: the node
128    /// cannot network-audit itself (no dialable address for the local peer).
129    self_target_skipped: AtomicU64,
130    /// A strictly-lower-count same-peer nomination that was dropped so a
131    /// higher-count pending pin survived. A sustained rise is the signal of an
132    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
133    suppressed_lower: AtomicU64,
134    cooldown_deferred_attempts: AtomicU64,
135    rate_deferred_attempts: AtomicU64,
136    window_deduped: AtomicU64,
137    launched: AtomicU64,
138    passed: AtomicU64,
139    timed_out: AtomicU64,
140    failed: AtomicU64,
141    bootstrap_claims: AtomicU64,
142    idle: AtomicU64,
143    insufficient_keys: AtomicU64,
144    outside_answerability_window: AtomicU64,
145    inflight: AtomicU64,
146}
147
148/// Test-only snapshot of the first-audit scheduler counters.
149///
150/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
151/// self-targeting monetized pin was dropped and never launched) instead of
152/// scraping log lines.
153#[cfg(any(test, feature = "test-utils"))]
154#[derive(Debug, Clone, Copy)]
155pub struct FirstAuditStats {
156    /// Events ingested from the monetized-pin channel.
157    pub received: u64,
158    /// Events accepted into the pending first-audit queue.
159    pub queued: u64,
160    /// Events dropped because they targeted the local peer.
161    pub self_target_skipped: u64,
162    /// Audits launched.
163    pub launched: u64,
164    /// Launched audits that passed.
165    pub passed: u64,
166    /// Launched audits that timed out (non-response lane).
167    pub timed_out: u64,
168    /// Launched audits that ended in a confirmed failure.
169    pub failed: u64,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum FirstAuditTerminalOutcome {
174    Passed,
175    Timeout,
176    Failed,
177    BootstrapClaim,
178    Idle,
179    InsufficientKeys,
180}
181
182impl FirstAuditTerminalOutcome {
183    #[cfg(any(feature = "logging", test))]
184    const fn as_str(self) -> &'static str {
185        match self {
186            Self::Passed => "passed",
187            Self::Timeout => "timeout",
188            Self::Failed => "failed",
189            Self::BootstrapClaim => "bootstrap_claim",
190            Self::Idle => "idle",
191            Self::InsufficientKeys => "insufficient_keys",
192        }
193    }
194}
195
196fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
197    match result {
198        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
199        AuditTickResult::Failed {
200            evidence:
201                FailureEvidence::AuditFailure {
202                    reason: AuditFailureReason::Timeout,
203                    ..
204                },
205            ..
206        } => FirstAuditTerminalOutcome::Timeout,
207        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
208        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
209        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
210        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
211    }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum FirstAuditQueueOutcome {
216    /// New peer inserted with free capacity.
217    Queued,
218    /// Collapsed with an existing same-peer entry; the incoming won (higher
219    /// count, or equal count and newer) and replaced it.
220    Coalesced,
221    /// Collapsed with an existing same-peer entry; the incoming LOST because it
222    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
223    /// in place. This is the attempted cheaper-pin self-erasure signal.
224    SuppressedLower,
225    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
226    /// lost the freshness tie (it was not the newer of the two) and the
227    /// existing entry was retained. Benign, not an attack signal.
228    RetainedOnTie,
229    /// A DIFFERENT peer's entry was displaced from the capped pending queue
230    /// (random victim) to make room.
231    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
232}
233
234/// Coalesce a monetized nomination into the per-peer pending queue with a
235/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
236/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
237///
238/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
239/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
240/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
241/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
242/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
243/// cannot promote the retained pin's lane position.
244///
245/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
246/// last, so it wins an equal-count tie for freshness) from a cooldown-race
247/// requeue of an older reserved event (the pending successor is newer, so it
248/// wins the tie).
249fn coalesce_first_audit_event(
250    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
251    incoming: MonetizedPinEvent,
252    incoming_is_newer: bool,
253    rng: &mut StdRng,
254) -> FirstAuditQueueOutcome {
255    if let Some(existing) = pending.peek(&incoming.peer) {
256        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
257        // the retained pin's recency (the security-relevant self-erasure case).
258        if incoming.key_count < existing.key_count {
259            return FirstAuditQueueOutcome::SuppressedLower;
260        }
261        // Equal count -> keep the fresher; an older incoming loses a benign tie.
262        if incoming.key_count == existing.key_count && !incoming_is_newer {
263            return FirstAuditQueueOutcome::RetainedOnTie;
264        }
265        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
266        // the value and bumps MRU; replacing an existing key never evicts a
267        // different peer.
268        let _ = pending.push(incoming.peer, incoming);
269        return FirstAuditQueueOutcome::Coalesced;
270    }
271    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
272    // never the LRU: deterministic keep-newest would let an ordered batch of
273    // `cap` distinct-peer nominations flush a chosen target before any launch
274    // lane sees it, cutting the eviction cost from probabilistic to exact. A
275    // random victim caps an attacker's per-nomination eviction probability at
276    // `1/cap` regardless of arrival order or timing, so suppressing a specific
277    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
278    // nominations and is never certain (ADR-0004 Amendment 4).
279    if pending.len() >= pending.cap().get() {
280        let victim = {
281            let idx = rng.gen_range(0..pending.len());
282            pending.iter().nth(idx).map(|(p, _)| *p)
283        };
284        if let Some(victim_peer) = victim {
285            if let Some(evicted) = pending.pop(&victim_peer) {
286                let _ = pending.push(incoming.peer, incoming);
287                return FirstAuditQueueOutcome::CapacityEvicted {
288                    peer: victim_peer,
289                    pin: evicted.pin,
290                };
291            }
292        }
293    }
294    match pending.push(incoming.peer, incoming) {
295        None => FirstAuditQueueOutcome::Queued,
296        // Unreachable: the random-displacement branch above guarantees
297        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
298        // exists). Kept so any future logic error surfaces as an ACCOUNTED
299        // eviction rather than silent loss — but note this arm would be
300        // LRU-order, not random, so it must stay unreachable.
301        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
302            peer: evicted_peer,
303            pin: evicted.pin,
304        },
305    }
306}
307
308/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
309/// prefiltering a nomination's answerability at schedule time, covering the
310/// spawn/dispatch latency between the timer firing and the wire challenge so a
311/// jitter==MAX pin is not admitted only to fail the authoritative check by a
312/// few milliseconds. Tiny against the multi-hour answerability window.
313const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
314
315/// A first audit the limiter recently launched at a peer: when, and the
316/// committed key count that was audited (for the count-jump override).
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318struct RecentFirstAudit {
319    launched_at: Instant,
320    key_count: u32,
321}
322
323/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
324/// panicking or cancelled audit task can never leak a slot and wedge the
325/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
326struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
327
328impl FirstAuditInflightSlot {
329    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
330        observability.inflight.fetch_add(1, Ordering::Relaxed);
331        Self(Arc::clone(observability))
332    }
333}
334
335impl Drop for FirstAuditInflightSlot {
336    fn drop(&mut self) {
337        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
338    }
339}
340
341/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
342/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
343/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
344/// overflow-free integer math). A jump re-nominates a peer despite a recent
345/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
346/// only, so no gossip-lottery audit can ever cover it.
347const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
348    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
349        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
350}
351
352/// The launch limiter's verdict for one pending monetized pin.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum LimiterVerdict {
355    /// Within budget and window: the caller may reserve a launch (and consumes
356    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
357    Admit,
358    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
359    /// pin pending and retry on a later tick.
360    RateDeferred,
361    /// The peer had a first audit within
362    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
363    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
364    /// gossip-lottery re-audit path is unaffected).
365    WindowDeduped,
366}
367
368/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
369/// (launch rate), an in-flight cap, and a per-peer re-audit window that
370/// survives pin rotation.
371///
372/// This is the load-bearing aggregate bound the original scheduler lacked:
373/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
374/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
375/// `now`/`inflight` values so every decision is unit-testable without a
376/// runtime.
377struct FirstAuditLimiter {
378    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
379    tokens: u32,
380    /// Refill anchor. While the bucket is full this tracks `now` (a full
381    /// bucket accrues nothing); while below capacity it advances only by
382    /// whole refill intervals so fractional elapsed time is never lost.
383    last_refill: Instant,
384    /// Peers given a first audit recently, with the audited key count.
385    /// Bounded like the drainer's other per-peer maps.
386    recent: LruCache<PeerId, RecentFirstAudit>,
387}
388
389impl FirstAuditLimiter {
390    fn new(now: Instant) -> Self {
391        Self {
392            tokens: config::FIRST_AUDIT_BUDGET_BURST,
393            last_refill: now,
394            recent: LruCache::new(
395                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
396            ),
397        }
398    }
399
400    /// Whether the per-peer re-audit window admits a nomination for `peer`
401    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
402    /// call at ENQUEUE time — suppressed nominations never occupy pending
403    /// slots — without disturbing LRU recency.
404    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
405        self.recent.peek(peer).is_none_or(|prev| {
406            now.saturating_duration_since(prev.launched_at)
407                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
408                || first_audit_count_jump(prev.key_count, key_count)
409        })
410    }
411
412    /// Refill the token bucket for the time elapsed up to `now`.
413    fn refill(&mut self, now: Instant) {
414        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
415            // Full bucket accrues nothing; keep the anchor current so the
416            // next consumption starts its interval from here.
417            self.last_refill = now;
418            return;
419        }
420        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
421        let elapsed = now.saturating_duration_since(self.last_refill);
422        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
423        if earned == 0 {
424            return;
425        }
426        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
427        if earned >= capacity_gap {
428            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
429            self.last_refill = now;
430        } else {
431            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
432            self.tokens = self
433                .tokens
434                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
435            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
436            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
437        }
438    }
439
440    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
441    /// caller runs the remaining (per-peer cooldown) gate and calls
442    /// [`Self::commit_launch`] only for a launch that actually happens, so a
443    /// deferral elsewhere never burns budget or stamps the window.
444    fn assess(
445        &mut self,
446        peer: &PeerId,
447        key_count: u32,
448        now: Instant,
449        inflight: u64,
450    ) -> LimiterVerdict {
451        if !self.window_allows(peer, key_count, now) {
452            return LimiterVerdict::WindowDeduped;
453        }
454        self.refill(now);
455        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
456            return LimiterVerdict::RateDeferred;
457        }
458        LimiterVerdict::Admit
459    }
460
461    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
462    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
463    /// only at [`Self::promote`], after the authoritative post-jitter
464    /// answerability check, so a reservation that is later cancelled leaves no
465    /// suppression behind.
466    fn reserve_token(&mut self) {
467        self.tokens = self.tokens.saturating_sub(1);
468    }
469
470    /// Return a token consumed by a reservation that was cancelled before it
471    /// launched (answerability lapsed or a concurrent gossip audit won the
472    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
473    /// the bucket.
474    fn refund_token(&mut self) {
475        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
476    }
477
478    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
479    /// (promotion). Separated from token consumption so suppression is only
480    /// ever recorded for a real send.
481    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
482        self.recent.put(
483            peer,
484            RecentFirstAudit {
485                launched_at: now,
486                key_count,
487            },
488        );
489    }
490
491    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
492    /// and stamp the window in one call. Production splits these across
493    /// reservation and promotion; the limiter's own budget/window unit tests do
494    /// not model the jitter reservation and use this shorthand.
495    #[cfg(test)]
496    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
497        self.reserve_token();
498        self.promote(peer, key_count, now);
499    }
500}
501
502/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
503/// across the ENTIRE launch-jitter window ending at
504/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
505/// for it cannot later require aborting an out-of-window challenge. The
506/// too-future bound is enforced at `now` (a jitter delay only ages a pin
507/// forward, never toward the future); the too-old bound is enforced at the
508/// latest possible send time. This is a conservative admission prefilter; the
509/// authoritative answerability check still runs at promotion against the real
510/// send-time wall clock, so A1 (no false conviction) holds regardless of how
511/// jitter and the answerability margin are sized. `checked_add` overflow fails
512/// closed (skip the pin).
513fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
514    let Some(latest_send) = now
515        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
516        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
517    else {
518        return false;
519    };
520    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
521}
522
523/// Open the single first-audit reservation from `pending` if none is
524/// outstanding: samples the launch jitter, snapshots the shared cooldown
525/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
526/// shared implementation for both drainer call sites — the per-wake launch
527/// phase and the pre-overflow opportunity inside the ingress batch — so the
528/// two cannot drift.
529async fn open_first_audit_reservation(
530    scheduler: &mut FirstAuditScheduler,
531    cooldown: &RwLock<HashMap<PeerId, Instant>>,
532    observability: &Arc<FirstAuditObservability>,
533) {
534    if scheduler.has_reservation() {
535        return;
536    }
537    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
538        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
539    ));
540    let inflight = observability.inflight.load(Ordering::Relaxed);
541    let reserved = {
542        let cooldown = cooldown.read().await;
543        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
544    };
545    if reserved {
546        if let Some(peer) = scheduler.reserved_peer() {
547            debug!(
548                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
549                scheduler.pending_len()
550            );
551        }
552    }
553}
554
555/// A far-future `Instant` used to effectively DISABLE the promotion-timer
556/// select arm when no reservation is outstanding. The drainer still wakes at
557/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
558/// needs to be comfortably past the next tick.
559fn first_audit_far_future() -> Instant {
560    Instant::now()
561        .checked_add(Duration::from_hours(1))
562        .unwrap_or_else(Instant::now)
563}
564
565/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
566/// its in-flight slot and launch token from schedule time until the jitter
567/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
568/// only if the authoritative post-jitter answerability + cooldown checks pass at
569/// promotion, so a cancelled reservation leaves NO suppression behind.
570struct FirstAuditReservation {
571    event: MonetizedPinEvent,
572    ready_at: Instant,
573    inflight: FirstAuditInflightSlot,
574}
575
576/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
577/// pending queue, the dedup set, the launch limiter, the alternating lane, and
578/// the single outstanding reservation. All mutation is single-threaded in the
579/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
580/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
581/// state machine is unit-testable with injected clocks.
582struct FirstAuditScheduler {
583    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
584    /// (a real send), never at reservation, so a cancelled reservation can be
585    /// re-nominated.
586    first_audited: LruCache<[u8; 32], ()>,
587    /// Highest-count-per-peer pending nominations not yet launched. Capped at
588    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
589    /// one effective answerability window); at capacity a uniformly RANDOM
590    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
591    /// of a specific entry can never be forced deterministically. One further
592    /// entry may be held in `reserved` outside this queue — a deliberate
593    /// one-entry guard slot, so total schedulable occupancy is at most
594    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
595    pending: LruCache<PeerId, MonetizedPinEvent>,
596    /// Token bucket + per-peer re-audit window.
597    limiter: FirstAuditLimiter,
598    /// The single outstanding reservation (E′ serializes reservations so the
599    /// per-launch lane alternation is preserved and at most one jitter timer is
600    /// live).
601    reserved: Option<FirstAuditReservation>,
602    /// Alternating launch lane, flipped on every PROMOTION (real launch).
603    oldest_first_lane: bool,
604    /// The local node's own peer ID. A verified payment's quote list includes
605    /// the node's own quote, so the verifier emits a monetized-pin event for
606    /// the local peer on every payment it verifies. The node cannot
607    /// network-audit itself (there is no dialable address for the local peer,
608    /// so the challenge fails instantly and is miscounted as a timeout), while
609    /// any other payee that verifies the same payment schedules its own first
610    /// audit of this node's pin — a self-dial adds no coverage either way.
611    /// Such an event is dropped at ingress: never queued, and hence never
612    /// launched nor marked first-audited.
613    self_peer: PeerId,
614    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
615    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
616    /// production seeds from OS entropy at construction.
617    rng: StdRng,
618}
619
620impl FirstAuditScheduler {
621    fn new(now: Instant, self_peer: PeerId) -> Self {
622        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
623        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
624        Self {
625            first_audited: LruCache::new(dedup_cap),
626            pending: LruCache::new(pending_cap),
627            limiter: FirstAuditLimiter::new(now),
628            reserved: None,
629            oldest_first_lane: false,
630            self_peer,
631            rng: StdRng::from_entropy(),
632        }
633    }
634
635    /// Observability getter: used by the scheduler summary log and unit tests,
636    /// both absent from a release `--no-default-features` build, so it is dead
637    /// only in that configuration.
638    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
639    fn pending_len(&self) -> usize {
640        self.pending.len()
641    }
642
643    /// Observability getter (see [`Self::pending_len`]).
644    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
645    fn tokens(&self) -> u32 {
646        self.limiter.tokens
647    }
648
649    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
650    /// signed quote timestamp of the oldest pin still awaiting a first audit:
651    /// how close the longest-waiting pending pin is to aging out of the
652    /// answerability window. A value climbing toward the window means pending
653    /// work is expiring unaudited instead of launching; a small, steady value
654    /// means the queue is draining promptly. Returns `0` when `pending` is empty
655    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
656    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
657    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
658        self.pending
659            .iter()
660            .map(|(_, e)| e.quote_ts)
661            .min()
662            .and_then(|oldest| now.duration_since(oldest).ok())
663            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
664    }
665
666    /// Drop every pending nomination that has aged past the answerability
667    /// horizon. `try_reserve` collects expired entries only while it can scan —
668    /// under token starvation it returns at the budget gate first — so without
669    /// a periodic sweep dead entries squat the capped pending queue (displacing
670    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
671    /// telemetry. Each removal is accounted as `outside_answerability_window`,
672    /// exactly like a scan-time expiry. Returns how many entries were dropped;
673    /// survivor recency is untouched.
674    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
675        let expired: Vec<PeerId> = self
676            .pending
677            .iter()
678            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
679            .map(|(peer, _)| *peer)
680            .collect();
681        for peer in &expired {
682            self.pending.pop(peer);
683        }
684        if !expired.is_empty() {
685            obs.outside_answerability_window.fetch_add(
686                u64::try_from(expired.len()).unwrap_or(u64::MAX),
687                Ordering::Relaxed,
688            );
689        }
690        expired.len()
691    }
692
693    fn has_reservation(&self) -> bool {
694        self.reserved.is_some()
695    }
696
697    /// Whether admitting `event` would displace a DIFFERENT peer's pending
698    /// entry: the queue is at capacity and `event.peer` has no incumbent to
699    /// coalesce into. The drainer checks this before enqueueing so pending
700    /// work gets a reservation opportunity BEFORE destructive overflow
701    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
702    /// of `pending`, freeing the slot without any eviction.
703    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
704        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
705    }
706
707    /// When the outstanding reservation becomes eligible for promotion.
708    fn reserved_ready_at(&self) -> Option<Instant> {
709        self.reserved.as_ref().map(|r| r.ready_at)
710    }
711
712    /// The peer of the outstanding reservation, if any.
713    fn reserved_peer(&self) -> Option<PeerId> {
714        self.reserved.as_ref().map(|r| r.event.peer)
715    }
716
717    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
718    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
719    /// if already first-audited; the window screen is bypassed for the currently
720    /// reserved peer (so a successor is retained across the reservation, never
721    /// window-dropped); otherwise window-screened. Coalescing is
722    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
723    /// displaces a higher-count pending pin. An incumbent that has aged past
724    /// the answerability horizon is dropped (and accounted as an expiry) before
725    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
726    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
727    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
728    /// displacement is accounted as `capacity_evicted` and stamps no
729    /// suppression, so a displaced peer's next nomination is judged like any
730    /// newcomer. The drainer additionally offers a reservation opportunity
731    /// via [`Self::would_displace`] before calling this on an overflowing
732    /// arrival.
733    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
734        if event.peer == self.self_peer {
735            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
736            return;
737        }
738        if self.first_audited.contains(&event.pin) {
739            obs.duplicates.fetch_add(1, Ordering::Relaxed);
740            return;
741        }
742        let reserved_peer = self.reserved_peer();
743        let is_reserved_peer = reserved_peer == Some(event.peer);
744        if !is_reserved_peer
745            && !self
746                .limiter
747                .window_allows(&event.peer, event.key_count, Instant::now())
748        {
749            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
750            return;
751        }
752        // A pending incumbent past the answerability horizon can never launch,
753        // yet its (possibly higher) key count would still win the coalesce
754        // against a live incoming — e.g. a fresh post-prune lower-count pin —
755        // and under token starvation no reserve scan runs to collect it. Drop
756        // it first so the incoming is judged on its own merits.
757        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
758            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
759        });
760        if stale_incumbent {
761            self.pending.pop(&event.peer);
762            obs.outside_answerability_window
763                .fetch_add(1, Ordering::Relaxed);
764        }
765        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
766        // tie.
767        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
768            FirstAuditQueueOutcome::Queued => {
769                obs.queued.fetch_add(1, Ordering::Relaxed);
770            }
771            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
772                obs.coalesced.fetch_add(1, Ordering::Relaxed);
773            }
774            FirstAuditQueueOutcome::SuppressedLower => {
775                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
776            }
777            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
778                obs.queued.fetch_add(1, Ordering::Relaxed);
779                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
780            }
781        }
782    }
783
784    /// Attempt to create the single reservation from `pending` (E′ reserve).
785    /// Scans in the current lane order and reserves the FIRST eligible pin:
786    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
787    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
788    /// flip the lane — those happen only at promotion. Returns whether a
789    /// reservation was made. `cooldown` is a read-only snapshot (the
790    /// authoritative check-and-stamp is at promotion).
791    fn try_reserve(
792        &mut self,
793        mono_now: Instant,
794        inflight: u64,
795        jitter: Duration,
796        cooldown: &HashMap<PeerId, Instant>,
797        obs: &Arc<FirstAuditObservability>,
798    ) -> bool {
799        if self.reserved.is_some() || self.pending.is_empty() {
800            return false;
801        }
802        self.limiter.refill(mono_now);
803        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
804            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
805            return false;
806        }
807        // MRU->LRU order; reverse for the oldest-first lane so the preferred
808        // end is at the front.
809        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
810            .pending
811            .iter()
812            .enumerate()
813            .map(|(i, (p, e))| (i, *p, *e))
814            .collect();
815        self.pending.clear();
816        if self.oldest_first_lane {
817            ordered.reverse();
818        }
819        let mut chosen: Option<MonetizedPinEvent> = None;
820        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
821        for (idx, peer, event) in ordered {
822            if chosen.is_some() {
823                kept.push((idx, peer, event));
824                continue;
825            }
826            if self.first_audited.contains(&event.pin) {
827                obs.duplicates.fetch_add(1, Ordering::Relaxed);
828                continue; // drop: already audited
829            }
830            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
831                obs.outside_answerability_window
832                    .fetch_add(1, Ordering::Relaxed);
833                continue; // drop: cannot stay answerable through the jitter
834            }
835            // Window + budget + inflight. Tokens do not decrease during the
836            // scan (reserve happens after the loop) and `inflight` is fixed, so
837            // after the upfront budget gate `assess` never returns RateDeferred
838            // here; a defensive RateDeferred keeps the pin.
839            match self
840                .limiter
841                .assess(&peer, event.key_count, mono_now, inflight)
842            {
843                LimiterVerdict::WindowDeduped => {
844                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
845                    continue; // drop: recently first-audited, no count jump
846                }
847                LimiterVerdict::RateDeferred => {
848                    kept.push((idx, peer, event));
849                    continue; // keep (defensive; unreachable after upfront gate)
850                }
851                LimiterVerdict::Admit => {}
852            }
853            if !cooldown_would_allow(cooldown, &peer, mono_now) {
854                obs.cooldown_deferred_attempts
855                    .fetch_add(1, Ordering::Relaxed);
856                kept.push((idx, peer, event));
857                continue; // keep: on shared cooldown, retry later
858            }
859            chosen = Some(event);
860        }
861        // Restore relative recency (oldest re-put first -> newest stays MRU).
862        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
863        for (_, peer, event) in kept {
864            self.pending.put(peer, event);
865        }
866        let Some(event) = chosen else {
867            return false;
868        };
869        self.limiter.reserve_token();
870        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
871        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
872        self.reserved = Some(FirstAuditReservation {
873            event,
874            ready_at,
875            inflight: inflight_slot,
876        });
877        true
878    }
879
880    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
881    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
882        if self
883            .reserved
884            .as_ref()
885            .is_some_and(|r| mono_now >= r.ready_at)
886        {
887            self.reserved.take()
888        } else {
889            None
890        }
891    }
892
893    /// Authoritative promotion of a due reservation (E′). The caller holds the
894    /// shared cooldown write lock and passes the real send-time `wall_now` and
895    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
896    /// launch, or `None` when the launch was cancelled (answerability lapsed
897    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
898    /// On both `None` paths the token is refunded, the in-flight slot released,
899    /// and NO suppression is recorded.
900    ///
901    /// Known operational residual: suppression is stamped here, at promotion,
902    /// while the wire challenge is sent by the detached task the caller spawns
903    /// with the returned event. A task-start or encoding failure between the
904    /// two therefore leaves a stamped-but-unsent window. No remote input can
905    /// force that failure (it requires local task-spawn/alloc failure), so it
906    /// is accepted rather than closed; closing it would require stamping from
907    /// inside the spawned task and re-introduce the cancel-leaves-suppression
908    /// race this design exists to prevent.
909    fn resolve(
910        &mut self,
911        reservation: FirstAuditReservation,
912        wall_now: SystemTime,
913        mono_now: Instant,
914        cooldown: &mut HashMap<PeerId, Instant>,
915        obs: &Arc<FirstAuditObservability>,
916    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
917        let FirstAuditReservation {
918            event, inflight, ..
919        } = reservation;
920        // Authoritative answerability at the REAL send time.
921        if !quote_within_audit_window(event.quote_ts, wall_now) {
922            self.limiter.refund_token();
923            obs.outside_answerability_window
924                .fetch_add(1, Ordering::Relaxed);
925            drop(inflight);
926            return None; // cancelled; nothing stamped, nothing to roll back
927        }
928        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
929        // concurrent gossip audit requeues the reserved event through the SAME
930        // security-aware coalescing: the reserved event is OLDER than any
931        // same-peer successor (`incoming_is_newer = false`), so a higher-count
932        // reserved event still wins over a lower-count successor (the inflated
933        // pin must be audited), while an equal/higher successor is preserved.
934        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
935            self.limiter.refund_token();
936            obs.cooldown_deferred_attempts
937                .fetch_add(1, Ordering::Relaxed);
938            drop(inflight);
939            // Account for the requeue outcome (the nomination itself was already
940            // counted at ingress, so `queued` is not re-incremented): a capacity
941            // eviction of a DIFFERENT peer and a suppressed reserved event are
942            // both observable per the ADR funnel.
943            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
944                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
945                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
946                }
947                FirstAuditQueueOutcome::SuppressedLower => {
948                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
949                }
950                FirstAuditQueueOutcome::Queued
951                | FirstAuditQueueOutcome::Coalesced
952                | FirstAuditQueueOutcome::RetainedOnTie => {}
953            }
954            return None;
955        }
956        // Promote: stamp durable suppression, flip the lane, count the launch.
957        self.limiter.promote(event.peer, event.key_count, mono_now);
958        self.first_audited.put(event.pin, ());
959        self.oldest_first_lane = !self.oldest_first_lane;
960        obs.launched.fetch_add(1, Ordering::Relaxed);
961        Some((event, inflight))
962    }
963}
964
965// ---------------------------------------------------------------------------
966// Constants
967// ---------------------------------------------------------------------------
968
969/// Prefix used by saorsa-core's request-response mechanism.
970const RR_PREFIX: &str = "/rr/";
971
972/// Bounded handoff from the P2P broadcast receiver to serial non-audit
973/// replication processing.
974///
975/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
976/// bulk/non-audit messages here. If this fills, the message is **dropped** —
977/// `start_message_handler` must never block on a full queue, because a stalled
978/// receiver laps the P2P broadcast ring and silently loses messages it never
979/// observed. Every serial-lane class has protocol recovery, so a drop costs a
980/// retry rather than the message.
981///
982/// This bounds a message COUNT, but a queued item is an owned decoded message
983/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
984/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
985/// for: the lane carries small requests and challenges alongside
986/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
987/// right for both. Responses never reach here — `replication_payload_from_event`
988/// filters them out and their requesters correlate them. ADR-0005 decision 12
989/// records the trade and why byte accounting is the correct eventual fix.
990const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
991
992/// Maximum fresh-replication offers processed concurrently, away from the
993/// serial non-audit loop.
994///
995/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
996/// write. Four workers keep that latency off the responder dispatch path while
997/// keeping concurrent EVM/storage pressure small and predictable.
998const FRESH_OFFER_WORKER_LIMIT: usize = 4;
999
1000/// Maximum fresh offers admitted at once, counting both those running on a
1001/// worker and those queued for one.
1002///
1003/// An admitted offer holds its payload until it completes, so this bounds
1004/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1005/// Offers past the bound are refused rather than queued or handled inline —
1006/// handling one on the message loop stalls every other non-audit message behind
1007/// a payment verification and a multi-MiB write. A refusal is not free: the
1008/// sender does not read it, so it resurfaces as a missing key at the delayed
1009/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1010/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1011/// bound is sized to make refusal rare rather than cheap.
1012const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1013
1014/// Distinct payment proofs queued for one fresh-offer key.
1015///
1016/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1017/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1018/// chunk out to the close group, so a receiver sees the same key from about that
1019/// many senders. They differ only in their proof — the bytes are provably
1020/// identical, since `fresh_offer_structural_rejection` has confirmed
1021/// `key == BLAKE3(data)` before any of them is queued.
1022///
1023/// Sizing the queue to the number of legitimate senders is what lets a failing
1024/// proof fall through to the next one instead of costing the node the record.
1025///
1026/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1027/// admitted, and a proof the handler has popped has spent its slot rather than
1028/// returned it. That distinction is what bounds the work an attacker can buy —
1029/// at most this many on-chain verifications per key, after which the entry
1030/// refuses everyone until it closes. Gating on the queue's instantaneous length
1031/// instead would let a stream of distinct sources refill each popped slot and
1032/// run unbounded sequential verifications while holding one of the four worker
1033/// slots. One attempt per source additionally means a single peer can only ever
1034/// consume one of these.
1035const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1036
1037/// Fresh-offer slots kept reachable by sources that hold none.
1038///
1039/// The property worth guaranteeing is that one peer cannot *starve* others, not
1040/// that any peer is held to a small quota. Expressing the bound as a reserve
1041/// rather than a quota is what keeps those two apart.
1042const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1043
1044/// Maximum fresh offers admitted from one source peer.
1045///
1046/// Without a per-source bound, one peer can hold every slot in the global pool
1047/// and every honest offer arriving in that window is refused — and because a
1048/// refusal is later read as absence by the sender's delayed possession check,
1049/// those refusals land as audit-severity trust penalties on the *refuser*.
1050/// That makes an unbounded global pool a targeted eviction primitive.
1051///
1052/// The bound is deliberately far looser than the other responder classes'
1053/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1054/// the opposite shape. Those are request/response: a requester needs only a
1055/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1056/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1057/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1058/// for request/response traffic therefore binds on completely legitimate
1059/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1060/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1061/// ceiling and none to the global pool.
1062///
1063/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1064/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1065/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1066// The cast is from a compile-time constant difference of two small literals
1067// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1068// relationship visible in the code rather than only in a test.
1069#[allow(clippy::cast_possible_truncation)]
1070const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1071    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1072
1073/// Maximum paid-list notifications served concurrently.
1074///
1075/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1076/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1077/// Two workers keep cross-peer progress without multiplying concurrent EVM
1078/// and DHT lookup pressure.
1079const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1080
1081/// Maximum paid-list notifications admitted across workers and their waiters.
1082///
1083/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1084/// is one-way: the protocol defines no response and the sender never retries,
1085/// so a refused notify is information permanently lost to this node until a
1086/// later verification cycle happens to re-derive the key's paid status from a
1087/// paid-list quorum. A tight admission bound therefore does not shed load, it
1088/// discards durable state — which is why the class's real protection is
1089/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1090/// is actually expensive, rather than this queue depth.
1091///
1092/// A client PUT fans one notify per key out to the whole paid close group, so
1093/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1094/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1095/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1096/// carry no chunk payload.
1097const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1098
1099/// Maximum admitted paid-list notifications from one source peer.
1100///
1101/// A quarter of the pool. One peer legitimately supplies a whole upload's
1102/// worth of notifies, so this must comfortably exceed a typical file's chunk
1103/// count in flight; it exists to stop a single source evicting every other
1104/// peer's durable paid-list evidence, not to ration ordinary traffic.
1105const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1106
1107/// Maximum fetch responses served concurrently.
1108///
1109/// Each successful response can upload a 4 MiB chunk. Matching
1110/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1111/// simultaneous chunk data, which avoids saturating typical home upload links.
1112const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1113
1114/// Maximum fetch requests admitted across workers and their bounded waiters.
1115///
1116/// Four worker waves absorb short bursts without retaining chunk bytes—the
1117/// request contains only a key—while the dequeue deadline sheds work before a
1118/// sustained flood can keep the node serving requests whose callers timed out.
1119const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1120
1121/// Maximum admitted fetch requests from one source peer.
1122///
1123/// Two requests let one peer pipeline useful reads while leaving at least one
1124/// of the three workers available to other peers under a single-source flood.
1125const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1126
1127/// Maximum verification batches served concurrently.
1128///
1129/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1130/// workers isolate that synchronous work from message dispatch without turning
1131/// large batches into an I/O fan-out throughput contest.
1132const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1133
1134/// Maximum verification batches admitted across workers and bounded waiters.
1135///
1136/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1137/// deadline prevents queued batches from consuming lookup capacity after their
1138/// requesters have stopped waiting.
1139const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1140
1141/// Maximum admitted verification batches from one source peer.
1142///
1143/// Senders already aggregate a peer's keys into one batch. One outstanding
1144/// batch therefore preserves useful work while reserving the other worker and
1145/// the bounded queue for different peers.
1146const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1147
1148/// Maximum neighbor-sync requests served concurrently across source peers.
1149///
1150/// Building a response scans local keys and performs DHT lookups, so two
1151/// workers allow cross-peer progress without multiplying that expensive scan
1152/// into broad network and storage contention.
1153const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1154
1155/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1156///
1157/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1158/// payloads bounded; expired waiters are shed before any key scan begins.
1159const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1160
1161/// Maximum admitted neighbor-sync requests from one source peer.
1162///
1163/// Sync history must be updated before repair proofs for the same peer. A
1164/// single slot preserves that ordering while independent peers remain parallel.
1165const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1166
1167/// Match an inbound topic against the replication protocol ids, in both the bare
1168/// gossip form and the `/rr/<id>` request-response form.
1169///
1170/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1171/// was the RR form. The matched id is carried into the handler so it can enforce
1172/// that subtree messages only arrive on the subtree id.
1173fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1174    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1175        if topic == id {
1176            return Some((id, false));
1177        }
1178        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1179            if rest == id {
1180                return Some((id, true));
1181            }
1182        }
1183    }
1184    None
1185}
1186
1187/// Whether a decoded body belongs on the protocol id it arrived on:
1188/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1189/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1190///
1191/// The receive guard drops any mismatch (a cross-version or misrouted message);
1192/// sharing this one predicate between the guard and its regression test means a
1193/// change to the rule cannot pass the test unnoticed.
1194fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1195    protocol == response_protocol_for(body)
1196}
1197
1198/// The protocol id a body belongs on — the single source of truth for BOTH
1199/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1200/// response selector in `send_replication_response_checked`.
1201///
1202/// Sharing one function makes the subtree/core isolation symmetric.
1203fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1204    if body.is_subtree_audit() {
1205        SUBTREE_AUDIT_PROTOCOL_ID
1206    } else {
1207        REPLICATION_PROTOCOL_ID
1208    }
1209}
1210
1211fn fresh_offer_payment_context() -> VerificationContext {
1212    VerificationContext::FreshReplication
1213}
1214
1215fn paid_notify_payment_context() -> VerificationContext {
1216    VerificationContext::PaidListAdmission
1217}
1218
1219/// Boxed future type for in-flight fetch tasks.
1220type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1221
1222/// Fresh-offer keys currently being handled, each with the proofs still to try.
1223///
1224/// Concurrent duplicates are routine: a client PUT is confirmed by
1225/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1226/// commonly arrives from several senders at once. Collapsing them onto one
1227/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1228/// and an on-chain verification per copy.
1229///
1230/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1231/// refusing every later offer outright made the first arrival the only arrival:
1232/// if its proof failed, the record was lost even though a valid proof for the
1233/// same bytes was queued behind it, and the resulting absence was charged to
1234/// this node by the delayed possession check. So the entry holds the bytes once
1235/// and queues each sender's proof, and the handler works down that queue. A
1236/// later offer therefore costs a proof, not a payload — sound only because
1237/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1238/// every one of them before it is queued, which is what makes their bytes
1239/// provably identical.
1240///
1241/// Entries are exact keys rather than hash shards. A node only receives offers
1242/// for keys it is close to, so the accepted key set clusters tightly around its
1243/// own ID — any index derived from the key would land nearly every offer on one
1244/// shard and serialize unrelated keys behind each other. Exact keys keep them
1245/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1246/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1247///
1248/// The critical section is a map insert, pop, or remove and is never held across
1249/// an await, so this is a blocking mutex rather than an async one.
1250type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1251
1252/// One sender's unverified claim to have paid for a key already in flight.
1253///
1254/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1255/// content-address check ran before this attempt was queued.
1256struct FreshOfferAttempt {
1257    source: PeerId,
1258    proof_of_payment: Vec<u8>,
1259    request_id: u64,
1260    rr_message_id: Option<String>,
1261}
1262
1263/// Proofs still to try for one in-flight key, and who supplied them.
1264///
1265/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1266/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1267struct FreshOfferEntry {
1268    /// Untried proofs in arrival order. The handler holds the current one.
1269    pending: VecDeque<FreshOfferAttempt>,
1270    /// Sources already represented, so one peer cannot fill the queue alone.
1271    sources: HashSet<PeerId>,
1272    /// Proofs admitted over this entry's whole life, **never decremented**.
1273    ///
1274    /// The budget has to be spent by admissions rather than held by the queue.
1275    /// The handler pops a proof before verifying it, so gating on
1276    /// `pending.len()` would let a fresh source refill the slot that pop just
1277    /// freed, and a stream of distinct sources could then run unbounded
1278    /// sequential payment verifications while holding one of only four worker
1279    /// slots. Counting admissions makes the cap a lifetime budget instead.
1280    admitted: usize,
1281}
1282
1283/// How an arriving fresh offer joined the work already in flight for its key.
1284enum FreshOfferAdmission {
1285    /// Opened the entry. This offer's handler owns the key and drives every
1286    /// queued proof, including proofs that arrive later.
1287    Opened(Box<FreshOfferEntryGuard>),
1288    /// Merged into an entry another offer opened; its handler reaches this proof
1289    /// if the ones ahead of it fail.
1290    Joined,
1291    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1292    Full,
1293    /// This source already has a proof queued for this key.
1294    DuplicateSource,
1295}
1296
1297// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1298// `debug!`, which compiles to nothing without the feature.
1299#[cfg(feature = "logging")]
1300impl FreshOfferAdmission {
1301    /// Why the offer added nothing to the work already queued for its key.
1302    ///
1303    /// Local logging only — the wire reason stays uniform so a probing peer
1304    /// cannot tell a full queue from a repeat of its own proof.
1305    const fn surplus_reason(&self) -> &'static str {
1306        match self {
1307            Self::DuplicateSource => "this source already has a proof queued",
1308            Self::Full => "the key already holds its full complement of proofs",
1309            Self::Opened(_) | Self::Joined => "not surplus",
1310        }
1311    }
1312}
1313
1314/// RAII ownership of one in-flight fresh-offer key.
1315///
1316/// Clears the entry on drop, so an early return, an error, or a panic cannot
1317/// strand a key as permanently in flight. Also owns the single copy of the
1318/// offered bytes that every queued proof is tried against.
1319struct FreshOfferEntryGuard {
1320    in_flight: FreshOfferInFlight,
1321    key: XorName,
1322    /// The bytes every attempt for this key shares, held exactly once.
1323    data: Vec<u8>,
1324    /// Arrival of the offer that opened the entry.
1325    received_at: Instant,
1326    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1327    /// a *later* offer has since opened for the same key.
1328    holds_entry: bool,
1329}
1330
1331impl FreshOfferEntryGuard {
1332    /// Open an entry for this offer's key, or queue its proof behind the entry
1333    /// already open.
1334    ///
1335    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1336    /// on every other outcome they are dropped here rather than held for the
1337    /// lifetime of the entry.
1338    fn admit(
1339        in_flight: &FreshOfferInFlight,
1340        offer: protocol::FreshReplicationOffer,
1341        source: PeerId,
1342        request_id: u64,
1343        rr_message_id: Option<String>,
1344        received_at: Instant,
1345    ) -> FreshOfferAdmission {
1346        let key = offer.key;
1347        let attempt = FreshOfferAttempt {
1348            source,
1349            proof_of_payment: offer.proof_of_payment,
1350            request_id,
1351            rr_message_id,
1352        };
1353
1354        let mut in_flight_map = in_flight.lock();
1355        if let Some(entry) = in_flight_map.get_mut(&key) {
1356            if entry.sources.contains(&source) {
1357                return FreshOfferAdmission::DuplicateSource;
1358            }
1359            // Lifetime budget, not queue depth: a proof the handler has already
1360            // popped has spent its slot, not returned it.
1361            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1362                return FreshOfferAdmission::Full;
1363            }
1364            entry.admitted = entry.admitted.saturating_add(1);
1365            entry.sources.insert(source);
1366            entry.pending.push_back(attempt);
1367            return FreshOfferAdmission::Joined;
1368        }
1369
1370        let mut sources = HashSet::new();
1371        sources.insert(source);
1372        let mut pending = VecDeque::new();
1373        pending.push_back(attempt);
1374        in_flight_map.insert(
1375            key,
1376            FreshOfferEntry {
1377                pending,
1378                sources,
1379                admitted: 1,
1380            },
1381        );
1382        drop(in_flight_map);
1383        FreshOfferAdmission::Opened(Box::new(Self {
1384            in_flight: Arc::clone(in_flight),
1385            key,
1386            data: offer.data,
1387            received_at,
1388            holds_entry: true,
1389        }))
1390    }
1391
1392    /// The bytes every proof for this key is tried against.
1393    fn data(&self) -> &[u8] {
1394        &self.data
1395    }
1396
1397    /// When the first offer for this key arrived.
1398    fn received_at(&self) -> Instant {
1399        self.received_at
1400    }
1401
1402    /// Take the next untried proof, releasing the key when none remain.
1403    ///
1404    /// Popping and releasing happen under one lock so a proof arriving exactly
1405    /// as the queue empties is never silently discarded: it either lands in this
1406    /// entry and is returned here, or finds no entry and opens its own.
1407    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1408        let mut in_flight = self.in_flight.lock();
1409        let Some(entry) = in_flight.get_mut(&self.key) else {
1410            self.holds_entry = false;
1411            return None;
1412        };
1413        if let Some(attempt) = entry.pending.pop_front() {
1414            return Some(attempt);
1415        }
1416        in_flight.remove(&self.key);
1417        self.holds_entry = false;
1418        None
1419    }
1420
1421    /// Release the key and return the proofs that were never tried, so their
1422    /// senders can be told the outcome the key reached without them.
1423    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1424        let mut in_flight = self.in_flight.lock();
1425        self.holds_entry = false;
1426        in_flight
1427            .remove(&self.key)
1428            .map(|entry| entry.pending.into_iter().collect())
1429            .unwrap_or_default()
1430    }
1431}
1432
1433impl Drop for FreshOfferEntryGuard {
1434    fn drop(&mut self) {
1435        if self.holds_entry {
1436            self.in_flight.lock().remove(&self.key);
1437        }
1438    }
1439}
1440
1441/// Shared dependencies for one verification worker cycle.
1442struct VerificationCycleContext<'a> {
1443    p2p_node: &'a Arc<P2PNode>,
1444    paid_list: &'a Arc<PaidList>,
1445    storage: &'a Arc<ChunkStore>,
1446    queues: &'a Arc<RwLock<ReplicationQueues>>,
1447    config: &'a ReplicationConfig,
1448    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1449    is_bootstrapping: &'a Arc<RwLock<bool>>,
1450    bootstrap_complete_notify: &'a Arc<Notify>,
1451    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1452    /// peer's Present claim to Unresolved unless they're a credited
1453    /// holder of the key (i.e. they recently passed a commitment-bound
1454    /// audit on it under their currently-credited commitment hash).
1455    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1456    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1457    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1458}
1459
1460/// Fetch worker polling interval in milliseconds.
1461const FETCH_WORKER_POLL_MS: u64 = 100;
1462
1463/// Verification worker polling interval in milliseconds.
1464const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1465
1466/// Verification cycle duration that is worth surfacing at info level.
1467const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1468
1469/// Standard trust event weight for per-operation success/failure signals.
1470///
1471/// Used for individual replication fetch outcomes, integrity check failures,
1472/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1473/// is reserved for confirmed audit failures.
1474const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1475/// Bound trust updates from one verification cycle. A malicious peer can
1476/// advertise thousands of bad singleton keys at once; a few independent
1477/// contradictions are enough for the trust engine without flooding it.
1478const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1479
1480/// Bootstrap drain check interval in seconds.
1481const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1482
1483/// Grace period `shutdown()` waits for each long-lived background task to
1484/// observe the cancellation token and terminate before aborting it.
1485///
1486/// Detached tasks are drained without a timeout because storage-capable work
1487/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1488/// if its async waiter is dropped.
1489const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1490
1491/// How often the responder rebuilds + rotates its storage commitment.
1492///
1493/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1494/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1495/// rotation-anchored: the responder stays answerable for the current
1496/// commitment plus every root it recently gossiped that is still in-window
1497/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1498/// its last emission (see `commitment_state`). So the rotation cadence does
1499/// not by itself bound answerability — a gossiped commitment stays
1500/// answerable across rotations until its gossip TTL lapses.
1501///
1502/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1503/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1504/// comfortably exceeds the gap between our rotation and the next gossip
1505/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1506/// Idle audit-skip pattern from being the common case.
1507///
1508/// Why not faster: the v12 pin is bound to a specific point-in-time
1509/// commitment, so rotation isn't security-critical for pin freshness —
1510/// only for keeping the committed key set current as the responder
1511/// writes new keys. 1 hour is plenty for that, and slow enough that
1512/// honest auditors mostly hit `current` or `previous` rather than the
1513/// "rotated past" case.
1514const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1515
1516/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1517/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1518/// durable well before it could matter to a restart, while the write-on-change
1519/// guard keeps idle nodes from needless disk writes.
1520const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1521
1522/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1523/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1524/// default that keeps log volume negligible.
1525const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1526
1527/// Cadence of the read-only bootstrap state snapshot used to separate drain
1528/// debt from cache and broader connectivity failures in fleet logs.
1529#[cfg(feature = "logging")]
1530const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1531
1532/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1533/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1534/// for first audit only if its SIGNED `quote_ts` lands in
1535/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1536/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1537/// badly-skewed or replayed quote) and one too old (the responder may have aged
1538/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1539/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1540/// within this margin); a legit first audit fires moments after payment
1541/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1542/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1543/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1544const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_mins(30);
1545
1546/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1547/// inside the answerability window relative to `now`, so first-auditing it cannot
1548/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1549/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1550/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1551/// All comparisons use `duration_since` (no `Duration` overflow).
1552fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1553    let too_future = quote_ts
1554        .duration_since(now)
1555        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1556    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1557    let too_old = now
1558        .duration_since(quote_ts)
1559        .is_ok_and(|age| age >= audit_cutoff);
1560    !(too_future || too_old)
1561}
1562
1563/// Minimum interval between commitment signature verifications for a
1564/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1565///
1566/// A sybil that bypasses the routing-table gate (e.g. by transient
1567/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1568/// per gossip message. This rate limit caps the verify-per-peer rate
1569/// at 1/min, which is comfortably above the legitimate gossip cadence
1570/// (the 10-20 min neighbor-sync round on each peer).
1571const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_mins(1);
1572
1573/// Hard cap on the size of `last_commitment_by_peer`.
1574///
1575/// Bounds the per-process memory cost of the auditor's per-peer
1576/// commitment cache. Each entry holds a `StorageCommitment`
1577/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1578/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1579/// realistic close-group neighborhood. When the cap is hit, one
1580/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1581/// order is unspecified; we do not track insertion order). The
1582/// `PeerRemoved` handler proactively drops entries as the DHT
1583/// detects departures, and `ingest_peer_commitment` only admits
1584/// commitments from peers currently in the routing table — together
1585/// the cap is the third line of defence against sybil/churn flooding.
1586const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1587
1588/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1589/// sized to the launch budget instead of the commitment cache.
1590///
1591/// The token bucket can launch at most one audit per
1592/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1593/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1594/// launchable for at most the effective answerability window
1595/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1596/// occupancy beyond `window / interval + burst` is work that cannot launch
1597/// before it expires, so admitting it only builds an aging backlog whose
1598/// telemetry measures the backlog instead of schedulable work.
1599///
1600/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1601/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1602/// rolling sample in which no arrival order lets an attacker deterministically
1603/// flush a chosen target; a fresh pin always enters the sample with an
1604/// unpredictable chance of near-immediate audit, whereas refusing at the door
1605/// would let a sustained payment flood guarantee that every later pin is never
1606/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1607/// ADR-0004 Amendment 4 for the eviction-cost math.
1608///
1609/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1610/// is usable only if the quote stays answerable through `a` plus the maximum
1611/// launch jitter and send slack, so the last usable refill is the largest
1612/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1613/// simulates the shipped predicate instant-by-instant and must agree.
1614#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1615const FIRST_AUDIT_PENDING_CAP: usize = {
1616    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1617        .as_secs()
1618        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1619        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1620        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1621    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1622    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1623    // if the launch interval is ever zeroed: a zero interval makes the budget
1624    // (and this cap) meaningless.
1625    let refills =
1626        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1627    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1628};
1629
1630// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1631// strictly tighter than the commitment-cache bound it replaced.
1632const _: () = {
1633    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1634    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1635};
1636
1637/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1638/// long-running bootstrap node cannot have the set grow without limit
1639/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1640/// the set comfortably outlives normal LRU churn but still caps the
1641/// blast radius of identity-rotation attacks. Once full we refuse new
1642/// inserts (no eviction) — keeps the historic set stable; new v12
1643/// peers above the cap are treated as legacy on rejoin, which matches
1644/// the behaviour before this set existed, not a security regression.
1645const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1646
1647// ---------------------------------------------------------------------------
1648// ReplicationEngine
1649// ---------------------------------------------------------------------------
1650
1651/// The replication engine manages all replication background tasks and state.
1652pub struct ReplicationEngine {
1653    /// Replication configuration (shared across spawned tasks).
1654    config: Arc<ReplicationConfig>,
1655    /// P2P networking node.
1656    p2p_node: Arc<P2PNode>,
1657    /// Local chunk storage.
1658    storage: Arc<ChunkStore>,
1659    /// Persistent paid-for-list.
1660    paid_list: Arc<PaidList>,
1661    /// Payment verifier for `PoP` validation.
1662    payment_verifier: Arc<PaymentVerifier>,
1663    /// Replication pipeline queues.
1664    queues: Arc<RwLock<ReplicationQueues>>,
1665    /// Neighbor sync cycle state.
1666    sync_state: Arc<RwLock<NeighborSyncState>>,
1667    /// Per-peer sync history (for `RepairOpportunity`).
1668    ///
1669    /// This map grows with peer churn and is intentionally unbounded: entries
1670    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1671    /// naturally bounded by the routing table's k-bucket capacity.
1672    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1673    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1674    ///
1675    /// Records when each peer was last audited so a burst of gossiped
1676    /// commitment changes cannot spawn back-to-back audits of the same peer.
1677    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1678    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679    /// Gossip-private lottery attempt window (one roll per peer per window,
1680    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1681    /// ticket never stamps the shared map and thus never defers a monetized
1682    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1683    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1684    /// Completed local neighbor-sync cycle epoch for proof maturity.
1685    sync_cycle_epoch: Arc<RwLock<u64>>,
1686    /// Per-key repair proof tracking for audit eligibility.
1687    repair_proofs: Arc<RwLock<RepairProofs>>,
1688    /// Bootstrap state tracking.
1689    bootstrap_state: Arc<RwLock<BootstrapState>>,
1690    /// Whether this node is currently bootstrapping.
1691    is_bootstrapping: Arc<RwLock<bool>>,
1692    /// Trigger for early neighbor sync (signalled on topology changes).
1693    sync_trigger: Arc<Notify>,
1694    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1695    bootstrap_complete_notify: Arc<Notify>,
1696    /// Node identity (for signing storage commitments).
1697    ///
1698    /// Phase 3 of the v12 storage-bound audit design. The responder
1699    /// uses this to sign its periodically-built `StorageCommitment`.
1700    identity: Arc<NodeIdentity>,
1701    /// Responder-side commitment state (two-slot atomic rotation).
1702    ///
1703    /// Periodically rebuilt from the live LMDB key set; gossiped on
1704    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1705    /// commitment-bound audit handler.
1706    commitment_state: Arc<ResponderCommitmentState>,
1707    /// Path to the persisted responder retention snapshot
1708    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1709    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1710    /// removing audit grace safe (an unanswerable in-window pin is then provable
1711    /// misbehaviour, not an honest crash-restart).
1712    retention_path: PathBuf,
1713    /// Auditor-side per-peer commitment record (last known commitment +
1714    /// sticky `commitment_capable` flag).
1715    ///
1716    /// Populated whenever an inbound gossip carries a verified
1717    /// commitment from the sender. Used by `audit_tick` to snapshot
1718    /// `expected_commitment_hash` into outbound challenges, and by
1719    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1720    /// proof should be honoured. The sticky `commitment_capable` flag
1721    /// flips true on first successful ingest and never reverts (§2
1722    /// step 5).
1723    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1724    /// Sticky set of peer IDs we have EVER seen carrying a v12
1725    /// commitment, independent of whether their commitment bytes are
1726    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1727    /// closure consults this set to keep treating churned-out
1728    /// previously-v12 peers as v12-capable (rather than degrading them
1729    /// to "legacy" credit-unconditionally) when they re-appear on the
1730    /// network before their next gossip arrives. Bounded growth: even
1731    /// at one million peers seen over the node's lifetime, the set is
1732    /// 32 MB.
1733    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1734    /// Auditor-side holder-eligibility cache (v12 §6).
1735    ///
1736    /// Recorded on successful commitment-bound audit; read by future
1737    /// quorum / paid-list eligibility checks (phase-3 stretch).
1738    recent_provers: Arc<RwLock<RecentProvers>>,
1739    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1740    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1741    /// failure) so a peer we've never successfully verified can't burn
1742    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1743    /// Lives separately from `last_commitment_by_peer` because that
1744    /// map's records only exist after a successful verify.
1745    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1746    /// Limits concurrent outbound replication sends to prevent bandwidth
1747    /// saturation on home broadband connections.
1748    send_semaphore: Arc<Semaphore>,
1749    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1750    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1751    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1752    /// message loop so disk
1753    /// reads don't block replication; the semaphore restores a global
1754    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1755    /// / multi-MiB byte serves.
1756    audit_responder_semaphore: Arc<Semaphore>,
1757    /// Per-source in-flight audit-responder counts, capped at
1758    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1759    /// flood-fair: one peer spamming challenges could occupy every slot and
1760    /// starve honest auditors, whose dropped challenges then convert to
1761    /// audit timeouts against HONEST peers (codex-r2 A). This
1762    /// per-peer cap guarantees no single source can hold more than its share,
1763    /// so a flood self-throttles without denying service to everyone else.
1764    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1765    /// Windowed per-origin capacity and processing-time telemetry for every
1766    /// request sharing the audit responder pool.
1767    audit_responder_metrics: Arc<AuditResponderMetrics>,
1768    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1769    ///
1770    /// Responsible-chunk audits, prune confirmations, and possession checks
1771    /// all use this before sending so local bursts wait instead of breaching
1772    /// the responder's deployed per-source admission cap.
1773    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1774    /// Worker permits for bandwidth-bound fetch responses.
1775    fetch_responder_worker_semaphore: Arc<Semaphore>,
1776    /// Admission permits bounding fetch workers and queued waiters together.
1777    fetch_responder_admission_semaphore: Arc<Semaphore>,
1778    /// Per-source fetch responder counts for flood-fair admission.
1779    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1780    /// Worker permits for lookup-heavy verification batches.
1781    verification_responder_worker_semaphore: Arc<Semaphore>,
1782    /// Admission permits bounding verification workers and queued waiters.
1783    verification_responder_admission_semaphore: Arc<Semaphore>,
1784    /// Per-source verification responder counts for flood-fair admission.
1785    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1786    /// Worker permits for expensive inbound neighbor-sync requests.
1787    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1788    /// Admission permits bounding sync workers and queued waiters together.
1789    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1790    /// Per-source sync responder counts; capped at one to preserve ordering.
1791    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1792    /// Bounded worker permits for expensive fresh-offer handling.
1793    fresh_offer_worker_semaphore: Arc<Semaphore>,
1794    /// Admission permits bounding offers running on a worker or queued for one.
1795    fresh_offer_admission_semaphore: Arc<Semaphore>,
1796    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1797    /// and turn honest senders' refusals into trust penalties on this node.
1798    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1799    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1800    /// duplicates collapse onto one verification and one write.
1801    fresh_offer_in_flight: FreshOfferInFlight,
1802    /// Bounded worker permits for paid-list notification proof verification.
1803    paid_notify_worker_semaphore: Arc<Semaphore>,
1804    /// Admission permits bounding notifies on a worker or queued for one.
1805    paid_notify_admission_semaphore: Arc<Semaphore>,
1806    /// Per-source paid-notify counts for flood-fair admission.
1807    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1808    /// Resource controls for the HEAVY subtree-audit round 1: its own
1809    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1810    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1811    /// sessions binding a slice challenge to a matching round 1.
1812    subtree_round1: SubtreeRound1Limiter,
1813    /// Receiver for fresh-write events from the chunk PUT handler.
1814    ///
1815    /// When present, `start()` spawns a drainer task that calls
1816    /// `replicate_fresh` for each event.
1817    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1818    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1819    /// drainer pushes the responsible close-group peers here after each fresh
1820    /// replication; the possession-check scheduler drains the paired receiver.
1821    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1822    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1823    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1824    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1825    /// for a deterministic first audit. The matching receiver is drained by
1826    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1827    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1828    /// like launches; a dropped nomination is penalty-free — the peer's
1829    /// gossiped commitments stay lottery-covered and its next settled payment
1830    /// re-nominates the paid pin.
1831    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1832    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1833    /// `start_first_audit_drainer`.
1834    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1835    /// Counters shared with the first-audit drainer task, so the scheduler's
1836    /// decisions (queued / launched / self-target skipped / outcome) stay
1837    /// observable from the engine after the drainer takes the receiver.
1838    first_audit_observability: Arc<FirstAuditObservability>,
1839    /// Shutdown token.
1840    shutdown: CancellationToken,
1841    /// Background task handles.
1842    task_handles: Vec<JoinHandle<()>>,
1843    /// Tracks detached, short-lived work spawned by background producers.
1844    ///
1845    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1846    /// tasks, and delayed possession checks may retain storage or P2P state
1847    /// after their producer exits, so shutdown drains them before those
1848    /// resources may be reopened.
1849    detached_task_tracker: TaskTracker,
1850}
1851
1852impl ReplicationEngine {
1853    /// Create a new replication engine.
1854    ///
1855    /// # Errors
1856    ///
1857    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1858    /// or if the configuration fails validation.
1859    #[allow(clippy::too_many_arguments)]
1860    pub async fn new(
1861        config: ReplicationConfig,
1862        p2p_node: Arc<P2PNode>,
1863        storage: Arc<ChunkStore>,
1864        payment_verifier: Arc<PaymentVerifier>,
1865        identity: Arc<NodeIdentity>,
1866        root_dir: &Path,
1867        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1868        shutdown: CancellationToken,
1869    ) -> Result<Self> {
1870        config.validate().map_err(Error::Config)?;
1871
1872        let paid_list = Arc::new(
1873            PaidList::new(root_dir)
1874                .await
1875                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1876        );
1877
1878        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1879        let config = Arc::new(config);
1880        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1881
1882        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1883        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1884        // now capacity-limited — ingress queue here, pending set (LRU), and
1885        // launch rate (token bucket).
1886        let (monetized_pin_tx, monetized_pin_rx) =
1887            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1888
1889        let engine = Self {
1890            config: Arc::clone(&config),
1891            p2p_node,
1892            storage,
1893            paid_list,
1894            payment_verifier,
1895            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1896            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1897            sync_history: Arc::new(RwLock::new(HashMap::new())),
1898            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1899            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1900            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1901            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1902            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1903            is_bootstrapping: Arc::new(RwLock::new(true)),
1904            sync_trigger: Arc::new(Notify::new()),
1905            bootstrap_complete_notify: Arc::new(Notify::new()),
1906            identity,
1907            commitment_state: Arc::new(ResponderCommitmentState::new()),
1908            retention_path: root_dir.join("commitment_retention.bin"),
1909            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1910            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1911            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1912            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1913            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1914            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1915            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1916            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1917            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1918            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1919                FETCH_RESPONDER_WORKER_LIMIT,
1920            )),
1921            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1922                FETCH_RESPONDER_MAX_OUTSTANDING,
1923            )),
1924            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1925            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1926                VERIFICATION_RESPONDER_WORKER_LIMIT,
1927            )),
1928            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1929                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1930            )),
1931            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1932            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1933                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1934            )),
1935            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1936                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1937            )),
1938            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1939            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1940            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1941            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1942            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1943            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1944            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1945            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1946            subtree_round1: SubtreeRound1Limiter::new(
1947                config.subtree_round1_responder_cooldown,
1948                config.subtree_round1_max_concurrent,
1949            ),
1950            fresh_write_rx: Some(fresh_write_rx),
1951            possession_check_tx,
1952            possession_check_rx: Some(possession_check_rx),
1953            monetized_pin_tx,
1954            monetized_pin_rx: Some(monetized_pin_rx),
1955            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1956            shutdown,
1957            task_handles: Vec::new(),
1958            detached_task_tracker: TaskTracker::new(),
1959        };
1960        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1961        // spawns, so an honest restarted node is answerable for its pre-restart
1962        // pins from the first audit it serves, and the persist loop never races
1963        // an empty snapshot over the good on-disk file.
1964        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1965        Ok(engine)
1966    }
1967
1968    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1969    /// (commitments that backed a payment) for a first audit. Cloneable; the
1970    /// engine drains the matching receiver. Bounded: senders must `try_send`
1971    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1972    #[must_use]
1973    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1974        self.monetized_pin_tx.clone()
1975    }
1976
1977    /// Get a reference to the `PaidList`.
1978    #[must_use]
1979    pub fn paid_list(&self) -> &Arc<PaidList> {
1980        &self.paid_list
1981    }
1982
1983    /// Get a reference to the responder's commitment state. Used by audit
1984    /// handlers to look up commitments by hash; used by the rotation tick
1985    /// to install fresh ones.
1986    #[must_use]
1987    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1988        &self.commitment_state
1989    }
1990
1991    /// Neighbour-sync state, for the storage migration's possession challenges.
1992    #[must_use]
1993    pub fn sync_state(&self) -> &Arc<RwLock<NeighborSyncState>> {
1994        &self.sync_state
1995    }
1996
1997    /// The audit-challenge coordinator, for the storage migration's possession challenges.
1998    #[must_use]
1999    pub fn audit_challenge_coordinator(&self) -> &Arc<AuditChallengeCoordinator> {
2000        &self.audit_challenge_coordinator
2001    }
2002
2003    /// Replication settings, for the storage migration's possession challenges.
2004    #[must_use]
2005    pub fn config(&self) -> &Arc<ReplicationConfig> {
2006        &self.config
2007    }
2008
2009    /// Get a reference to the auditor's last-commitment-by-peer table.
2010    #[must_use]
2011    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2012        &self.last_commitment_by_peer
2013    }
2014
2015    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2016    /// will be read by quorum / paid-list eligibility checks.
2017    #[must_use]
2018    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2019        &self.recent_provers
2020    }
2021
2022    /// Test-only: rebuild + rotate this node's storage commitment now over its
2023    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2024    /// just stored without waiting for the rotation cadence.
2025    ///
2026    /// # Errors
2027    ///
2028    /// Propagates any error from reading the local key set or building/signing
2029    /// the commitment.
2030    #[cfg(any(test, feature = "test-utils"))]
2031    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2032        rebuild_and_rotate_commitment(
2033            &self.storage,
2034            &self.identity,
2035            &self.commitment_state,
2036            &self.p2p_node,
2037            &self.config,
2038        )
2039        .await
2040    }
2041
2042    /// Test-only: directly seed this node's cached commitment for `peer`,
2043    /// simulating "we received `peer`'s gossiped commitment" without depending
2044    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2045    /// peer's commitment deterministically.
2046    #[cfg(any(feature = "test-utils", test))]
2047    pub async fn inject_peer_commitment_for_test(
2048        &self,
2049        peer: &PeerId,
2050        commitment: StorageCommitment,
2051    ) {
2052        let now = Instant::now();
2053        self.last_commitment_by_peer
2054            .write()
2055            .await
2056            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2057        self.ever_capable_peers.write().await.insert(*peer);
2058    }
2059
2060    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2061    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2062    /// window and clears any shared cooldown stamped by an earlier gossip
2063    /// launch. The locks follow the production gossip-audit lock order.
2064    #[cfg(any(test, feature = "test-utils"))]
2065    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2066        let now = Instant::now();
2067        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2068        let mut launched = self.audit_on_gossip_cooldown.write().await;
2069        lottery_attempts.insert(*peer, now);
2070        launched.remove(peer);
2071    }
2072
2073    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2074    /// commitment this node has cached for it (from gossip), over the live wire.
2075    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2076    /// in a real two-node setting without waiting for the gossip cadence.
2077    ///
2078    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2079    /// peer yet (gossip hasn't reached us). Gated to test builds.
2080    #[cfg(any(test, feature = "test-utils"))]
2081    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2082        let target = {
2083            let map = self.last_commitment_by_peer.read().await;
2084            map.get(peer)
2085                .and_then(PeerCommitmentRecord::last_commitment)
2086                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2087        };
2088        let Some((pin, key_count)) = target else {
2089            return audit::AuditTickResult::Idle;
2090        };
2091        let credit = storage_commitment_audit::AuditCredit {
2092            recent_provers: &self.recent_provers,
2093        };
2094        storage_commitment_audit::run_subtree_audit(
2095            &self.p2p_node,
2096            &self.config,
2097            peer,
2098            pin,
2099            key_count,
2100            Some(&credit),
2101        )
2102        .await
2103    }
2104
2105    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2106    /// tests assert what the live drainer decided for an injected
2107    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2108    #[cfg(any(test, feature = "test-utils"))]
2109    #[must_use]
2110    pub fn first_audit_stats(&self) -> FirstAuditStats {
2111        let o = &self.first_audit_observability;
2112        FirstAuditStats {
2113            received: o.received.load(Ordering::Relaxed),
2114            queued: o.queued.load(Ordering::Relaxed),
2115            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2116            launched: o.launched.load(Ordering::Relaxed),
2117            passed: o.passed.load(Ordering::Relaxed),
2118            timed_out: o.timed_out.load(Ordering::Relaxed),
2119            failed: o.failed.load(Ordering::Relaxed),
2120        }
2121    }
2122
2123    /// Test-only: run the possession check immediately for `key` against
2124    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2125    ///
2126    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2127    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2128    /// deterministically without waiting for the scheduled check.
2129    #[cfg(any(test, feature = "test-utils"))]
2130    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2131        possession::run_possession_check(
2132            key,
2133            peers,
2134            &self.p2p_node,
2135            &self.storage,
2136            &self.config,
2137            &self.sync_state,
2138            &self.audit_challenge_coordinator,
2139            &self.shutdown,
2140        )
2141        .await;
2142    }
2143
2144    /// Test-only: place `key` directly into the fetch queue as though a
2145    /// verification cycle had just promoted it, with `sources` as its
2146    /// verified holders. Returns whether the key was enqueued.
2147    ///
2148    /// Bypasses admission, verification, and the promotion-time
2149    /// responsibility pre-filter, modelling a promotion decision that has
2150    /// since gone stale (topology churn between promotion and download).
2151    /// The only guard left standing is the per-attempt recheck inside
2152    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2153    /// exercise.
2154    #[cfg(any(test, feature = "test-utils"))]
2155    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2156        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2157        self.queues
2158            .write()
2159            .await
2160            .enqueue_fetch(key, distance, sources)
2161    }
2162
2163    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2164    /// (pending verification, fetch queue, or in-flight fetch).
2165    #[cfg(any(test, feature = "test-utils"))]
2166    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2167        self.queues.read().await.contains_key(key)
2168    }
2169
2170    /// Test-only: place `key` into pending verification as though `hinter` had
2171    /// just advertised it with a replica hint. Returns whether it was admitted.
2172    ///
2173    /// Enters the pipeline one stage earlier than
2174    /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2175    /// decides about the key is observable.
2176    #[cfg(any(test, feature = "test-utils"))]
2177    pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2178        let now = Instant::now();
2179        let entry = VerificationEntry {
2180            state: VerificationState::PendingVerify,
2181            verified_sources: Vec::new(),
2182            tried_sources: HashSet::new(),
2183            created_at: now,
2184            next_verify_at: now,
2185            hint_sources: HashSet::from([hinter]),
2186            replica_hint_sources: HashSet::from([hinter]),
2187            unresolved_retries: 0,
2188            no_holder_reported: false,
2189        };
2190        self.queues
2191            .write()
2192            .await
2193            .add_pending_verify(key, entry)
2194            .admitted()
2195    }
2196
2197    /// Test-only: how far ahead `key`'s next verification round is scheduled,
2198    /// or `None` when the key is not pending verification.
2199    #[cfg(any(test, feature = "test-utils"))]
2200    pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2201        self.queues.read().await.get_pending(key).map(|entry| {
2202            entry
2203                .next_verify_at
2204                .saturating_duration_since(Instant::now())
2205        })
2206    }
2207
2208    /// Start all background tasks.
2209    ///
2210    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2211    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2212    /// missed by the bootstrap-sync gate.
2213    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2214        if !self.task_handles.is_empty() {
2215            error!("ReplicationEngine::start() called while already running — ignoring");
2216            return;
2217        }
2218        info!("Starting replication engine");
2219
2220        self.start_message_handler();
2221        self.start_neighbor_sync_loop();
2222        self.start_self_lookup_loop();
2223        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2224        // chunks they SHOULD store (responsibility + prior hint).
2225        self.start_audit_loop();
2226        // Audit #1 (storage-commitment) is gossip-triggered in the message
2227        // handler when a peer's commitment is ingested, not on a periodic tick.
2228        self.start_commitment_rotation_loop();
2229        self.start_retention_persist_loop();
2230        self.start_fetch_worker();
2231        self.start_verification_worker();
2232        self.start_bootstrap_sync(dht_events);
2233        self.start_fresh_write_drainer();
2234        self.start_possession_check_scheduler();
2235        // ADR-0004: deterministic first audit of commitments that backed a
2236        // payment (surfaced by the verifier cross-check).
2237        self.start_first_audit_drainer();
2238        // V2-623: periodic cumulative per-variant traffic accounting.
2239        self.start_traffic_summary_loop();
2240        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2241        #[cfg(feature = "logging")]
2242        self.start_bootstrap_state_snapshot_loop();
2243        #[cfg(feature = "logging")]
2244        self.start_audit_responder_summary_loop();
2245
2246        info!(
2247            "Replication engine started with {} background tasks",
2248            self.task_handles.len()
2249        );
2250    }
2251
2252    /// Returns `true` if the node is still in the replication bootstrap phase.
2253    ///
2254    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2255    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2256    pub async fn is_bootstrapping(&self) -> bool {
2257        *self.is_bootstrapping.read().await
2258    }
2259
2260    /// Wait until the replication bootstrap phase completes.
2261    ///
2262    /// Returns immediately if bootstrap has already completed. Useful for
2263    /// readiness probes, health checks, and test harnesses that need the
2264    /// node to be fully operational before proceeding.
2265    ///
2266    /// Returns `true` if bootstrap completed within the timeout, `false`
2267    /// if the timeout elapsed first.
2268    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2269        // Register the notification future *before* checking the flag so that
2270        // a transition between the read and the await is not missed.
2271        let notified = self.bootstrap_complete_notify.notified();
2272        tokio::pin!(notified);
2273        notified.as_mut().enable();
2274
2275        if !*self.is_bootstrapping.read().await {
2276            return true;
2277        }
2278
2279        tokio::time::timeout(timeout, notified).await.is_ok()
2280    }
2281
2282    /// Cancel all background tasks and wait for them to terminate.
2283    ///
2284    /// This must be awaited before dropping the engine when the caller needs
2285    /// the `Arc<ChunkStore>` references held by background tasks to be
2286    /// released (e.g. before reopening the same LMDB environment).
2287    ///
2288    /// When this returns, no engine-spawned task still holds
2289    /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no LMDB blocking operation
2290    /// (read or write, on either the chunk store or the paid-list
2291    /// environment) is still running.  Engine tasks race their work against
2292    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2293    /// LMDB transaction running detached, so this method additionally waits
2294    /// for both storage layers to go quiescent before returning.
2295    pub async fn shutdown(&mut self) {
2296        self.shutdown.cancel();
2297        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2298            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2299                Ok(Ok(())) => {}
2300                Ok(Err(e)) if e.is_cancelled() => {}
2301                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2302                Err(_) => {
2303                    warn!(
2304                        "Replication task {i} did not stop within {}s, aborting",
2305                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2306                    );
2307                    handle.abort();
2308                    // `abort` only requests cancellation. Await the handle so
2309                    // synchronous sections finish and the task drops every
2310                    // storage/P2P clone before we claim producer quiescence.
2311                    match handle.await {
2312                        Ok(()) => {}
2313                        Err(e) if e.is_cancelled() => {}
2314                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2315                    }
2316                }
2317            }
2318        }
2319
2320        // Close the responder worker pools. Detached tasks still queued for a
2321        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2322        // rather than waiting for a slot that will never free up — without
2323        // this, work admitted just before shutdown would queue behind the last
2324        // in-flight batch and hold the drain below open for its full duration.
2325        self.fresh_offer_worker_semaphore.close();
2326        self.paid_notify_worker_semaphore.close();
2327        self.fetch_responder_worker_semaphore.close();
2328        self.verification_responder_worker_semaphore.close();
2329        self.neighbor_sync_responder_worker_semaphore.close();
2330
2331        // All producers have stopped, so close and drain their detached work.
2332        // A started storage operation must run to completion: dropping an async
2333        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2334        // while an LMDB transaction still owns the environment.
2335        //
2336        // Deliberately unbounded: the LMDB contract requires every worker to
2337        // release its `Arc<ChunkStore>` before the caller may reopen the
2338        // environment, and a timeout here could return with one still held.
2339        // What makes that safe is that every detached task is now guaranteed to
2340        // finish — the pools above are closed, stale work is shed at dequeue,
2341        // and the one genuinely unbounded await (payment verification) races
2342        // `self.shutdown` via `verify_payment_until_shutdown`.
2343        self.detached_task_tracker.close();
2344        self.detached_task_tracker.wait().await;
2345
2346        // Every producer is gone, but a select! racing the shutdown token may
2347        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2348        // (fetch `storage.put`, prune `storage.delete` /
2349        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2350        // detached blocking closure owns a cloned `Env`; wait for both
2351        // environments to go quiescent — bounded by one in-flight transaction
2352        // per op — so the caller may reopen them.
2353        self.storage.wait_idle().await;
2354        self.paid_list.wait_idle().await;
2355    }
2356
2357    /// Trigger an early neighbor sync round.
2358    ///
2359    /// Useful after topology changes (new nodes joining, network heal after
2360    /// partition) when the caller wants replication to converge faster than
2361    /// the regular 10-20 minute cadence.
2362    pub fn trigger_neighbor_sync(&self) {
2363        self.sync_trigger.notify_one();
2364    }
2365
2366    /// Execute fresh replication for a newly stored record, then schedule the
2367    /// delayed possession check for the responsible close-group peers
2368    /// (ADR-0003). The production PUT path schedules via the fresh-write
2369    /// drainer; this direct entry point schedules here so callers (and tests)
2370    /// that drive replication directly still get the possession check.
2371    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2372        let peers = fresh::replicate_fresh(
2373            key,
2374            data,
2375            proof_of_payment,
2376            &self.p2p_node,
2377            &self.paid_list,
2378            &self.config,
2379            &self.send_semaphore,
2380        )
2381        .await;
2382        if !peers.is_empty() {
2383            let _ = self
2384                .possession_check_tx
2385                .send(possession::PossessionCheckEvent { key: *key, peers });
2386        }
2387    }
2388
2389    // =======================================================================
2390    // Background task launchers
2391    // =======================================================================
2392
2393    /// Spawn a task that drains the fresh-write channel and triggers
2394    /// replication for each newly-stored chunk.
2395    fn start_fresh_write_drainer(&mut self) {
2396        let Some(mut rx) = self.fresh_write_rx.take() else {
2397            return;
2398        };
2399        let p2p = Arc::clone(&self.p2p_node);
2400        let paid_list = Arc::clone(&self.paid_list);
2401        let config = Arc::clone(&self.config);
2402        let send_semaphore = Arc::clone(&self.send_semaphore);
2403        let possession_tx = self.possession_check_tx.clone();
2404        let shutdown = self.shutdown.clone();
2405
2406        let handle = tokio::spawn(async move {
2407            loop {
2408                tokio::select! {
2409                    () = shutdown.cancelled() => break,
2410                    event = rx.recv() => {
2411                        let Some(event) = event else { break };
2412                        let peers = fresh::replicate_fresh(
2413                            &event.key,
2414                            &event.data,
2415                            &event.payment_proof,
2416                            &p2p,
2417                            &paid_list,
2418                            &config,
2419                            &send_semaphore,
2420                        )
2421                        .await;
2422                        // Schedule the delayed possession check (ADR-0003) for
2423                        // the responsible close-group peers. A closed receiver
2424                        // (engine shutting down) is ignored.
2425                        if !peers.is_empty() {
2426                            let _ = possession_tx.send(possession::PossessionCheckEvent {
2427                                key: event.key,
2428                                peers,
2429                            });
2430                        }
2431                    }
2432                }
2433            }
2434            debug!("Fresh-write drainer shut down");
2435        });
2436        self.task_handles.push(handle);
2437    }
2438
2439    /// Spawn the possession-check scheduler (ADR-0003).
2440    ///
2441    /// Drains scheduled possession-check events and, for each, waits a
2442    /// randomised 5-15 minute settle delay before probing every responsible
2443    /// peer for actual possession. A peer that fails to prove possession or does
2444    /// not answer is penalised at `AuditChallenge` severity.
2445    fn start_possession_check_scheduler(&mut self) {
2446        let Some(mut rx) = self.possession_check_rx.take() else {
2447            return;
2448        };
2449        let p2p = Arc::clone(&self.p2p_node);
2450        let storage = Arc::clone(&self.storage);
2451        let config = Arc::clone(&self.config);
2452        let sync_state = Arc::clone(&self.sync_state);
2453        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2454        let shutdown = self.shutdown.clone();
2455        let detached_task_tracker = self.detached_task_tracker.clone();
2456
2457        let handle = tokio::spawn(async move {
2458            loop {
2459                tokio::select! {
2460                    () = shutdown.cancelled() => break,
2461                    event = rx.recv() => {
2462                        let Some(event) = event else { break };
2463                        // Spawn a per-chunk delayed check so the drain loop
2464                        // keeps pace with the write rate. Each check sleeps the
2465                        // randomised settle delay, then probes every peer.
2466                        let p2p = Arc::clone(&p2p);
2467                        let storage = Arc::clone(&storage);
2468                        let config = Arc::clone(&config);
2469                        let sync_state = Arc::clone(&sync_state);
2470                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2471                        let shutdown = shutdown.clone();
2472                        let delay_min = config.possession_check_delay_min;
2473                        let delay_max = config.possession_check_delay_max;
2474                        detached_task_tracker.spawn(async move {
2475                            let delay = possession::random_delay(delay_min, delay_max);
2476                            // Race shutdown against the whole settle-then-probe
2477                            // sequence, not just the sleep. Once a check starts it
2478                            // may park on the per-target audit coordinator, which
2479                            // has no deadline of its own: with the settle delay
2480                            // inside the branch BODY the select is already resolved,
2481                            // so those waiters would drain only at the probe timeout
2482                            // (roughly `queued / per-target-limit` probes deep) while
2483                            // `detached_task_tracker.wait()` — deliberately unbounded
2484                            // for the LMDB contract — held shutdown open.
2485                            //
2486                            // Dropping this future mid-probe is safe and is the same
2487                            // shape the neighbor-sync round uses: a parked coordinator
2488                            // acquire releases its counted reference via
2489                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2490                            // covered by the storage-quiescence wait in `shutdown`.
2491                            tokio::select! {
2492                                () = shutdown.cancelled() => {}
2493                                () = async {
2494                                    tokio::time::sleep(delay).await;
2495                                    possession::run_possession_check(
2496                                        event.key,
2497                                        event.peers,
2498                                        &p2p,
2499                                        &storage,
2500                                        &config,
2501                                        &sync_state,
2502                                        &audit_challenge_coordinator,
2503                                        &shutdown,
2504                                    )
2505                                    .await;
2506                                } => {}
2507                            }
2508                        });
2509                    }
2510                }
2511            }
2512            debug!("Possession-check scheduler shut down");
2513        });
2514        self.task_handles.push(handle);
2515    }
2516
2517    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2518    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2519    /// as the gossip path, under the same per-peer cooldown and concurrency
2520    /// caps, but with the probability lottery BYPASSED (the lottery governs
2521    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2522    /// deterministic first audit; a peer minting fresh pins faster than the
2523    /// cooldown forfeits the older ones' coverage, never the newest's (the
2524    /// channel surfaces newest pins as they are monetized).
2525    #[allow(clippy::too_many_lines)]
2526    fn start_first_audit_drainer(&mut self) {
2527        let Some(mut rx) = self.monetized_pin_rx.take() else {
2528            return;
2529        };
2530        let gossip_audit = GossipAuditTrigger {
2531            p2p_node: Arc::clone(&self.p2p_node),
2532            config: Arc::clone(&self.config),
2533            recent_provers: Arc::clone(&self.recent_provers),
2534            sync_state: Arc::clone(&self.sync_state),
2535            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2536            detached_task_tracker: self.detached_task_tracker.clone(),
2537            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2538        };
2539        let shutdown = self.shutdown.clone();
2540        let observability = Arc::clone(&self.first_audit_observability);
2541        let self_peer = *self.p2p_node.peer_id();
2542
2543        let handle = tokio::spawn(async move {
2544            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2545            // scheduler. Payments only NOMINATE pins; the token bucket launches
2546            // them at a fixed per-node rate, and durable suppression is stamped
2547            // only at PROMOTION (after an authoritative post-jitter answerability
2548            // + cooldown check), so a cancelled reservation leaves nothing behind.
2549            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2550            // Periodic retry tick so budget/cooldown-deferred pins get retried
2551            // even when no new nomination arrives. `Skip` collapses a backlog.
2552            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2553            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2554            let mut last_summary = Instant::now();
2555            loop {
2556                // The reservation's jitter deadline is a wake source: if a
2557                // reservation is outstanding, sleep until it is due; otherwise
2558                // a far-future deadline effectively disables that arm and only
2559                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2560                // newly reserved (earlier) deadline is honoured next turn.
2561                let promotion_due = scheduler
2562                    .reserved_ready_at()
2563                    .unwrap_or_else(first_audit_far_future);
2564                tokio::select! {
2565                    () = shutdown.cancelled() => break,
2566                    event = rx.recv() => match event {
2567                        Some(e) => {
2568                            observability.received.fetch_add(1, Ordering::Relaxed);
2569                            // Pre-overflow reservation opportunity: before an
2570                            // arrival may displace a DIFFERENT peer, let the
2571                            // queue launch — a successful reservation frees the
2572                            // slot without eviction. One reservation can be
2573                            // outstanding at a time, so this consumes at most
2574                            // one slot per jitter window; arrivals beyond it
2575                            // fall through to random displacement (ADR-0004
2576                            // Amendment 4).
2577                            if scheduler.would_displace(&e) {
2578                                open_first_audit_reservation(
2579                                    &mut scheduler,
2580                                    &gossip_audit.cooldown,
2581                                    &observability,
2582                                )
2583                                .await;
2584                            }
2585                            scheduler.enqueue(e, &observability);
2586                            // Drain a bounded burst so a flood cannot starve the
2587                            // launch phase.
2588                            let mut drained = 1usize;
2589                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2590                                match rx.try_recv() {
2591                                    Ok(e) => {
2592                                        observability.received.fetch_add(1, Ordering::Relaxed);
2593                                        if scheduler.would_displace(&e) {
2594                                            open_first_audit_reservation(
2595                                                &mut scheduler,
2596                                                &gossip_audit.cooldown,
2597                                                &observability,
2598                                            )
2599                                            .await;
2600                                        }
2601                                        scheduler.enqueue(e, &observability);
2602                                        drained += 1;
2603                                    }
2604                                    Err(_) => break,
2605                                }
2606                            }
2607                        }
2608                        None => break,
2609                    },
2610                    _ = tick.tick() => {}
2611                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2612                }
2613
2614                // 1) Promote a due reservation. Resolved after EVERY wake (not
2615                //    only when the timer arm wins) so a continuously-ready `rx`
2616                //    cannot indefinitely delay a due promotion. The authoritative
2617                //    answerability + cooldown check-and-stamp happens here under
2618                //    the shared cooldown write lock, immediately before the send.
2619                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2620                    let promoted = {
2621                        let mut cooldown = gossip_audit.cooldown.write().await;
2622                        scheduler.resolve(
2623                            reservation,
2624                            SystemTime::now(),
2625                            Instant::now(),
2626                            &mut cooldown,
2627                            &observability,
2628                        )
2629                    };
2630                    if let Some((event, inflight_slot)) = promoted {
2631                        debug!(
2632                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2633                            event.peer, hex::encode(event.pin), event.key_count,
2634                            observability.inflight.load(Ordering::Relaxed)
2635                        );
2636                        let trigger = gossip_audit.clone();
2637                        let audit_observability = Arc::clone(&observability);
2638                        // Track the launch so `shutdown()`'s detached drain
2639                        // covers it. This task outlives the drainer loop that
2640                        // spawned it — the loop breaks on the shutdown token
2641                        // while the audit is still awaiting its response — so a
2642                        // bare spawn would let an in-flight subtree audit keep
2643                        // running, and keep its `Arc<P2PNode>`, past the point
2644                        // `shutdown()` claims every engine task has stopped.
2645                        let tracker = trigger.detached_task_tracker.clone();
2646                        tracker.spawn(async move {
2647                            // The jitter already elapsed as the reservation's
2648                            // timer; the slot is held for the audit's duration
2649                            // and released on drop (panic-safe).
2650                            let inflight_slot = inflight_slot;
2651                            let started = Instant::now();
2652                            let credit = storage_commitment_audit::AuditCredit {
2653                                recent_provers: &trigger.recent_provers,
2654                            };
2655                            let result = storage_commitment_audit::run_subtree_audit(
2656                                &trigger.p2p_node,
2657                                &trigger.config,
2658                                &event.peer,
2659                                event.pin,
2660                                event.key_count,
2661                                Some(&credit),
2662                            )
2663                            .await;
2664                            let outcome = first_audit_terminal_outcome(&result);
2665                            match outcome {
2666                                FirstAuditTerminalOutcome::Passed => {
2667                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2668                                }
2669                                FirstAuditTerminalOutcome::Timeout => {
2670                                    audit_observability
2671                                        .timed_out
2672                                        .fetch_add(1, Ordering::Relaxed);
2673                                }
2674                                FirstAuditTerminalOutcome::Failed => {
2675                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2676                                }
2677                                FirstAuditTerminalOutcome::BootstrapClaim => {
2678                                    audit_observability
2679                                        .bootstrap_claims
2680                                        .fetch_add(1, Ordering::Relaxed);
2681                                }
2682                                FirstAuditTerminalOutcome::Idle => {
2683                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2684                                }
2685                                FirstAuditTerminalOutcome::InsufficientKeys => {
2686                                    audit_observability
2687                                        .insufficient_keys
2688                                        .fetch_add(1, Ordering::Relaxed);
2689                                }
2690                            }
2691                            drop(inflight_slot);
2692                            debug!(
2693                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2694                                outcome.as_str(),
2695                                event.peer, hex::encode(event.pin), event.key_count,
2696                                started.elapsed().as_millis(),
2697                                audit_observability.inflight.load(Ordering::Relaxed)
2698                            );
2699                            handle_subtree_audit_result(
2700                                &result,
2701                                &trigger.p2p_node,
2702                                &trigger.sync_state,
2703                                &trigger.recent_provers,
2704                                &trigger.config,
2705                            )
2706                            .await;
2707                        });
2708                    }
2709                }
2710
2711                // 2) Open the single reservation from the pending queue if none
2712                //    is outstanding (read-only cooldown snapshot; the
2713                //    authoritative stamp is at promotion). Serializing
2714                //    reservations preserves per-launch lane alternation and keeps
2715                //    at most one jitter timer live.
2716                open_first_audit_reservation(
2717                    &mut scheduler,
2718                    &gossip_audit.cooldown,
2719                    &observability,
2720                )
2721                .await;
2722
2723                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2724                    // Token-independent hygiene: collect entries that aged past
2725                    // the answerability horizon while the budget gate kept the
2726                    // reserve scan from running, so the summary below reports
2727                    // only live work.
2728                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2729                    if swept > 0 {
2730                        debug!(
2731                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2732                            scheduler.pending_len()
2733                        );
2734                    }
2735                    info!(
2736                        "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={}",
2737                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2738                        observability.received.load(Ordering::Relaxed),
2739                        observability.queued.load(Ordering::Relaxed),
2740                        observability.coalesced.load(Ordering::Relaxed),
2741                        observability.suppressed_lower.load(Ordering::Relaxed),
2742                        observability.duplicates.load(Ordering::Relaxed),
2743                        observability.capacity_evicted.load(Ordering::Relaxed),
2744                        observability.self_target_skipped.load(Ordering::Relaxed),
2745                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2746                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2747                        observability.window_deduped.load(Ordering::Relaxed),
2748                        observability.launched.load(Ordering::Relaxed),
2749                        observability.passed.load(Ordering::Relaxed),
2750                        observability.timed_out.load(Ordering::Relaxed),
2751                        observability.failed.load(Ordering::Relaxed),
2752                        observability.bootstrap_claims.load(Ordering::Relaxed),
2753                        observability.idle.load(Ordering::Relaxed),
2754                        observability.insufficient_keys.load(Ordering::Relaxed),
2755                        observability.outside_answerability_window.load(Ordering::Relaxed),
2756                        scheduler.pending_len(),
2757                        FIRST_AUDIT_PENDING_CAP,
2758                        u8::from(scheduler.has_reservation()),
2759                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2760                        observability.inflight.load(Ordering::Relaxed),
2761                        scheduler.tokens(),
2762                    );
2763                    last_summary = Instant::now();
2764                }
2765            }
2766            debug!("First-audit drainer shut down");
2767        });
2768        self.task_handles.push(handle);
2769    }
2770
2771    #[allow(clippy::too_many_lines)]
2772    fn start_message_handler(&mut self) {
2773        let mut p2p_events = self.p2p_node.subscribe_events();
2774        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2775        let p2p = Arc::clone(&self.p2p_node);
2776        let storage = Arc::clone(&self.storage);
2777        let paid_list = Arc::clone(&self.paid_list);
2778        let payment_verifier = Arc::clone(&self.payment_verifier);
2779        let queues = Arc::clone(&self.queues);
2780        let config = Arc::clone(&self.config);
2781        let shutdown = self.shutdown.clone();
2782        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2783        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2784        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2785        let sync_history = Arc::clone(&self.sync_history);
2786        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2787        let repair_proofs = Arc::clone(&self.repair_proofs);
2788        let sync_trigger = Arc::clone(&self.sync_trigger);
2789        let my_commitment_state = Arc::clone(&self.commitment_state);
2790        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2791        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2792        let recent_provers = Arc::clone(&self.recent_provers);
2793        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2794        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2795        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2796        let sync_state = Arc::clone(&self.sync_state);
2797        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2798        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2799        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2800        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2801        let fetch_responder_admission_semaphore =
2802            Arc::clone(&self.fetch_responder_admission_semaphore);
2803        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2804        let verification_responder_worker_semaphore =
2805            Arc::clone(&self.verification_responder_worker_semaphore);
2806        let verification_responder_admission_semaphore =
2807            Arc::clone(&self.verification_responder_admission_semaphore);
2808        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2809        let neighbor_sync_responder_worker_semaphore =
2810            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2811        let neighbor_sync_responder_admission_semaphore =
2812            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2813        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2814        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2815        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2816        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2817        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2818        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2819        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2820        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2821        let detached_task_tracker = self.detached_task_tracker.clone();
2822        let subtree_round1 = self.subtree_round1.clone();
2823
2824        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2825        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2826        let gossip_audit = GossipAuditTrigger {
2827            p2p_node: Arc::clone(&p2p),
2828            config: Arc::clone(&config),
2829            recent_provers: Arc::clone(&recent_provers),
2830            sync_state: Arc::clone(&sync_state),
2831            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2832            detached_task_tracker: detached_task_tracker.clone(),
2833            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2834        };
2835
2836        let handler_context = ReplicationMessageHandlerContext {
2837            p2p_node: Arc::clone(&p2p),
2838            storage,
2839            paid_list,
2840            payment_verifier,
2841            queues,
2842            config: Arc::clone(&config),
2843            is_bootstrapping,
2844            bootstrap_state,
2845            sync_history,
2846            sync_cycle_epoch,
2847            repair_proofs: Arc::clone(&repair_proofs),
2848            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2849            ever_capable_peers,
2850            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2851            my_commitment_state,
2852            gossip_audit,
2853            audit_responder_semaphore,
2854            audit_responder_inflight,
2855            audit_responder_metrics,
2856            subtree_round1,
2857            fetch_responder_worker_semaphore,
2858            fetch_responder_admission_semaphore,
2859            fetch_responder_inflight,
2860            verification_responder_worker_semaphore,
2861            verification_responder_admission_semaphore,
2862            verification_responder_inflight,
2863            neighbor_sync_responder_worker_semaphore,
2864            neighbor_sync_responder_admission_semaphore,
2865            neighbor_sync_responder_inflight,
2866            fresh_offer_worker_semaphore,
2867            fresh_offer_admission_semaphore,
2868            fresh_offer_responder_inflight,
2869            fresh_offer_in_flight,
2870            paid_notify_worker_semaphore,
2871            paid_notify_admission_semaphore,
2872            paid_notify_responder_inflight,
2873            shutdown: shutdown.clone(),
2874            detached_task_tracker,
2875        };
2876
2877        let (replication_tx, mut replication_rx) =
2878            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2879        let serial_context = handler_context.clone();
2880        let serial_shutdown = shutdown.clone();
2881        let serial_handle = tokio::spawn(async move {
2882            loop {
2883                tokio::select! {
2884                    () = serial_shutdown.cancelled() => break,
2885                    inbound = replication_rx.recv() => {
2886                        let Some(inbound) = inbound else { break };
2887                        let source = inbound.source;
2888                        match handle_replication_message(
2889                            &source,
2890                            inbound.msg,
2891                            &serial_context,
2892                            inbound.received_at,
2893                            inbound.rr_message_id.as_deref(),
2894                        )
2895                        .await
2896                        {
2897                            Ok(()) => {}
2898                            Err(e) => {
2899                                debug!("Replication message from {source} error: {e}");
2900                            }
2901                        }
2902                    }
2903                }
2904            }
2905            debug!("Replication non-audit serial handler shut down");
2906        });
2907        self.task_handles.push(serial_handle);
2908
2909        let handle = tokio::spawn(async move {
2910            loop {
2911                tokio::select! {
2912                    () = shutdown.cancelled() => break,
2913                    event = p2p_events.recv() => {
2914                        let event = match event {
2915                            Ok(event) => event,
2916                            Err(error) => match handle_replication_event_recv_error(&error) {
2917                                ControlFlow::Continue(()) => continue,
2918                                ControlFlow::Break(()) => break,
2919                            },
2920                        };
2921                        let Some((source, payload, inbound_protocol, rr_message_id)) =
2922                            replication_payload_from_event(event)
2923                        else {
2924                            continue;
2925                        };
2926                        let received_at = Instant::now();
2927                        let msg = match ReplicationMessage::decode(&payload) {
2928                            Ok(msg) => msg,
2929                            Err(e) => {
2930                                debug!("Replication message from {source} decode error: {e}");
2931                                continue;
2932                            }
2933                        };
2934                        if !body_matches_protocol(&msg.body, inbound_protocol) {
2935                            debug!(
2936                                "Dropping replication body (variant {}) on protocol \
2937                                 {inbound_protocol}: wrong id for its family \
2938                                 (cross-version or misrouted)",
2939                                msg.body.variant_index()
2940                            );
2941                            continue;
2942                        }
2943                        if let Some(class) = audit_responder_class(&msg.body) {
2944                            handler_context
2945                                .audit_responder_metrics
2946                                .record_received(source, class);
2947                        }
2948                        let inbound = InboundReplicationMessage {
2949                            source,
2950                            msg,
2951                            rr_message_id,
2952                            received_at,
2953                        };
2954                        if matches!(
2955                            inbound.msg.body,
2956                            ReplicationMessageBody::AuditChallenge(_)
2957                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
2958                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
2959                        ) {
2960                            let source = inbound.source;
2961                            match handle_replication_message(
2962                                &source,
2963                                inbound.msg,
2964                                &handler_context,
2965                                inbound.received_at,
2966                                inbound.rr_message_id.as_deref(),
2967                            )
2968                            .await
2969                            {
2970                                Ok(()) => {}
2971                                Err(e) => {
2972                                    debug!("Replication message from {source} error: {e}");
2973                                }
2974                            }
2975                            continue;
2976                        }
2977                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2978                            if dropped.audit_responder_class.is_some() {
2979                                handler_context
2980                                    .audit_responder_metrics
2981                                    .record_serial_queue_drop(dropped.source);
2982                            }
2983                            // Every serial-lane class has protocol recovery: syncs rerun,
2984                            // fetches retry, verification re-asks, and a dropped fresh
2985                            // offer is refilled by neighbor sync (the possession check
2986                            // penalises the absence but never re-offers). Responses are
2987                            // covered by their requester's deadline/retry path. Never run
2988                            // a bulk handler here: event receipt must remain non-blocking.
2989                            warn!(
2990                                message_class = dropped.message_class,
2991                                source = %dropped.source,
2992                                queue_depth = dropped.queue_depth,
2993                                reason = dropped.reason.as_str(),
2994                                "Replication serial-queue message dropped"
2995                            );
2996                        }
2997                    }
2998                    // Gap 4: Topology churn handling (Section 13).
2999                    //
3000                    // The DHT routing table emits KClosestPeersChanged when the
3001                    // K-closest peer set actually changes, which is the precise
3002                    // signal for triggering neighbor sync. This replaces the
3003                    // previous approach of checking every PeerConnected /
3004                    // PeerDisconnected event against the close group.
3005                    dht_event = dht_events.recv() => {
3006                        let dht_event = match dht_event {
3007                            Ok(event) => event,
3008                            Err(RecvError::Lagged(missed)) => {
3009                                // Under heavy churn the broadcast buffer can overflow
3010                                // and drop routing-table events — the moment
3011                                // convergence matters most. A dropped
3012                                // KClosestPeersChanged means its entrants were never
3013                                // queued and its departures were never pruned, so
3014                                // draining priority_order cannot recover either.
3015                                // Resync from ground truth instead: snapshot the
3016                                // current close-peer set, prune pending peers that
3017                                // left it during the lost window (retain_sync_peers,
3018                                // as the normal topology-change path does), and queue
3019                                // every member. Dedup (queue_priority_peers) and
3020                                // per-peer cooldown (select_next_sync_peer) drop peers
3021                                // already queued or recently synced, so only genuine
3022                                // entrants surface.
3023                                warn!(
3024                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3025                                );
3026                                let self_id = *p2p.peer_id();
3027                                let neighbors = neighbor_sync::snapshot_close_neighbors(
3028                                    &p2p,
3029                                    &self_id,
3030                                    config.neighbor_sync_scope,
3031                                )
3032                                .await;
3033                                let neighbor_set =
3034                                    neighbors.iter().copied().collect::<HashSet<_>>();
3035                                let (requeued, sync_removals) = {
3036                                    let mut state = sync_state.write().await;
3037                                    let sync_removals =
3038                                        state.retain_sync_peers(&neighbor_set);
3039                                    let requeued = state.queue_priority_peers(neighbors);
3040                                    (requeued, sync_removals)
3041                                };
3042                                if sync_removals > 0 {
3043                                    debug!(
3044                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3045                                    );
3046                                }
3047                                if requeued > 0 {
3048                                    debug!(
3049                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3050                                    );
3051                                    sync_trigger.notify_one();
3052                                }
3053                                continue;
3054                            }
3055                            Err(RecvError::Closed) => {
3056                                // A closed broadcast channel never yields again;
3057                                // continuing would spin the select! loop forever.
3058                                warn!(
3059                                    "DHT event stream closed on replication branch; stopping message handler"
3060                                );
3061                                break;
3062                            }
3063                        };
3064                        match dht_event {
3065                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3066                                let old_peers = old
3067                                    .iter()
3068                                    .take(config.neighbor_sync_scope)
3069                                    .copied()
3070                                    .collect::<HashSet<_>>();
3071                                let new_scoped = new
3072                                    .iter()
3073                                    .take(config.neighbor_sync_scope)
3074                                    .copied()
3075                                    .collect::<Vec<_>>();
3076                                let new_peers =
3077                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3078                                let entrants = new_scoped
3079                                    .iter()
3080                                    .copied()
3081                                    .filter(|peer| !old_peers.contains(peer))
3082                                    .collect::<Vec<_>>();
3083                                let entrant_count = entrants.len();
3084                                let (priority_insertions, sync_removals) = {
3085                                    let mut state = sync_state.write().await;
3086                                    let sync_removals = state.retain_sync_peers(&new_peers);
3087                                    let priority_insertions = state.queue_priority_peers(entrants);
3088                                    (priority_insertions, sync_removals)
3089                                };
3090                                if priority_insertions > 0 {
3091                                    debug!(
3092                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3093                                    );
3094                                } else {
3095                                    debug!(
3096                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3097                                    );
3098                                }
3099                                sync_trigger.notify_one();
3100                            }
3101                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3102                                sync_state.write().await.remove_peer(&peer_id);
3103                                repair_proofs.write().await.remove_peer(&peer_id);
3104                                update_bootstrap_after_peer_removed(
3105                                    &peer_id,
3106                                    &handler_context.bootstrap_state,
3107                                    &handler_context.queues,
3108                                    &handler_context.is_bootstrapping,
3109                                    &bootstrap_complete_notify,
3110                                )
3111                                .await;
3112                                // v12: drop the commitment bytes and the
3113                                // recent-prover credit so a churn / sybil
3114                                // attacker cannot leave behind one
3115                                // StorageCommitment per identity in
3116                                // `last_commitment_by_peer`. Also drop the
3117                                // sig-verify rate-limit timestamp.
3118                                last_commitment_by_peer.write().await.remove(&peer_id);
3119                                recent_provers.write().await.forget_peer(&peer_id);
3120                                sig_verify_attempts.write().await.remove(&peer_id);
3121                                // Same for the gossip-audit cooldown (ADR-0002)
3122                                // and the lottery-attempt window.
3123                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3124                                gossip_lottery_attempts.write().await.remove(&peer_id);
3125                                // The sticky `commitment_capable` flag is
3126                                // preserved orthogonally via
3127                                // `ever_capable_peers` — even after this
3128                                // removal, a re-joining peer continues to
3129                                // be treated as v12-capable rather than
3130                                // legacy (§3 shield).
3131                            }
3132                            _ => {}
3133                        }
3134                    }
3135                }
3136            }
3137            debug!("Replication message handler shut down");
3138        });
3139        self.task_handles.push(handle);
3140    }
3141
3142    fn start_neighbor_sync_loop(&mut self) {
3143        let p2p = Arc::clone(&self.p2p_node);
3144        let storage = Arc::clone(&self.storage);
3145        let paid_list = Arc::clone(&self.paid_list);
3146        let queues = Arc::clone(&self.queues);
3147        let config = Arc::clone(&self.config);
3148        let shutdown = self.shutdown.clone();
3149        let sync_state = Arc::clone(&self.sync_state);
3150        let sync_history = Arc::clone(&self.sync_history);
3151        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3152        let repair_proofs = Arc::clone(&self.repair_proofs);
3153        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3154        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3155        let sync_trigger = Arc::clone(&self.sync_trigger);
3156        let commitment_state = Arc::clone(&self.commitment_state);
3157        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3158        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3159        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3160        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3161        let detached_task_tracker = self.detached_task_tracker.clone();
3162        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3163        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3164        // here too so a peer that only ever answers — never initiates sync —
3165        // is still audited; otherwise it could fully evade auditing.
3166        let gossip_audit = GossipAuditTrigger {
3167            p2p_node: Arc::clone(&p2p),
3168            config: Arc::clone(&config),
3169            recent_provers: Arc::clone(&self.recent_provers),
3170            sync_state: Arc::clone(&sync_state),
3171            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3172            detached_task_tracker,
3173            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3174        };
3175
3176        let handle = tokio::spawn(async move {
3177            loop {
3178                // Park for the periodic tick or an explicit trigger ONLY when no
3179                // priority (topology-change) peers are queued. `sync_trigger` is a
3180                // coalescing `Notify`, so a churn burst that queues many entrants
3181                // produces a single wakeup; parking after draining one batch would
3182                // leave the rest waiting up to a full periodic tick. `priority_order`
3183                // is the durable record of pending work, so drain it back-to-back —
3184                // each round removes the peers it selects (`select_next_sync_peer`),
3185                // so the drain terminates once the queue empties.
3186                if !sync_state.read().await.has_priority_peers() {
3187                    let interval = config.random_neighbor_sync_interval();
3188                    tokio::select! {
3189                        () = shutdown.cancelled() => break,
3190                        () = tokio::time::sleep(interval) => {}
3191                        () = sync_trigger.notified() => {
3192                            debug!("Neighbor sync triggered by topology change");
3193                        }
3194                    }
3195                }
3196                // Wrap the sync round in a select so shutdown cancels
3197                // in-progress network operations rather than waiting for
3198                // the full round to complete.
3199                tokio::select! {
3200                    () = shutdown.cancelled() => break,
3201                    () = run_neighbor_sync_round(
3202                        &p2p,
3203                        &storage,
3204                        &paid_list,
3205                        &queues,
3206                        &config,
3207                        &sync_state,
3208                        &sync_history,
3209                        &sync_cycle_epoch,
3210                        &repair_proofs,
3211                        &is_bootstrapping,
3212                        &bootstrap_state,
3213                        &commitment_state,
3214                        &last_commitment_by_peer,
3215                        &ever_capable_peers,
3216                        &sig_verify_attempts,
3217                        &audit_challenge_coordinator,
3218                        &gossip_audit,
3219                    ) => {}
3220                }
3221            }
3222            debug!("Neighbor sync loop shut down");
3223        });
3224        self.task_handles.push(handle);
3225    }
3226
3227    fn start_self_lookup_loop(&mut self) {
3228        let p2p = Arc::clone(&self.p2p_node);
3229        let config = Arc::clone(&self.config);
3230        let shutdown = self.shutdown.clone();
3231
3232        let handle = tokio::spawn(async move {
3233            loop {
3234                let interval = config.random_self_lookup_interval();
3235                tokio::select! {
3236                    () = shutdown.cancelled() => break,
3237                    () = tokio::time::sleep(interval) => {
3238                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3239                            debug!("Self-lookup failed: {e}");
3240                        }
3241                    }
3242                }
3243            }
3244            debug!("Self-lookup loop shut down");
3245        });
3246        self.task_handles.push(handle);
3247    }
3248
3249    /// Periodic responsible-chunk audit loop (audit #2): every
3250    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3251    /// eligible close peer for the chunks it *should* be storing (by
3252    /// responsibility and prior repair hint), independent of the gossip-triggered
3253    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3254    /// immediately and periodically thereafter.
3255    fn start_audit_loop(&mut self) {
3256        let p2p = Arc::clone(&self.p2p_node);
3257        let storage = Arc::clone(&self.storage);
3258        let config = Arc::clone(&self.config);
3259        let shutdown = self.shutdown.clone();
3260        let sync_history = Arc::clone(&self.sync_history);
3261        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3262        let repair_proofs = Arc::clone(&self.repair_proofs);
3263        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3264        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3265        let sync_state = Arc::clone(&self.sync_state);
3266        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3267
3268        let handle = tokio::spawn(async move {
3269            // Invariant 19: wait for bootstrap to drain before starting audits.
3270            loop {
3271                tokio::select! {
3272                    () = shutdown.cancelled() => return,
3273                    () = tokio::time::sleep(
3274                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3275                    ) => {
3276                        if bootstrap_state.read().await.is_drained() {
3277                            break;
3278                        }
3279                    }
3280                }
3281            }
3282
3283            // Run one audit tick immediately after bootstrap drain.
3284            {
3285                let bootstrapping = *is_bootstrapping.read().await;
3286                let result = {
3287                    let history = sync_history.read().await;
3288                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3289                    audit::audit_tick_with_repair_proofs(
3290                        &p2p,
3291                        &storage,
3292                        &config,
3293                        &history,
3294                        &repair_proofs,
3295                        &audit_challenge_coordinator,
3296                        current_sync_epoch,
3297                        bootstrapping,
3298                    )
3299                    .await
3300                };
3301                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3302            }
3303
3304            // Then run periodically.
3305            loop {
3306                let interval = config.random_audit_tick_interval();
3307                tokio::select! {
3308                    () = shutdown.cancelled() => break,
3309                    () = tokio::time::sleep(interval) => {
3310                        let bootstrapping = *is_bootstrapping.read().await;
3311                        let result = {
3312                            let history = sync_history.read().await;
3313                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3314                            audit::audit_tick_with_repair_proofs(
3315                                &p2p,
3316                                &storage,
3317                                &config,
3318                                &history,
3319                                &repair_proofs,
3320                                &audit_challenge_coordinator,
3321                                current_sync_epoch,
3322                                bootstrapping,
3323                            )
3324                            .await
3325                        };
3326                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3327                    }
3328                }
3329            }
3330            debug!("Audit loop shut down");
3331        });
3332        self.task_handles.push(handle);
3333    }
3334
3335    /// Periodically rebuild + sign + rotate the responder's storage
3336    /// commitment.
3337    ///
3338    /// Phase 3 of the v12 storage-bound audit. Once per
3339    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3340    /// current LMDB key set, builds a Merkle tree (for content-addressed
3341    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3342    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3343    /// into `commitment_state`. Old `previous` slot is dropped by the
3344    /// rotate (per `ResponderCommitmentState::rotate`).
3345    ///
3346    /// Skips if the key set is empty (no commitment to make) — the
3347    /// auditor side falls back to the legacy plain-digest path for
3348    /// peers that have never gossiped a commitment.
3349    fn start_commitment_rotation_loop(&mut self) {
3350        let storage = Arc::clone(&self.storage);
3351        let identity = Arc::clone(&self.identity);
3352        let commitment_state = Arc::clone(&self.commitment_state);
3353        let shutdown = self.shutdown.clone();
3354        let p2p = Arc::clone(&self.p2p_node);
3355        let config = Arc::clone(&self.config);
3356        let sync_trigger = Arc::clone(&self.sync_trigger);
3357        let recent_provers = Arc::clone(&self.recent_provers);
3358
3359        let handle = tokio::spawn(async move {
3360            // Build the first commitment immediately on startup so a
3361            // restarted node can answer commitment-bound audits right
3362            // away — otherwise current() stays None for a full rotation
3363            // interval and audits silently fall back to legacy.
3364            //
3365            // After the first build, trigger an immediate neighbor-sync
3366            // round so the new commitment gossips out within seconds.
3367            // Without this, after a restart remote auditors keep pinning
3368            // the pre-restart (rotated-away) hash until their normal
3369            // sync cadence elapses — up to 1 h in the worst case,
3370            // during which time commitment-bound audits hit "unknown
3371            // commitment hash" -> Idle no-ops.
3372            // ML-DSA signatures are randomized so we cannot reproduce
3373            // the pre-restart hash; the only honest path to recovery
3374            // is fast re-gossip.
3375            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3376            // spawned), so this initial rebuild no-ops when the key set is
3377            // unchanged — preserving the reloaded current pin; otherwise the
3378            // reloaded roots stay answerable as retained slots until their gossip
3379            // TTL lapses. Persistence is handled by the retention-persist loop.
3380            if let Err(e) =
3381                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3382                    .await
3383            {
3384                warn!("Initial commitment build failed: {e}");
3385            } else {
3386                sync_trigger.notify_one();
3387            }
3388            loop {
3389                tokio::select! {
3390                    () = shutdown.cancelled() => break,
3391                    () = tokio::time::sleep(
3392                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3393                    ) => {
3394                        if let Err(e) = rebuild_and_rotate_commitment(
3395                            &storage,
3396                            &identity,
3397                            &commitment_state,
3398                            &p2p,
3399                            &config,
3400                        ).await {
3401                            warn!("Commitment rotation failed: {e}");
3402                        }
3403                        // Piggyback a sweep of expired recent_provers
3404                        // entries on the rotation tick (same cadence,
3405                        // 1 h). is_credited_holder already honours the
3406                        // TTL on read, but the sweep reclaims memory
3407                        // for entries we'll never re-read.
3408                        let dropped = recent_provers.write().await.sweep_expired(
3409                            std::time::Instant::now()
3410                        );
3411                        if dropped > 0 {
3412                            debug!("recent_provers: swept {dropped} expired entries");
3413                        }
3414                    }
3415                }
3416            }
3417            debug!("Commitment rotation loop shut down");
3418        });
3419        self.task_handles.push(handle);
3420    }
3421
3422    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3423    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3424    /// rotations — survives a restart. Flushes once immediately, then every
3425    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3426    fn start_retention_persist_loop(&mut self) {
3427        let commitment_state = Arc::clone(&self.commitment_state);
3428        let retention_path = self.retention_path.clone();
3429        let shutdown = self.shutdown.clone();
3430        let handle = tokio::spawn(async move {
3431            let mut last: Option<Vec<u8>> = None;
3432            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3433            loop {
3434                tokio::select! {
3435                    () = shutdown.cancelled() => {
3436                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3437                            .await;
3438                        break;
3439                    }
3440                    () = tokio::time::sleep(std::time::Duration::from_secs(
3441                        RETENTION_PERSIST_INTERVAL_SECS,
3442                    )) => {
3443                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3444                            .await;
3445                    }
3446                }
3447            }
3448            debug!("Commitment retention persist loop shut down");
3449        });
3450        self.task_handles.push(handle);
3451    }
3452
3453    /// Periodically emit the cumulative replication traffic summaries: the
3454    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3455    /// (V2-684). Both read process-global counter tables maintained by the
3456    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3457    /// state.
3458    fn start_traffic_summary_loop(&mut self) {
3459        let shutdown = self.shutdown.clone();
3460        let handle = tokio::spawn(async move {
3461            loop {
3462                tokio::select! {
3463                    () = shutdown.cancelled() => break,
3464                    () = tokio::time::sleep(std::time::Duration::from_secs(
3465                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3466                    )) => {
3467                        protocol::log_traffic_summary();
3468                        protocol::log_served_peers_summary();
3469                        protocol::log_audit_outcome_summary();
3470                        audit_metrics::log_responder_admission_summary();
3471                        // V2-834 Part D: chunk RPC, upgrade and EVM RPC attribution
3472                        // ride the same cadence.
3473                        crate::storage::traffic::log_chunk_rpc_traffic_summary();
3474                        crate::upgrade::traffic::log_upgrade_traffic_summary();
3475                        crate::payment::traffic::log_evm_rpc_summary();
3476                    }
3477                }
3478            }
3479            debug!("Replication traffic summary loop shut down");
3480        });
3481        self.task_handles.push(handle);
3482    }
3483
3484    /// Periodically expose the state that gates bootstrap completion and prune
3485    /// admission. The state counts are copied before reading `is_bootstrapping`
3486    /// so this diagnostic path never nests async locks.
3487    #[cfg(feature = "logging")]
3488    fn start_bootstrap_state_snapshot_loop(&mut self) {
3489        let shutdown = self.shutdown.clone();
3490        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3491        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3492        let started_at = Instant::now();
3493        let handle = tokio::spawn(async move {
3494            loop {
3495                tokio::select! {
3496                    () = shutdown.cancelled() => break,
3497                    () = tokio::time::sleep(Duration::from_secs(
3498                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3499                    )) => {
3500                        let (
3501                            drained,
3502                            pending_peer_requests,
3503                            pending_keys,
3504                            capacity_rejected_sources,
3505                        ) = {
3506                            let state = bootstrap_state.read().await;
3507                            (
3508                                state.drained,
3509                                state.pending_peer_requests,
3510                                state.pending_keys.len(),
3511                                state.capacity_rejected_sources.len(),
3512                            )
3513                        };
3514                        let bootstrapping = *is_bootstrapping.read().await;
3515                        let snapshot_state = if drained && !bootstrapping {
3516                            "healthy"
3517                        } else if drained {
3518                            "drained_waiting_for_bootstrap_flag"
3519                        } else {
3520                            "pending"
3521                        };
3522                        info!(
3523                            drained,
3524                            pending_peer_requests,
3525                            pending_keys,
3526                            capacity_rejected_sources,
3527                            is_bootstrapping = bootstrapping,
3528                            snapshot_state,
3529                            uptime_secs = started_at.elapsed().as_secs(),
3530                            "Replication bootstrap state snapshot"
3531                        );
3532                        if drained && !bootstrapping {
3533                            info!(
3534                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3535                            );
3536                            break;
3537                        }
3538                    }
3539                }
3540            }
3541            debug!("Bootstrap state snapshot loop shut down");
3542        });
3543        self.task_handles.push(handle);
3544    }
3545
3546    /// Periodically rank remote peers using the shared audit responder pool and
3547    /// report handler-only versus end-to-end latency. Windowed values make a
3548    /// burst visible even after a long-running node has accumulated traffic.
3549    #[cfg(feature = "logging")]
3550    fn start_audit_responder_summary_loop(&mut self) {
3551        let shutdown = self.shutdown.clone();
3552        let metrics = Arc::clone(&self.audit_responder_metrics);
3553        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3554        let handle = tokio::spawn(async move {
3555            let mut window_started = Instant::now();
3556            loop {
3557                tokio::select! {
3558                    () = shutdown.cancelled() => {
3559                        log_audit_responder_summary(
3560                            &metrics,
3561                            &semaphore,
3562                            window_started.elapsed(),
3563                        );
3564                        break;
3565                    }
3566                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3567                        log_audit_responder_summary(
3568                            &metrics,
3569                            &semaphore,
3570                            window_started.elapsed(),
3571                        );
3572                        window_started = Instant::now();
3573                    }
3574                }
3575            }
3576            debug!("Audit responder summary loop shut down");
3577        });
3578        self.task_handles.push(handle);
3579    }
3580
3581    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3582    fn start_fetch_worker(&mut self) {
3583        let p2p = Arc::clone(&self.p2p_node);
3584        let storage = Arc::clone(&self.storage);
3585        let queues = Arc::clone(&self.queues);
3586        let config = Arc::clone(&self.config);
3587        let shutdown = self.shutdown.clone();
3588        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3589        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3590        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3591        let detached_task_tracker = self.detached_task_tracker.clone();
3592        let concurrency = max_parallel_fetch();
3593
3594        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3595
3596        let handle = tokio::spawn(async move {
3597            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3598            // always recover the key — even if the inner task panics.
3599            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3600
3601            loop {
3602                // Fill up to `concurrency` slots from the queue.
3603                {
3604                    let mut q = queues.write().await;
3605                    while in_flight.len() < concurrency {
3606                        let Some(candidate) = q.dequeue_fetch() else {
3607                            break;
3608                        };
3609                        let fetch_key = candidate.key;
3610                        let Some(&source) = candidate.sources.first() else {
3611                            warn!(
3612                                "Fetch candidate {} has no sources; requeueing for verification",
3613                                hex::encode(fetch_key)
3614                            );
3615                            let _ = q.requeue_candidate_for_verification(
3616                                candidate,
3617                                config.verification_request_timeout,
3618                            );
3619                            continue;
3620                        };
3621                        q.start_dequeued_fetch(candidate, source);
3622
3623                        let p2p = Arc::clone(&p2p);
3624                        let storage = Arc::clone(&storage);
3625                        let config = Arc::clone(&config);
3626                        let token = shutdown.clone();
3627                        let tracker = detached_task_tracker.clone();
3628                        in_flight.push(Box::pin(async move {
3629                            // Tracked so shutdown() still awaits the task if
3630                            // this awaiter is dropped (e.g. the worker is
3631                            // aborted): it holds Arc<ChunkStore> and must
3632                            // not outlive the engine.
3633                            let handle = tracker.spawn(async move {
3634                                // Cancel-aware: abort when the engine shuts down.
3635                                tokio::select! {
3636                                    () = token.cancelled() => FetchOutcome {
3637                                        key: fetch_key,
3638                                        result: FetchResult::SourceFailed,
3639                                    },
3640                                    outcome = execute_single_fetch(
3641                                        p2p, storage, config, fetch_key, source,
3642                                    ) => outcome,
3643                                }
3644                            });
3645                            match handle.await {
3646                                Ok(outcome) => (outcome.key, Some(outcome)),
3647                                Err(e) => {
3648                                    error!(
3649                                        "Fetch task for {} panicked: {e}",
3650                                        hex::encode(fetch_key)
3651                                    );
3652                                    (fetch_key, None)
3653                                }
3654                            }
3655                        }));
3656                    }
3657                } // release queues write lock
3658
3659                if in_flight.is_empty() {
3660                    // No work — wait for new items or shutdown.
3661                    tokio::select! {
3662                        () = shutdown.cancelled() => break,
3663                        () = tokio::time::sleep(
3664                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3665                        ) => continue,
3666                    }
3667                }
3668
3669                // Wait for the next fetch to complete and process the result.
3670                tokio::select! {
3671                    () = shutdown.cancelled() => break,
3672                    Some((key, maybe_outcome)) = in_flight.next() => {
3673                        let mut q = queues.write().await;
3674                        let terminal = if let Some(outcome) = maybe_outcome {
3675                            match apply_fetch_result(
3676                                &mut q,
3677                                &key,
3678                                &outcome.result,
3679                                config.verification_request_timeout,
3680                            ) {
3681                                FetchFollowUp::Terminal => true,
3682                                FetchFollowUp::RequeuedForVerification => false,
3683                                FetchFollowUp::RetryFrom(next_peer) => {
3684                                    // Spawn a new fetch task for the next source.
3685                                    let p2p = Arc::clone(&p2p);
3686                                    let storage = Arc::clone(&storage);
3687                                    let config = Arc::clone(&config);
3688                                    let token = shutdown.clone();
3689                                    let tracker = detached_task_tracker.clone();
3690                                    let fetch_key = key;
3691                                    in_flight.push(Box::pin(async move {
3692                                        // Tracked for the same reason as the
3693                                        // initial fetch spawn above.
3694                                        let handle = tracker.spawn(async move {
3695                                            tokio::select! {
3696                                                () = token.cancelled() => FetchOutcome {
3697                                                    key: fetch_key,
3698                                                    result: FetchResult::SourceFailed,
3699                                                },
3700                                                outcome = execute_single_fetch(
3701                                                    p2p, storage, config, fetch_key, next_peer,
3702                                                ) => outcome,
3703                                            }
3704                                        });
3705                                        match handle.await {
3706                                            Ok(outcome) => (outcome.key, Some(outcome)),
3707                                            Err(e) => {
3708                                                error!(
3709                                                    "Fetch task for {} panicked: {e}",
3710                                                    hex::encode(fetch_key)
3711                                                );
3712                                                (fetch_key, None)
3713                                            }
3714                                        }
3715                                    }));
3716                                    false
3717                                }
3718                            }
3719                        } else {
3720                            // Task panicked — retry verification when this was
3721                            // a verified repair, otherwise reclaim the slot.
3722                            !q.requeue_fetch_for_verification(
3723                                &key,
3724                                config.verification_request_timeout,
3725                            )
3726                        };
3727
3728                        // Shrink bootstrap pending set on terminal exit.
3729                        if terminal {
3730                            drop(q); // release queues lock before acquiring bootstrap_state
3731                            if !bootstrap_state.read().await.is_drained() {
3732                                bootstrap_state.write().await.remove_key(&key);
3733                                let q = queues.read().await;
3734                                if bootstrap::check_bootstrap_drained(
3735                                    &bootstrap_state,
3736                                    &q,
3737                                )
3738                                .await
3739                                {
3740                                    complete_bootstrap(
3741                                        &is_bootstrapping,
3742                                        &bootstrap_complete_notify,
3743                                    ).await;
3744                                }
3745                            }
3746                        }
3747                    }
3748                }
3749            }
3750
3751            // Cancel and drain remaining in-flight fetches on shutdown.
3752            // The CancellationToken is already cancelled by this point, so
3753            // spawned tasks will see cancellation via their select! branches.
3754            while in_flight.next().await.is_some() {}
3755            debug!("Fetch worker shut down");
3756        });
3757        self.task_handles.push(handle);
3758    }
3759
3760    fn start_verification_worker(&mut self) {
3761        let p2p = Arc::clone(&self.p2p_node);
3762        let storage = Arc::clone(&self.storage);
3763        let queues = Arc::clone(&self.queues);
3764        let paid_list = Arc::clone(&self.paid_list);
3765        let config = Arc::clone(&self.config);
3766        let shutdown = self.shutdown.clone();
3767        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3768        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3769        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3770        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3771        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3772        let recent_provers = Arc::clone(&self.recent_provers);
3773
3774        let handle = tokio::spawn(async move {
3775            loop {
3776                tokio::select! {
3777                    () = shutdown.cancelled() => break,
3778                    () = tokio::time::sleep(
3779                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3780                    ) => {
3781                        let ctx = VerificationCycleContext {
3782                            p2p_node: &p2p,
3783                            paid_list: &paid_list,
3784                            storage: &storage,
3785                            queues: &queues,
3786                            config: &config,
3787                            bootstrap_state: &bootstrap_state,
3788                            is_bootstrapping: &is_bootstrapping,
3789                            bootstrap_complete_notify: &bootstrap_complete_notify,
3790                            last_commitment_by_peer: &last_commitment_by_peer,
3791                            ever_capable_peers: &ever_capable_peers,
3792                            recent_provers: &recent_provers,
3793                        };
3794                        run_verification_cycle(ctx).await;
3795                    }
3796                }
3797            }
3798            debug!("Verification worker shut down");
3799        });
3800        self.task_handles.push(handle);
3801    }
3802
3803    /// Gap 3: Run a one-shot bootstrap sync on startup.
3804    ///
3805    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3806    /// (indicating the routing table is populated) before snapshotting
3807    /// close neighbors. Falls back after a timeout so bootstrap nodes
3808    /// (which have no peers and therefore never receive the event) still
3809    /// proceed.
3810    ///
3811    /// After the gate, finds close neighbors, syncs with each in
3812    /// round-robin batches, admits returned hints into the verification
3813    /// pipeline, and tracks discovered keys for bootstrap drain detection.
3814    #[allow(clippy::too_many_lines)]
3815    fn start_bootstrap_sync(
3816        &mut self,
3817        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3818    ) {
3819        let p2p = Arc::clone(&self.p2p_node);
3820        let storage = Arc::clone(&self.storage);
3821        let paid_list = Arc::clone(&self.paid_list);
3822        let queues = Arc::clone(&self.queues);
3823        let config = Arc::clone(&self.config);
3824        let shutdown = self.shutdown.clone();
3825        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3826        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3827        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3828        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3829        let repair_proofs = Arc::clone(&self.repair_proofs);
3830        let my_commitment_state = Arc::clone(&self.commitment_state);
3831        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3832        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3833        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3834
3835        let handle = tokio::spawn(async move {
3836            // Wait for DHT bootstrap to complete before snapshotting
3837            // neighbors. The routing table is empty until saorsa-core
3838            // finishes its FIND_NODE rounds and bucket refreshes.
3839            let gate = bootstrap::wait_for_bootstrap_complete(
3840                dht_events,
3841                config.bootstrap_complete_timeout_secs,
3842                &shutdown,
3843            )
3844            .await;
3845
3846            if gate == bootstrap::BootstrapGateResult::Shutdown {
3847                return;
3848            }
3849
3850            let self_id = *p2p.peer_id();
3851            let neighbors =
3852                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3853                    .await;
3854
3855            if neighbors.is_empty() {
3856                info!("Bootstrap sync: no close neighbors found, marking drained");
3857                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3858                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3859                return;
3860            }
3861
3862            let neighbor_count = neighbors.len();
3863            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3864
3865            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3866            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3867                if shutdown.is_cancelled() {
3868                    break;
3869                }
3870
3871                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3872                    batch,
3873                    &storage,
3874                    &paid_list,
3875                    &p2p,
3876                    config.close_group_size,
3877                    config.paid_list_close_group_size,
3878                )
3879                .await;
3880
3881                // Keep the batch outstanding until every response has been
3882                // admitted and bootstrap accounting is updated. The verification
3883                // worker uses this counter as a batch barrier, so it cannot race
3884                // the source aggregation below.
3885                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3886                let bootstrapping = *is_bootstrapping.read().await;
3887
3888                let sync_futures = batch.iter().map(|peer| {
3889                    let peer = *peer;
3890                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3891                    // Atomically snapshot + mark-gossiped for each emitted
3892                    // bootstrap request so we remain answerable for it.
3893                    let commitment = my_commitment_state
3894                        .current_for_gossip()
3895                        .map(|binding| binding.commitment().clone());
3896                    let p2p = &p2p;
3897                    let config = &config;
3898                    async move {
3899                        let outcome = neighbor_sync::sync_with_peer_with_hints(
3900                            &peer,
3901                            p2p,
3902                            config,
3903                            bootstrapping,
3904                            hints,
3905                            commitment,
3906                        )
3907                        .await;
3908                        (peer, outcome)
3909                    }
3910                });
3911                let completed = join_all(sync_futures).await;
3912
3913                // Process response metadata before exposing any of this batch's
3914                // hints to verification.
3915                for (peer, outcome) in &completed {
3916                    if let Some(outcome) = outcome {
3917                        // Ingest the peer's piggybacked commitment from the
3918                        // response (same verification as the request path).
3919                        // Bootstrap is the FIRST gossip we receive from most
3920                        // peers, so this populates last_commitment_by_peer.
3921                        //
3922                        // We intentionally do NOT trigger a gossip-audit here:
3923                        // during bootstrap this node may itself still be
3924                        // bootstrapping (audits are gated on that), and the
3925                        // close-group/RT view is not yet stable. The peer is
3926                        // audited on the first STEADY-STATE neighbor-sync round
3927                        // after bootstrap drains (request + response paths both
3928                        // trigger), which is within one sync cycle — so caching
3929                        // the commitment here is sufficient and there is no
3930                        // coverage gap (ADR-0002).
3931                        ingest_peer_commitment(
3932                            peer,
3933                            outcome.response.commitment.as_ref(),
3934                            &p2p,
3935                            &last_commitment_by_peer,
3936                            &ever_capable_peers,
3937                            &sig_verify_attempts,
3938                        )
3939                        .await; // sig_verify_attempts in scope from line ~1080
3940
3941                        if !outcome.response.bootstrapping {
3942                            record_sent_replica_hints(
3943                                peer,
3944                                &outcome.sent_replica_hints,
3945                                &repair_proofs,
3946                                &sync_cycle_epoch,
3947                            )
3948                            .await;
3949                        }
3950                    }
3951                }
3952
3953                let pending_keys: HashSet<XorName> = {
3954                    let q = queues.read().await;
3955                    q.pending_keys().into_iter().collect()
3956                };
3957                let admission_futures = completed.iter().map(async |(_, outcome)| match outcome {
3958                    Some(outcome) if !outcome.response.bootstrapping => Some(
3959                        admission::admit_hints(
3960                            &self_id,
3961                            &outcome.response.replica_hints,
3962                            &outcome.response.paid_hints,
3963                            &p2p,
3964                            &config,
3965                            &storage,
3966                            &paid_list,
3967                            &pending_keys,
3968                        )
3969                        .await,
3970                    ),
3971                    _ => None,
3972                });
3973                let admitted = join_all(admission_futures).await;
3974
3975                // Queue every peer's admitted hints under one write lock. Once
3976                // released, source-count ordering sees the complete batch.
3977                let (batch_outcomes, batch_discovered) = {
3978                    let mut q = queues.write().await;
3979                    let outcomes = completed
3980                        .iter()
3981                        .zip(admitted)
3982                        .filter_map(|((peer, _), admitted)| {
3983                            admitted.map(|admitted| {
3984                                (
3985                                    *peer,
3986                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
3987                                )
3988                            })
3989                        })
3990                        .collect::<Vec<_>>();
3991                    let live_discovered = outcomes
3992                        .iter()
3993                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3994                        .filter(|key| q.contains_key(key))
3995                        .collect::<HashSet<_>>();
3996                    (outcomes, live_discovered)
3997                };
3998
3999                publish_bootstrap_admission_outcomes(
4000                    &bootstrap_state,
4001                    &batch_outcomes,
4002                    &batch_discovered,
4003                )
4004                .await;
4005
4006                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4007            }
4008
4009            // Check drain condition.
4010            {
4011                let q = queues.read().await;
4012                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4013                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4014                }
4015            }
4016
4017            info!("Bootstrap sync completed");
4018        });
4019        self.task_handles.push(handle);
4020    }
4021}
4022
4023// ===========================================================================
4024// Free functions for background tasks
4025// ===========================================================================
4026
4027#[cfg(feature = "logging")]
4028fn log_audit_responder_summary(
4029    metrics: &AuditResponderMetrics,
4030    semaphore: &Semaphore,
4031    window: Duration,
4032) {
4033    let snapshot = metrics.take_snapshot();
4034    if snapshot.origins.is_empty() {
4035        return;
4036    }
4037
4038    let total = snapshot.total;
4039    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4040        total.received_by_class;
4041    let global_inflight =
4042        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4043    info!(
4044        target: "ant_node::replication::audit_responder",
4045        window_ms = window.as_millis(),
4046        source_count = snapshot.origins.len(),
4047        received = total.received(),
4048        digest_received,
4049        subtree_received,
4050        byte_received,
4051        commitment_pin_received,
4052        admitted = total.admitted,
4053        global_pool_drops = total.global_pool_drops,
4054        per_peer_cap_drops = total.per_peer_cap_drops,
4055        serial_queue_drops = total.serial_queue_drops,
4056        completed = total.completed,
4057        send_failures = total.send_failures,
4058        processing_avg_ms = total.processing_avg_ms(),
4059        processing_max_ms = total.processing_max_ms,
4060        total_avg_ms = total.total_avg_ms(),
4061        total_max_ms = total.total_max_ms,
4062        global_inflight,
4063        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4064        peak_global_inflight = total.peak_global_inflight,
4065        "Audit responder summary"
4066    );
4067
4068    for (index, origin) in snapshot
4069        .origins
4070        .iter()
4071        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4072        .enumerate()
4073    {
4074        let Some(source) = origin.source else {
4075            continue;
4076        };
4077        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4078            origin.received_by_class;
4079        info!(
4080            target: "ant_node::replication::audit_responder",
4081            rank = index + 1,
4082            source = %source,
4083            received = origin.received(),
4084            digest_received,
4085            subtree_received,
4086            byte_received,
4087            commitment_pin_received,
4088            admitted = origin.admitted,
4089            global_pool_drops = origin.global_pool_drops,
4090            per_peer_cap_drops = origin.per_peer_cap_drops,
4091            serial_queue_drops = origin.serial_queue_drops,
4092            completed = origin.completed,
4093            send_failures = origin.send_failures,
4094            processing_avg_ms = origin.processing_avg_ms(),
4095            processing_max_ms = origin.processing_max_ms,
4096            total_avg_ms = origin.total_avg_ms(),
4097            total_max_ms = origin.total_max_ms,
4098            peak_global_inflight = origin.peak_global_inflight,
4099            peak_peer_inflight = origin.peak_peer_inflight,
4100            "Audit responder top origin"
4101        );
4102    }
4103}
4104
4105/// Which ceiling rejected an audit-responder admission attempt.
4106///
4107/// Stable, machine-readable so a production log-scrape can bucket drops by
4108/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4109/// single opaque "capacity reached" line; this splits the two distinct causes
4110/// so the next such investigation can tell a global-pool exhaustion (the whole
4111/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4112/// without re-instrumenting.
4113///
4114/// This branch runs a SINGLE shared audit-responder pool for all challenge
4115/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4116/// pool to distinguish here — the `kind=` log field already separates the
4117/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4118/// dedicated slow pool is later split out, add its variants here.
4119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4120enum ResponderRejectReason {
4121    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4122    /// free; the per-peer cap was not the binding constraint.
4123    GlobalPoolFull,
4124    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4125    /// share, so the global permit was never attempted.
4126    PerPeerCapFull,
4127}
4128
4129impl ResponderRejectReason {
4130    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4131    /// frozen — production log tooling greps for them.
4132    fn as_str(self) -> &'static str {
4133        match self {
4134            Self::GlobalPoolFull => "global_pool_full",
4135            Self::PerPeerCapFull => "per_peer_cap_full",
4136        }
4137    }
4138}
4139
4140impl From<ResponderRejectReason> for AuditResponderDropReason {
4141    fn from(reason: ResponderRejectReason) -> Self {
4142        match reason {
4143            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4144            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4145        }
4146    }
4147}
4148
4149impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4150    fn from(reason: ResponderRejectReason) -> Self {
4151        match reason {
4152            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4153            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4154        }
4155    }
4156}
4157
4158/// Cumulative fresh-offer admission refusals in this process.
4159///
4160/// **Expected value in healthy operation is zero.** A node that refuses a
4161/// legitimate fresh offer does not merely shed load: the sender transmits
4162/// offers one-way and never reads the refusal, so the chunk's absence
4163/// resurfaces at the sender's delayed possession check and is charged to the
4164/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4165/// means the node is either under-provisioned for its offered load or its
4166/// admission share is mis-sized — and is accruing unearned trust damage either
4167/// way. Operators should alarm on any sustained non-zero rate.
4168///
4169/// Process-global rather than per-engine, which is exactly right in production
4170/// (one node per process) and adequate in multi-node test harnesses, where the
4171/// useful assertion is that *no* node in the fleet refused.
4172#[must_use]
4173pub fn fresh_offer_admission_refusals() -> u64 {
4174    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4175}
4176
4177/// Cumulative paid-list notification admission refusals in this process.
4178///
4179/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4180/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4181/// paid-list evidence outright rather than pushing work back onto a requester.
4182#[must_use]
4183pub fn paid_notify_admission_refusals() -> u64 {
4184    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4185}
4186
4187/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4188///
4189/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4190/// different things: this one says the node was saturated across all sources
4191/// and is genuinely under-provisioned for its offered load.
4192#[must_use]
4193pub fn fresh_offer_refusals_global_pool() -> u64 {
4194    audit_metrics::responder_admission_drops_by_ceiling(
4195        ReplicationResponderClass::FreshOffer,
4196        ResponderAdmissionCeiling::GlobalPool,
4197    )
4198}
4199
4200/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4201///
4202/// For fresh offers this usually indicts the *share's size* rather than the
4203/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4204/// node handling a client's PUT and fanning it out — so a share sized for
4205/// request/response traffic will refuse ordinary uploads.
4206#[must_use]
4207pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4208    audit_metrics::responder_admission_drops_by_ceiling(
4209        ReplicationResponderClass::FreshOffer,
4210        ResponderAdmissionCeiling::PerPeerShare,
4211    )
4212}
4213
4214/// Why an audit-responder admission attempt failed, with the decision-time
4215/// capacity counters that let a drop be logged with full context.
4216///
4217/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4218/// decision was made (the two ceilings are read under different locks, so they
4219/// are not a single atomic view), but they are exact enough to tell a saturated
4220/// node from a single self-throttling flooder.
4221#[derive(Debug, Clone, Copy)]
4222struct ResponderAdmissionFailure {
4223    reason: ResponderRejectReason,
4224    /// Global permits in use across the whole engine at decision time.
4225    global_inflight: usize,
4226    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4227    global_limit: usize,
4228    /// In-flight audit responders already held for `source` at decision time.
4229    peer_inflight: u32,
4230    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4231    peer_limit: u32,
4232}
4233
4234impl fmt::Display for ResponderAdmissionFailure {
4235    /// Renders the stable `reason=... global_inflight=... global_limit=...
4236    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4238        write!(
4239            f,
4240            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4241            self.reason.as_str(),
4242            self.global_inflight,
4243            self.global_limit,
4244            self.peer_inflight,
4245            self.peer_limit,
4246        )
4247    }
4248}
4249
4250/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4251/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4252/// spawned task ties both bounds to the task's exact lifetime — no manual
4253/// decrement to forget on an early return or panic.
4254struct ResponderGuard {
4255    _permit: tokio::sync::OwnedSemaphorePermit,
4256    _peer_slot: PeerResponderSlot,
4257    global_inflight: usize,
4258    peer_inflight: u32,
4259}
4260
4261type AuditResponderGuard = ResponderGuard;
4262type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4263
4264/// Provisional or admitted per-peer responder slot.
4265///
4266/// The slot is claimed before the global permit is attempted. Keeping that
4267/// claim under RAII means cancellation while rolling a failed admission back
4268/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4269/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4270struct PeerResponderSlot {
4271    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4272    peer: PeerId,
4273}
4274
4275#[derive(Clone)]
4276struct ReplicationMessageHandlerContext {
4277    p2p_node: Arc<P2PNode>,
4278    storage: Arc<ChunkStore>,
4279    paid_list: Arc<PaidList>,
4280    payment_verifier: Arc<PaymentVerifier>,
4281    queues: Arc<RwLock<ReplicationQueues>>,
4282    config: Arc<ReplicationConfig>,
4283    is_bootstrapping: Arc<RwLock<bool>>,
4284    bootstrap_state: Arc<RwLock<BootstrapState>>,
4285    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4286    sync_cycle_epoch: Arc<RwLock<u64>>,
4287    repair_proofs: Arc<RwLock<RepairProofs>>,
4288    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4289    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4290    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4291    my_commitment_state: Arc<ResponderCommitmentState>,
4292    gossip_audit: GossipAuditTrigger,
4293    audit_responder_semaphore: Arc<Semaphore>,
4294    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4295    audit_responder_metrics: Arc<AuditResponderMetrics>,
4296    subtree_round1: SubtreeRound1Limiter,
4297    fetch_responder_worker_semaphore: Arc<Semaphore>,
4298    fetch_responder_admission_semaphore: Arc<Semaphore>,
4299    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4300    verification_responder_worker_semaphore: Arc<Semaphore>,
4301    verification_responder_admission_semaphore: Arc<Semaphore>,
4302    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4303    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4304    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4305    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4306    fresh_offer_worker_semaphore: Arc<Semaphore>,
4307    fresh_offer_admission_semaphore: Arc<Semaphore>,
4308    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4309    fresh_offer_in_flight: FreshOfferInFlight,
4310    paid_notify_worker_semaphore: Arc<Semaphore>,
4311    paid_notify_admission_semaphore: Arc<Semaphore>,
4312    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4313    /// The engine's shutdown token, for detached responder work.
4314    ///
4315    /// Workers on [`Self::detached_task_tracker`] race this around their
4316    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4317    /// where dropping the awaiter would detach a live transaction. This is
4318    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4319    /// terminate: the wait stays safe because it is now guaranteed finite.
4320    shutdown: CancellationToken,
4321    /// Shared tracker for detached work so `shutdown()` can await release of
4322    /// storage and P2P resources after all producer tasks have stopped.
4323    detached_task_tracker: TaskTracker,
4324}
4325
4326struct InboundReplicationMessage {
4327    source: PeerId,
4328    msg: ReplicationMessage,
4329    rr_message_id: Option<String>,
4330    received_at: Instant,
4331}
4332
4333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4334enum SerialQueueDropReason {
4335    Full,
4336    Closed,
4337}
4338
4339#[cfg(feature = "logging")]
4340impl SerialQueueDropReason {
4341    const fn as_str(self) -> &'static str {
4342        match self {
4343            Self::Full => "full",
4344            Self::Closed => "closed",
4345        }
4346    }
4347}
4348
4349#[derive(Debug, Clone, Copy)]
4350#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4351struct SerialQueueDrop {
4352    source: PeerId,
4353    message_class: &'static str,
4354    audit_responder_class: Option<AuditResponderClass>,
4355    queue_depth: usize,
4356    reason: SerialQueueDropReason,
4357}
4358
4359fn try_enqueue_serial_message(
4360    sender: &mpsc::Sender<InboundReplicationMessage>,
4361    inbound: InboundReplicationMessage,
4362) -> std::result::Result<(), SerialQueueDrop> {
4363    let source = inbound.source;
4364    let message_class = replication_message_class(&inbound.msg.body);
4365    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4366    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4367    sender.try_send(inbound).map_err(|error| {
4368        let (reason, dropped) = match error {
4369            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4370            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4371        };
4372        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4373        SerialQueueDrop {
4374            source,
4375            message_class,
4376            audit_responder_class,
4377            queue_depth,
4378            reason,
4379        }
4380    })
4381}
4382
4383const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4384    match body {
4385        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4386        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4387        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4388        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4389        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4390        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4391        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4392        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4393        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4394        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4395        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4396        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4397        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4398        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4399        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4400        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4401        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4402    }
4403}
4404
4405const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4406    match body {
4407        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4408        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4409        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4410        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4411        _ => None,
4412    }
4413}
4414
4415impl AuditResponderClass {
4416    const fn per_peer_limit(self) -> u32 {
4417        match self {
4418            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4419            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4420        }
4421    }
4422}
4423
4424fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4425    match error {
4426        RecvError::Lagged(missed) => {
4427            audit_metrics::record_replication_event_lagged(*missed);
4428            warn!(
4429                "Missed {missed} P2P events on replication branch (broadcast lag); \
4430                 replication messages may have been dropped before dispatch"
4431            );
4432            ControlFlow::Continue(())
4433        }
4434        RecvError::Closed => {
4435            // A closed broadcast channel never yields again, so the branch
4436            // would otherwise be immediately ready on every select! iteration.
4437            warn!("P2P event stream closed on replication branch; stopping message handler");
4438            ControlFlow::Break(())
4439        }
4440    }
4441}
4442
4443fn replication_payload_from_event(
4444    event: P2PEvent,
4445) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4446    let P2PEvent::Message {
4447        topic,
4448        source: Some(source),
4449        data,
4450        ..
4451    } = event
4452    else {
4453        return None;
4454    };
4455
4456    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4457    if !is_rr {
4458        return Some((source, data, matched_id, None));
4459    }
4460    if is_rr {
4461        return P2PNode::parse_request_envelope(&data)
4462            .filter(|(_, is_resp, _)| !is_resp)
4463            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4464    }
4465    None
4466}
4467
4468impl Drop for PeerResponderSlot {
4469    fn drop(&mut self) {
4470        // Decrement (and prune to keep the map bounded) without blocking the
4471        // async runtime: a short lock on a tiny map.
4472        //
4473        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4474        // with no spawn. Otherwise defer to a task — but only if a runtime is
4475        // actually current, so `Drop` during shutdown (no runtime) can never
4476        // panic. A missed decrement at shutdown is harmless: the whole map is
4477        // being dropped with the engine.
4478        let peer = self.peer;
4479        if let Ok(mut map) = self.inflight.try_write() {
4480            if let Some(n) = map.get_mut(&peer) {
4481                *n = n.saturating_sub(1);
4482                if *n == 0 {
4483                    map.remove(&peer);
4484                }
4485            }
4486            return;
4487        }
4488        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4489            let inflight = Arc::clone(&self.inflight);
4490            handle.spawn(async move {
4491                let mut map = inflight.write().await;
4492                if let Some(n) = map.get_mut(&peer) {
4493                    *n = n.saturating_sub(1);
4494                    if *n == 0 {
4495                        map.remove(&peer);
4496                    }
4497                }
4498            });
4499        }
4500    }
4501}
4502
4503/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4504/// and then a global permit. The limits are parameters so independent responder
4505/// classes can reuse the same flood-fair admission and cancellation semantics.
4506async fn admit_bounded_responder(
4507    semaphore: &Arc<Semaphore>,
4508    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4509    source: &PeerId,
4510    global_limit: usize,
4511    peer_limit: u32,
4512) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4513    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4514
4515    let admitted_peer_inflight = {
4516        let mut map = inflight.write().await;
4517        let entry = map.entry(*source).or_insert(0);
4518        if *entry >= peer_limit {
4519            let peer_inflight = *entry;
4520            drop(map);
4521            return Err(ResponderAdmissionFailure {
4522                reason: ResponderRejectReason::PerPeerCapFull,
4523                global_inflight: global_inflight(semaphore),
4524                global_limit,
4525                peer_inflight,
4526                peer_limit,
4527            });
4528        }
4529        *entry += 1;
4530        *entry
4531    };
4532
4533    let peer_slot = PeerResponderSlot {
4534        inflight: Arc::clone(inflight),
4535        peer: *source,
4536    };
4537    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4538        return Err(ResponderAdmissionFailure {
4539            reason: ResponderRejectReason::GlobalPoolFull,
4540            global_inflight: global_inflight(semaphore),
4541            global_limit,
4542            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4543            peer_limit,
4544        });
4545    };
4546
4547    Ok(ResponderGuard {
4548        _permit: permit,
4549        _peer_slot: peer_slot,
4550        global_inflight: global_inflight(semaphore),
4551        peer_inflight: admitted_peer_inflight,
4552    })
4553}
4554
4555/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4556struct SubtreeSession {
4557    commitment_hash: [u8; 32],
4558    nonce: [u8; 32],
4559    inserted: Instant,
4560}
4561
4562/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4563/// read and hash, refilled continuously at
4564/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4565/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4566///
4567/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4568/// identity may ask, so it is refilled by acquiring more identities; this is
4569/// charged for work done regardless of who asked, so it is not.
4570///
4571/// Charged after the fact, with the bytes the proof actually covered: the cost
4572/// of a request is not known until the pinned commitment has been resolved and
4573/// its subtree selected, both of which happen inside the handler. Admission
4574/// therefore asks only whether the balance is positive, and a proof that costs
4575/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4576/// Carrying the debt is what makes the bound real: without it a maximal proof
4577/// would cost the same as a trivial one, since either way the next request only
4578/// has to wait for the balance to climb back above zero. With it, sustained
4579/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4580/// admitted proportionally less often.
4581struct Round1WorkBudget {
4582    /// Signed, so an over-large proof leaves debt to work off.
4583    balance: i64,
4584    last_refill: Instant,
4585}
4586
4587impl Round1WorkBudget {
4588    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4589    /// for longer than the burst takes to refill.
4590    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4591    /// Nanoseconds per second, for the sub-second part of a refill.
4592    const NANOS_PER_SEC: i64 = 1_000_000_000;
4593
4594    fn new() -> Self {
4595        Self {
4596            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4597            last_refill: Instant::now(),
4598        }
4599    }
4600
4601    /// Add the tokens accrued since the last touch, capped at the burst size.
4602    fn refill(&mut self, now: Instant) {
4603        let elapsed = now.saturating_duration_since(self.last_refill);
4604        self.last_refill = now;
4605        let whole_secs = i64::try_from(elapsed.as_secs())
4606            .unwrap_or(i64::MAX)
4607            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4608        let sub_sec = i64::from(elapsed.subsec_nanos())
4609            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4610            / Self::NANOS_PER_SEC;
4611        self.balance = self
4612            .balance
4613            .saturating_add(whole_secs.saturating_add(sub_sec))
4614            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4615    }
4616
4617    /// Whether budget remains for a new round-1 proof.
4618    fn has_budget(&mut self, now: Instant) -> bool {
4619        self.refill(now);
4620        self.balance > 0
4621    }
4622
4623    /// Charge `bytes` of completed proof work, carrying debt down to
4624    /// [`Self::MAX_DEBT`].
4625    fn charge(&mut self, bytes: i64, now: Instant) {
4626        self.refill(now);
4627        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4628    }
4629}
4630
4631/// Resource controls for the HEAVY subtree-audit round 1: a tight
4632/// admission pool separate from the light responsible/slice audits, a per-peer
4633/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4634/// challenge is only served after a matching round 1.
4635///
4636/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4637/// bounds not keyed by peer identity, and so the only one that bounds sustained
4638/// work rather than concurrency or per-identity frequency.
4639#[derive(Clone)]
4640struct SubtreeRound1Limiter {
4641    semaphore: Arc<Semaphore>,
4642    /// Global ceiling on concurrent round-1 proofs (config-driven;
4643    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4644    /// semaphore because the per-peer admission helper needs the same number.
4645    max_concurrent: usize,
4646    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4647    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4648    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4649    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4650    cooldown_interval: Duration,
4651    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4652    /// Identity-independent ceiling on sustained round-1 work.
4653    work: Arc<RwLock<Round1WorkBudget>>,
4654}
4655
4656impl SubtreeRound1Limiter {
4657    /// `max_concurrent` of 0 would wedge the responder into refusing every
4658    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4659    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4660    /// rather than to off.
4661    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4662        let max_concurrent = max_concurrent.max(1);
4663        Self {
4664            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4665            max_concurrent,
4666            inflight: Arc::new(RwLock::new(HashMap::new())),
4667            cooldown: Arc::new(RwLock::new(HashMap::new())),
4668            cooldown_interval,
4669            sessions: Arc::new(RwLock::new(HashMap::new())),
4670            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4671        }
4672    }
4673
4674    /// Charge completed round-1 proof work against the responder-wide budget.
4675    async fn charge_work(&self, content_bytes: i64) {
4676        self.work
4677            .write()
4678            .await
4679            .charge(content_bytes, Instant::now());
4680    }
4681
4682    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4683    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4684    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4685    /// drops the challenge (the remote auditor applies its own graced-timeout
4686    /// policy).
4687    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4688        let guard = admit_bounded_responder(
4689            &self.semaphore,
4690            &self.inflight,
4691            source,
4692            self.max_concurrent,
4693            MAX_SUBTREE_ROUND1_PER_PEER,
4694        )
4695        .await
4696        .ok()?;
4697        // Checked before the per-peer cooldown is stamped, so a peer refused for
4698        // want of budget is not also charged its next allowance.
4699        if !self.work.write().await.has_budget(Instant::now()) {
4700            return None; // guard drops here, releasing the permit + slot
4701        }
4702        let now = Instant::now();
4703        let mut cooldown = self.cooldown.write().await;
4704        if let Some(&last) = cooldown.get(source) {
4705            if now.duration_since(last) < self.cooldown_interval {
4706                return None; // guard drops here, releasing the permit + slot
4707            }
4708        }
4709        // Evict lapsed entries (their cooldown has expired, so they no longer
4710        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4711        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4712        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4713            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4714                cooldown.remove(&oldest);
4715            }
4716        }
4717        cooldown.insert(*source, now);
4718        Some(guard)
4719    }
4720
4721    /// Record a single-use session once a round-1 proof is built and about to be
4722    /// sent, so the matching round 2 is admitted exactly once.
4723    async fn open_session(
4724        &self,
4725        source: PeerId,
4726        challenge_id: u64,
4727        commitment_hash: [u8; 32],
4728        nonce: [u8; 32],
4729    ) {
4730        let now = Instant::now();
4731        let mut sessions = self.sessions.write().await;
4732        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4733        if sessions.len() >= MAX_SUBTREE_SESSIONS {
4734            if let Some(oldest) = sessions
4735                .iter()
4736                .min_by_key(|(_, e)| e.inserted)
4737                .map(|(k, _)| *k)
4738            {
4739                sessions.remove(&oldest);
4740            }
4741        }
4742        sessions.insert(
4743            (source, challenge_id),
4744            SubtreeSession {
4745                commitment_hash,
4746                nonce,
4747                inserted: now,
4748            },
4749        );
4750    }
4751
4752    /// Atomically consume the round-2 session for this exchange. `true` iff a
4753    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4754    /// existed (and is now removed); a miss silently drops round 2 to the graced
4755    /// timeout lane (sessions are ephemeral and can be lost across a restart).
4756    async fn consume_session(
4757        &self,
4758        source: &PeerId,
4759        challenge_id: u64,
4760        commitment_hash: &[u8; 32],
4761        nonce: &[u8; 32],
4762    ) -> bool {
4763        let mut sessions = self.sessions.write().await;
4764        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4765            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4766                && &e.commitment_hash == commitment_hash
4767                && &e.nonce == nonce
4768        });
4769        if matches {
4770            sessions.remove(&(*source, challenge_id));
4771        }
4772        matches
4773    }
4774}
4775
4776/// Outcome of admitting a round-2 slice challenge.
4777enum SliceAdmission {
4778    /// Admitted: the guard holds the global permit and the per-peer slot, and
4779    /// the single-use round-1 session has been consumed.
4780    Admitted(AuditResponderGuard),
4781    /// Refused at a responder ceiling. The round-1 session is left INTACT.
4782    Capacity(AuditResponderAdmissionFailure),
4783    /// No live round-1 session matched this challenge.
4784    NoSession,
4785}
4786
4787/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4788/// the single-use round-1 session.
4789///
4790/// The order is the point: a single-use token must not be spent on work that is
4791/// then refused. Consuming first and testing admission second leaves the session
4792/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4793/// even in principle.
4794///
4795/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4796/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4797/// auditor does not currently re-send round 2 within an audit. The preserved
4798/// session is therefore not yet *recovering* an audit — it keeps a refusal
4799/// truthful (temporary means temporary) and keeps the invariant available for a
4800/// retry, rather than baking "capacity drop is permanent" into the state
4801/// machine. If an application-level retry is ruled out for good, this ordering
4802/// still costs nothing over the alternative.
4803///
4804/// Cost of the ordering: the permit and per-peer slot are held across the
4805/// session probe, which is one in-memory map lookup and no chunk work. The
4806/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4807/// share it could already occupy with well-formed ones, so the admission
4808/// surface is unchanged.
4809async fn admit_slice_challenge(
4810    semaphore: &Arc<Semaphore>,
4811    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4812    round1: &SubtreeRound1Limiter,
4813    source: &PeerId,
4814    challenge: &protocol::SubtreeSliceChallenge,
4815) -> SliceAdmission {
4816    let guard =
4817        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4818            Ok(guard) => guard,
4819            Err(failure) => return SliceAdmission::Capacity(failure),
4820        };
4821    if !round1
4822        .consume_session(
4823            source,
4824            challenge.challenge_id,
4825            &challenge.expected_commitment_hash,
4826            &challenge.nonce,
4827        )
4828        .await
4829    {
4830        // Release the permit and per-peer slot before the caller replies: no
4831        // chunk work follows, so holding them would shrink the pool for nothing.
4832        drop(guard);
4833        return SliceAdmission::NoSession;
4834    }
4835    SliceAdmission::Admitted(guard)
4836}
4837
4838/// Try to admit one audit-responder task for `source`: take a global permit AND
4839/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4840/// its decision-time counters (caller drops the challenge, leaving the remote
4841/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4842/// so one flooder can neither exhaust the global pool's effect on others nor
4843/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4844/// log exactly WHY the drop happened rather than a single opaque "capacity
4845/// reached".
4846async fn admit_audit_responder(
4847    semaphore: &Arc<Semaphore>,
4848    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4849    source: &PeerId,
4850    class: AuditResponderClass,
4851) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4852    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4853    let peer_limit = class.per_peer_limit();
4854    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4855}
4856
4857/// Handle an incoming replication protocol message.
4858///
4859/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4860/// request-response path and the response must be sent via `send_response`
4861/// so saorsa-core can route it back to the waiting `send_request` caller.
4862#[allow(clippy::too_many_lines)]
4863async fn handle_replication_message(
4864    source: &PeerId,
4865    msg: ReplicationMessage,
4866    ctx: &ReplicationMessageHandlerContext,
4867    received_at: Instant,
4868    rr_message_id: Option<&str>,
4869) -> Result<()> {
4870    match msg.body {
4871        ReplicationMessageBody::FreshReplicationOffer(offer) => {
4872            dispatch_fresh_offer(
4873                *source,
4874                offer,
4875                ctx,
4876                msg.request_id,
4877                received_at,
4878                rr_message_id,
4879            )
4880            .await
4881        }
4882        ReplicationMessageBody::PaidNotify(notify) => {
4883            dispatch_paid_notify(*source, notify, ctx, received_at).await
4884        }
4885        ReplicationMessageBody::NeighborSyncRequest(request) => {
4886            let bootstrapping = *ctx.is_bootstrapping.read().await;
4887            // Phase-3 storage-bound audit: store the sender's
4888            // commitment for use as `expected_commitment_hash` in
4889            // future audits. Verify signature before storing so a peer
4890            // cannot inject a forged commitment for someone else.
4891            if let Some(target) = ingest_peer_commitment(
4892                source,
4893                request.commitment.as_ref(),
4894                &ctx.p2p_node,
4895                &ctx.last_commitment_by_peer,
4896                &ctx.ever_capable_peers,
4897                &ctx.sig_verify_attempts,
4898            )
4899            .await
4900            {
4901                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4902            }
4903            dispatch_neighbor_sync_request(
4904                *source,
4905                request,
4906                ctx,
4907                bootstrapping,
4908                // Atomically snapshot + mark-gossiped: emitted in the sync
4909                // response, so we must stay answerable for it (ADR-0002).
4910                ctx.my_commitment_state
4911                    .current_for_gossip()
4912                    .map(|b| b.commitment().clone()),
4913                msg.request_id,
4914                received_at,
4915                rr_message_id,
4916            )
4917            .await
4918        }
4919        ReplicationMessageBody::VerificationRequest(request) => {
4920            dispatch_verification_request(
4921                *source,
4922                request,
4923                ctx,
4924                msg.request_id,
4925                received_at,
4926                rr_message_id,
4927            )
4928            .await
4929        }
4930        ReplicationMessageBody::FetchRequest(request) => {
4931            dispatch_fetch_request(
4932                *source,
4933                request,
4934                ctx,
4935                msg.request_id,
4936                received_at,
4937                rr_message_id,
4938            )
4939            .await
4940        }
4941        ReplicationMessageBody::AuditChallenge(challenge) => {
4942            // Responsible-chunk audit (audit #2) responder: answer with per-key
4943            // possession digests. This same handler also answers the
4944            // prune-confirmation audit, which sends the same `AuditChallenge`
4945            // wire message.
4946            //
4947            // Answering digests the stored bytes of every challenged key, so —
4948            // like the subtree/byte audits below — run it on a detached task off
4949            // this serial message loop. Handling it inline lets one challenge
4950            // block all other replication traffic until its digests complete
4951            // (head-of-line blocking). The same flood-fair admission applies: a
4952            // global ceiling AND a per-peer cap, dropping the challenge if either
4953            // is hit. A dropped challenge reads as a penalised timeout to the
4954            // auditor, so the caps must remain high enough for honest audit load;
4955            // the per-peer share still prevents one flooder from starving others.
4956            let class = AuditResponderClass::Digest;
4957            let guard = match admit_audit_responder(
4958                &ctx.audit_responder_semaphore,
4959                &ctx.audit_responder_inflight,
4960                source,
4961                class,
4962            )
4963            .await
4964            {
4965                Ok(guard) => guard,
4966                Err(failure) => {
4967                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4968                    audit_metrics::record_admission_drop(class);
4969                    ctx.audit_responder_metrics
4970                        .record_drop(*source, failure.reason.into());
4971                    warn!(
4972                        target: "ant_node::replication::audit_responder",
4973                        event = "admission_dropped",
4974                        kind = "responsible",
4975                        responder_class = class.as_str(),
4976                        source = %source,
4977                        challenge_id = challenge.challenge_id,
4978                        key_count = challenge.keys.len(),
4979                        request_response = rr_message_id.is_some(),
4980                        dispatch_ms = received_at.elapsed().as_millis(),
4981                        reason = failure.reason.as_str(),
4982                        global_inflight = failure.global_inflight,
4983                        global_limit = failure.global_limit,
4984                        peer_inflight = failure.peer_inflight,
4985                        peer_limit = failure.peer_limit,
4986                        "Audit responder admission dropped"
4987                    );
4988                    return Ok(());
4989                }
4990            };
4991            let admission_global_inflight = guard.global_inflight;
4992            let admission_peer_inflight = guard.peer_inflight;
4993            ctx.audit_responder_metrics.record_admitted(
4994                *source,
4995                admission_global_inflight,
4996                admission_peer_inflight,
4997            );
4998            info!(
4999                target: "ant_node::replication::audit_responder",
5000                event = "admitted",
5001                kind = "responsible",
5002                responder_class = class.as_str(),
5003                source = %source,
5004                challenge_id = challenge.challenge_id,
5005                key_count = challenge.keys.len(),
5006                request_response = rr_message_id.is_some(),
5007                dispatch_ms = received_at.elapsed().as_millis(),
5008                global_inflight = admission_global_inflight,
5009                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5010                peer_inflight = admission_peer_inflight,
5011                peer_limit = class.per_peer_limit(),
5012                "Audit responder request admitted"
5013            );
5014            let bootstrapping = *ctx.is_bootstrapping.read().await;
5015            let dispatch_latency = received_at.elapsed();
5016            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5017            debug!(
5018                audit_type = "digest_responder",
5019                dispatch_latency_ms = dispatch_latency.as_millis(),
5020                source = %source,
5021                "Audit challenge dispatch latency measured"
5022            );
5023            let storage = Arc::clone(&ctx.storage);
5024            let p2p_node = Arc::clone(&ctx.p2p_node);
5025            let source = *source;
5026            let request_id = msg.request_id;
5027            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5028            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5029            ctx.detached_task_tracker.spawn(async move {
5030                let _guard = guard; // global permit + per-peer slot, held until done
5031                let worker_started = Instant::now();
5032                match handle_audit_challenge_msg(
5033                    &source,
5034                    &challenge,
5035                    &storage,
5036                    &p2p_node,
5037                    bootstrapping,
5038                    ReplyRoute {
5039                        request_id,
5040                        rr_message_id: rr_message_id.as_deref(),
5041                        protocol: REPLICATION_PROTOCOL_ID,
5042                    },
5043                )
5044                .await
5045                {
5046                    Ok(completion) => log_audit_responder_completion(
5047                        &responder_metrics,
5048                        source,
5049                        class,
5050                        "responsible",
5051                        challenge.challenge_id,
5052                        challenge.keys.len(),
5053                        completion.response_kind,
5054                        completion.sent,
5055                        received_at,
5056                        worker_started,
5057                        completion.processing,
5058                        completion.response_send,
5059                    ),
5060                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5061                }
5062            });
5063            Ok(())
5064        }
5065        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5066            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5067            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5068            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5069            // detached task so this serial message loop is never blocked on disk
5070            // I/O — otherwise one audit stalls all replication traffic (§5).
5071            //
5072            // A bounded, flood-fair admission restores backpressure (codex#1 +
5073            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5074            // we drop this challenge. Subtree auditors grace timeout
5075            // non-responses, so capacity drops throttle flooders without turning
5076            // into trust penalties (and one source cannot starve other peers,
5077            // since its share is capped per-peer).
5078            let class = AuditResponderClass::Subtree;
5079            info!(
5080                "Audit challenge received: kind=subtree source={source} request_response={}",
5081                rr_message_id.is_some(),
5082            );
5083            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5084            // so it uses its own tight admission pool + per-peer rate cooldown,
5085            // separate from the light responsible/slice audits, and a miss silently
5086            // drops (subtree auditors grace timeouts).
5087            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5088                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5089                warn!(
5090                    target: "ant_node::replication::audit_responder",
5091                    event = "admission_dropped",
5092                    kind = "subtree",
5093                    responder_class = class.as_str(),
5094                    source = %source,
5095                    challenge_id = challenge.challenge_id,
5096                    request_response = rr_message_id.is_some(),
5097                    dispatch_ms = received_at.elapsed().as_millis(),
5098                    reason = "heavy_pool_cooldown_or_work_budget",
5099                    "Audit responder admission dropped"
5100                );
5101                return Ok(());
5102            };
5103            let admission_global_inflight = guard.global_inflight;
5104            let admission_peer_inflight = guard.peer_inflight;
5105            ctx.audit_responder_metrics.record_admitted(
5106                *source,
5107                admission_global_inflight,
5108                admission_peer_inflight,
5109            );
5110            info!(
5111                target: "ant_node::replication::audit_responder",
5112                event = "admitted",
5113                kind = "subtree",
5114                responder_class = class.as_str(),
5115                source = %source,
5116                challenge_id = challenge.challenge_id,
5117                request_response = rr_message_id.is_some(),
5118                dispatch_ms = received_at.elapsed().as_millis(),
5119                global_inflight = admission_global_inflight,
5120                global_limit = ctx.subtree_round1.max_concurrent,
5121                peer_inflight = admission_peer_inflight,
5122                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5123                "Audit responder request admitted"
5124            );
5125            let bootstrapping = *ctx.is_bootstrapping.read().await;
5126            let storage = Arc::clone(&ctx.storage);
5127            let p2p_node = Arc::clone(&ctx.p2p_node);
5128            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5129            let source = *source;
5130            let request_id = msg.request_id;
5131            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5132            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5133            let subtree_round1 = ctx.subtree_round1.clone();
5134            ctx.detached_task_tracker.spawn(async move {
5135                let _guard = guard; // global permit + per-peer slot, held until done
5136                let worker_started = Instant::now();
5137                let processing_started = Instant::now();
5138                let storage_commitment_audit::Round1Work {
5139                    response,
5140                    content_bytes,
5141                } = storage_commitment_audit::handle_subtree_challenge_measured(
5142                    &challenge,
5143                    &storage,
5144                    p2p_node.peer_id(),
5145                    bootstrapping,
5146                    Some(&my_commitment_state),
5147                )
5148                .await;
5149                let processing = processing_started.elapsed();
5150                // Charge the work actually done, on EVERY outcome.
5151                //
5152                // This used to charge only the `Proof` arm, reasoning that the
5153                // rejecting paths either read nothing or reflected this node's
5154                // own broken storage. The second half of that was wrong: a
5155                // retained commitment containing one unreadable key still costs
5156                // a full run of reads and keyed-BLAKE3 passes over every leaf
5157                // before it, and then rejects. An attacker who finds such a
5158                // commitment could replay subtrees over it indefinitely for
5159                // free. The per-peer cooldown does not catch that either, since
5160                // it is escapable by rotating identity — the responder-wide
5161                // budget is the only bound that applies, so it has to see the
5162                // work. A zero charge is a no-op, so the untouched paths are
5163                // unaffected.
5164                subtree_round1.charge_work(content_bytes).await;
5165                // A round-1 proof authorizes exactly one matching round 2: open a
5166                // single-use session so a slice challenge cannot be served without
5167                // a live round-1 exchange.
5168                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5169                {
5170                    subtree_round1
5171                        .open_session(
5172                            source,
5173                            challenge.challenge_id,
5174                            challenge.expected_commitment_hash,
5175                            challenge.nonce,
5176                        )
5177                        .await;
5178                }
5179                let response_kind = subtree_audit_response_kind(&response);
5180                let work_items = subtree_audit_response_work_items(&response);
5181                let response_send_started = Instant::now();
5182                let sent = send_replication_response_checked(
5183                    &source,
5184                    &p2p_node,
5185                    request_id,
5186                    ReplicationMessageBody::SubtreeAuditResponse(response),
5187                    rr_message_id.as_deref(),
5188                    None,
5189                )
5190                .await;
5191                let response_send = response_send_started.elapsed();
5192                log_audit_responder_completion(
5193                    &responder_metrics,
5194                    source,
5195                    class,
5196                    "subtree",
5197                    challenge.challenge_id,
5198                    work_items,
5199                    response_kind,
5200                    sent,
5201                    received_at,
5202                    worker_started,
5203                    processing,
5204                    response_send,
5205                );
5206            });
5207            Ok(())
5208        }
5209        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5210            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5211            // block of each auditor-selected spot-check key with a Bao verified
5212            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5213            // build the proofs, so it runs off the serial loop under the light
5214            // audit pool's global and per-peer ceilings.
5215            let class = AuditResponderClass::Byte;
5216            info!(
5217                "Audit challenge received: kind=slice source={source} request_response={}",
5218                rr_message_id.is_some(),
5219            );
5220            let guard = match admit_slice_challenge(
5221                &ctx.audit_responder_semaphore,
5222                &ctx.audit_responder_inflight,
5223                &ctx.subtree_round1,
5224                source,
5225                &challenge,
5226            )
5227            .await
5228            {
5229                SliceAdmission::Admitted(guard) => guard,
5230                SliceAdmission::Capacity(failure) => {
5231                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5232                    audit_metrics::record_admission_drop(class);
5233                    ctx.audit_responder_metrics
5234                        .record_drop(*source, failure.reason.into());
5235                    warn!(
5236                        target: "ant_node::replication::audit_responder",
5237                        event = "admission_dropped",
5238                        kind = "byte",
5239                        responder_class = class.as_str(),
5240                        source = %source,
5241                        challenge_id = challenge.challenge_id,
5242                        key_count = challenge.openings.len(),
5243                        request_response = rr_message_id.is_some(),
5244                        dispatch_ms = received_at.elapsed().as_millis(),
5245                        reason = failure.reason.as_str(),
5246                        global_inflight = failure.global_inflight,
5247                        global_limit = failure.global_limit,
5248                        peer_inflight = failure.peer_inflight,
5249                        peer_limit = failure.peer_limit,
5250                        "Audit responder admission dropped"
5251                    );
5252                    return Ok(());
5253                }
5254                // No live round-1 session: reply with a cheap `Transient` rejection
5255                // rather than dropping silently. Sessions are ephemeral (an honest
5256                // responder that restarts between rounds loses its session), and an
5257                // unanswered `send_request` would make saorsa-core record a
5258                // transport trust failure against that honest responder — an
5259                // ongoing effect, not just a rollout-window one. A `Transient`
5260                // reply routes the auditor to the graced timeout lane (no trust
5261                // penalty; the responder re-earns pinned credit on the next audit)
5262                // and does no chunk work, so it is not a DoS lever.
5263                SliceAdmission::NoSession => {
5264                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5265                    debug!(
5266                        "Slice challenge without a live round-1 session source={source} \
5267                         challenge_id={} → Transient reject",
5268                        challenge.challenge_id
5269                    );
5270                    send_replication_response_checked(
5271                        source,
5272                        &ctx.p2p_node,
5273                        msg.request_id,
5274                        ReplicationMessageBody::SubtreeSliceResponse(
5275                            protocol::SubtreeSliceResponse::Rejected {
5276                                challenge_id: challenge.challenge_id,
5277                                kind: protocol::RejectKind::Transient,
5278                                reason: "no live round-1 session".to_string(),
5279                            },
5280                        ),
5281                        rr_message_id,
5282                        None,
5283                    )
5284                    .await;
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 = "byte",
5299                responder_class = class.as_str(),
5300                source = %source,
5301                challenge_id = challenge.challenge_id,
5302                key_count = challenge.openings.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 storage = Arc::clone(&ctx.storage);
5313            let p2p_node = Arc::clone(&ctx.p2p_node);
5314            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5315            let source = *source;
5316            let request_id = msg.request_id;
5317            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5318            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5319            ctx.detached_task_tracker.spawn(async move {
5320                let _guard = guard; // global permit + per-peer slot, held until done
5321                let worker_started = Instant::now();
5322                let processing_started = Instant::now();
5323                let response = storage_commitment_audit::handle_subtree_slice_challenge(
5324                    &challenge,
5325                    &storage,
5326                    p2p_node.peer_id(),
5327                    bootstrapping,
5328                    Some(&my_commitment_state),
5329                )
5330                .await;
5331                let processing = processing_started.elapsed();
5332                let response_kind = subtree_slice_response_kind(&response);
5333                let response_send_started = Instant::now();
5334                let sent = send_replication_response_checked(
5335                    &source,
5336                    &p2p_node,
5337                    request_id,
5338                    ReplicationMessageBody::SubtreeSliceResponse(response),
5339                    rr_message_id.as_deref(),
5340                    None,
5341                )
5342                .await;
5343                let response_send = response_send_started.elapsed();
5344                log_audit_responder_completion(
5345                    &responder_metrics,
5346                    source,
5347                    class,
5348                    "byte",
5349                    challenge.challenge_id,
5350                    challenge.openings.len(),
5351                    response_kind,
5352                    sent,
5353                    received_at,
5354                    worker_started,
5355                    processing,
5356                    response_send,
5357                );
5358            });
5359            Ok(())
5360        }
5361        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5362            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5363            // only. `lookup_by_hash` is an allocation-light read over the
5364            // bounded slot set; it returns the live current commitment or any
5365            // still-answerable recently-gossiped/quoted one. A miss is reported
5366            // as `NotRetained` (graced, never confirmed) rather than an error,
5367            // so an aged-out pin can never brand an honest node.
5368            //
5369            // Reuse the audit-responder admission guard (global ceiling + per-peer
5370            // cap) so a flood of fetches cannot drive unbounded commitment
5371            // clone/encode/send work; over-limit is dropped, which the fetching
5372            // peer graces exactly like a missed audit response.
5373            let class = AuditResponderClass::CommitmentPin;
5374            let guard = match admit_audit_responder(
5375                &ctx.audit_responder_semaphore,
5376                &ctx.audit_responder_inflight,
5377                source,
5378                class,
5379            )
5380            .await
5381            {
5382                Ok(guard) => guard,
5383                Err(failure) => {
5384                    audit_metrics::record_admission_drop(class);
5385                    ctx.audit_responder_metrics
5386                        .record_drop(*source, failure.reason.into());
5387                    warn!(
5388                        target: "ant_node::replication::audit_responder",
5389                        event = "admission_dropped",
5390                        kind = "commitment_pin",
5391                        responder_class = class.as_str(),
5392                        source = %source,
5393                        challenge_id = msg.request_id,
5394                        request_response = rr_message_id.is_some(),
5395                        dispatch_ms = received_at.elapsed().as_millis(),
5396                        reason = failure.reason.as_str(),
5397                        global_inflight = failure.global_inflight,
5398                        global_limit = failure.global_limit,
5399                        peer_inflight = failure.peer_inflight,
5400                        peer_limit = failure.peer_limit,
5401                        "Audit responder admission dropped"
5402                    );
5403                    return Ok(());
5404                }
5405            };
5406            ctx.audit_responder_metrics.record_admitted(
5407                *source,
5408                guard.global_inflight,
5409                guard.peer_inflight,
5410            );
5411            info!(
5412                target: "ant_node::replication::audit_responder",
5413                event = "admitted",
5414                kind = "commitment_pin",
5415                responder_class = class.as_str(),
5416                source = %source,
5417                challenge_id = msg.request_id,
5418                request_response = rr_message_id.is_some(),
5419                dispatch_ms = received_at.elapsed().as_millis(),
5420                global_inflight = guard.global_inflight,
5421                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5422                peer_inflight = guard.peer_inflight,
5423                peer_limit = class.per_peer_limit(),
5424                "Audit responder request admitted"
5425            );
5426            let worker_started = Instant::now();
5427            let processing_started = Instant::now();
5428            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5429                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5430                |built| protocol::GetCommitmentByPinResponse::Found {
5431                    commitment: built.commitment().clone(),
5432                },
5433            );
5434            let processing = processing_started.elapsed();
5435            let response_kind = commitment_pin_response_kind(&response);
5436            let response_send_started = Instant::now();
5437            let sent = send_replication_response_checked(
5438                source,
5439                &ctx.p2p_node,
5440                msg.request_id,
5441                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5442                rr_message_id,
5443                None,
5444            )
5445            .await;
5446            let response_send = response_send_started.elapsed();
5447            log_audit_responder_completion(
5448                &ctx.audit_responder_metrics,
5449                *source,
5450                class,
5451                "commitment_pin",
5452                msg.request_id,
5453                1,
5454                response_kind,
5455                sent,
5456                received_at,
5457                worker_started,
5458                processing,
5459                response_send,
5460            );
5461            drop(guard);
5462            Ok(())
5463        }
5464        // Response messages are handled by their respective request initiators.
5465        ReplicationMessageBody::FreshReplicationResponse(_)
5466        | ReplicationMessageBody::NeighborSyncResponse(_)
5467        | ReplicationMessageBody::VerificationResponse(_)
5468        | ReplicationMessageBody::FetchResponse(_)
5469        | ReplicationMessageBody::AuditResponse(_)
5470        | ReplicationMessageBody::SubtreeAuditResponse(_)
5471        | ReplicationMessageBody::SubtreeSliceResponse(_)
5472        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5473    }
5474}
5475
5476// ---------------------------------------------------------------------------
5477// Per-message-type handlers
5478// ---------------------------------------------------------------------------
5479
5480/// Verify a payment proof, yielding early if the engine is shutting down.
5481///
5482/// Returns `None` when shutdown won the race, meaning no verdict was reached
5483/// and the caller must abandon the message without storing or penalising.
5484///
5485/// Payment verification is pure network I/O — an EVM round trip and, on the
5486/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5487/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5488/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5489/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5490/// is guaranteed to end.
5491///
5492/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5493/// dropping its awaiter would detach a live LMDB transaction and break the
5494/// very contract the unbounded wait exists to uphold.
5495async fn verify_payment_until_shutdown(
5496    payment_verifier: &Arc<PaymentVerifier>,
5497    key: &XorName,
5498    proof_of_payment: &[u8],
5499    context: VerificationContext,
5500    shutdown: &CancellationToken,
5501) -> Option<Result<crate::payment::PaymentStatus>> {
5502    tokio::select! {
5503        () = shutdown.cancelled() => None,
5504        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5505            Some(result)
5506        }
5507    }
5508}
5509
5510/// A fresh offer rejected on payload shape alone.
5511struct FreshOfferRejection {
5512    /// Wire-visible reason returned to the sender.
5513    reason: String,
5514    /// Whether the sender is charged for it. Reserved for offers no honest
5515    /// node would construct, so an ordinary capacity refusal stays free.
5516    penalise: bool,
5517}
5518
5519/// Reject a fresh offer on payload shape, or return `None` to admit it.
5520///
5521/// Pure and non-blocking by construction: these are the checks answerable from
5522/// the payload alone, run on the serial message loop *before* the in-flight
5523/// claim and the admission permit, so a malformed offer can neither lock an
5524/// honest offer out of its key nor occupy one of the scarce
5525/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5526/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5527/// verification — stays on the worker.
5528///
5529/// The content-address hash is deliberately included despite costing real CPU
5530/// on the loop: it is what makes the entry below *earned* rather than merely
5531/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5532/// arrive at link speed, so a flooder can never make this loop hash faster than
5533/// it can deliver the bytes, and delivering them already cost it more than the
5534/// hash costs us. The receive path has in any case already deserialised the
5535/// same buffer.
5536///
5537/// Every rejection here is penalised. These are the conditions no honest sender
5538/// can produce — an absent, undersized, oversized, or non-matching payload — as
5539/// distinct from a capacity refusal, which is this node's own state and stays
5540/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5541/// proof that fails to verify may simply have been read against a lagging chain
5542/// view, and penalising that would charge honest senders in correlated bursts.
5543fn fresh_offer_structural_rejection(
5544    key: &XorName,
5545    data: &[u8],
5546    proof_of_payment: &[u8],
5547) -> Option<FreshOfferRejection> {
5548    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5549    // and an absent proof is the cheapest possible slot-filler, so this is the
5550    // first thing checked.
5551    if proof_of_payment.is_empty() {
5552        return Some(FreshOfferRejection {
5553            reason: "Missing proof of payment".to_string(),
5554            penalise: true,
5555        });
5556    }
5557
5558    // Bound the proof before it can be queued. The verifier applies the same
5559    // limits, but only once the offer reaches a worker — too late here, because
5560    // an entry retains a proof per queued sender, and a proof is capped on the
5561    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5562    // a byte of data and a 10 MiB "proof" would be admitted, and
5563    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5564    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5565    // admission bound exists to enforce.
5566    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5567        return Some(FreshOfferRejection {
5568            reason: format!(
5569                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5570                proof_of_payment.len(),
5571            ),
5572            penalise: true,
5573        });
5574    }
5575    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5576        return Some(FreshOfferRejection {
5577            reason: format!(
5578                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5579                proof_of_payment.len(),
5580            ),
5581            penalise: true,
5582        });
5583    }
5584
5585    // Enforce chunk size invariant: the normal PUT path rejects data larger
5586    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5587    // prevent peers from pushing oversized records through replication.
5588    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5589        return Some(FreshOfferRejection {
5590            reason: format!(
5591                "Data size {} exceeds maximum chunk size {}",
5592                data.len(),
5593                crate::ant_protocol::MAX_CHUNK_SIZE,
5594            ),
5595            penalise: true,
5596        });
5597    }
5598
5599    // Mirror the normal PUT path: the advertised key must be the content
5600    // address of the supplied bytes. Ordered last so an oversized payload is
5601    // refused without being hashed.
5602    //
5603    // This is the check that makes the entry safe to open, and safe for later
5604    // offers to be folded into. Until it passes, the sender has only *asserted*
5605    // an association between the key and the bytes. Opening an entry on an
5606    // assertion would let any peer that knows a key — every recipient of its
5607    // `PaidNotify`, not just the close group — seize it with junk; folding a
5608    // later offer into an entry on an assertion would be worse still, since the
5609    // handler tries each queued proof against the *opener's* bytes and would be
5610    // storing bytes nobody offered for that proof.
5611    let computed_key = crate::client::compute_address(data);
5612    if computed_key != *key {
5613        return Some(FreshOfferRejection {
5614            reason: format!(
5615                "Content address mismatch: expected {}, computed {}",
5616                hex::encode(key),
5617                hex::encode(computed_key),
5618            ),
5619            penalise: true,
5620        });
5621    }
5622
5623    None
5624}
5625
5626/// Tell `source` its offer for `key` was not taken.
5627///
5628/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5629/// one-way `send_message`, so the refusal is observed only as a later absence by
5630/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5631async fn refuse_fresh_offer(
5632    source: &PeerId,
5633    key: XorName,
5634    reason: String,
5635    ctx: &ReplicationMessageHandlerContext,
5636    request_id: u64,
5637    rr_message_id: Option<&str>,
5638) {
5639    send_replication_response(
5640        source,
5641        &ctx.p2p_node,
5642        request_id,
5643        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5644            key,
5645            reason,
5646        }),
5647        rr_message_id,
5648    )
5649    .await;
5650}
5651
5652/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5653/// the sender when the defect is one no honest node could produce.
5654///
5655/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5656/// two say opposite things: this is the sender's fault, that one is ours.
5657async fn refuse_malformed_fresh_offer(
5658    source: &PeerId,
5659    key: XorName,
5660    rejection: FreshOfferRejection,
5661    ctx: &ReplicationMessageHandlerContext,
5662    request_id: u64,
5663    rr_message_id: Option<&str>,
5664) {
5665    if rejection.penalise {
5666        warn!(
5667            "Rejecting fresh offer for key {} from {source}: {}",
5668            hex::encode(key),
5669            rejection.reason
5670        );
5671        ctx.p2p_node
5672            .report_trust_event(
5673                source,
5674                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5675            )
5676            .await;
5677    } else {
5678        debug!(
5679            "Fresh offer for {} from {source} refused before admission: {}",
5680            hex::encode(key),
5681            rejection.reason
5682        );
5683    }
5684    refuse_fresh_offer(
5685        source,
5686        key,
5687        rejection.reason,
5688        ctx,
5689        request_id,
5690        rr_message_id,
5691    )
5692    .await;
5693}
5694
5695/// Tell senders whose proofs joined an entry that was torn down before a handler
5696/// ever ran for it.
5697///
5698/// Only reachable in the window between opening an entry and failing to take an
5699/// admission permit. Their proofs are answered rather than dropped with the
5700/// entry, so the refusal count reflects what actually happened.
5701async fn refuse_stranded_fresh_offers(
5702    key: XorName,
5703    stranded: Vec<FreshOfferAttempt>,
5704    ctx: &ReplicationMessageHandlerContext,
5705) {
5706    for attempt in stranded {
5707        refuse_fresh_offer(
5708            &attempt.source,
5709            key,
5710            "Receiver at fresh-offer capacity".to_string(),
5711            ctx,
5712            attempt.request_id,
5713            attempt.rr_message_id.as_deref(),
5714        )
5715        .await;
5716    }
5717}
5718
5719/// Admit a fresh offer for handling on a worker, or refuse it.
5720///
5721/// This runs on the serial non-audit message loop, so it must stay cheap: every
5722/// path here is a set insert, a permit try, or a small response send. The offer
5723/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5724/// runs on a tracked worker task, never inline, because stalling this loop backs
5725/// up the inbound queue and ultimately drops replication messages wholesale.
5726///
5727/// Admission is bounded **per source** as well as globally
5728/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5729/// hold every slot, and since a refusal is later read as absence by the
5730/// sender's delayed possession check, the resulting refusals land as
5731/// audit-severity penalties on this node rather than on the flooder.
5732///
5733/// The structurally-invalid checks run **before** the entry is opened and before
5734/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5735/// the duration of a payment verification.
5736///
5737/// Only the offer that *opens* an entry costs a permit and a worker. Later
5738/// offers for the same key contribute their proof and are answered by whatever
5739/// the opener's handler concludes, which is what keeps the routine
5740/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5741/// one verification per key.
5742async fn dispatch_fresh_offer(
5743    source: PeerId,
5744    offer: protocol::FreshReplicationOffer,
5745    ctx: &ReplicationMessageHandlerContext,
5746    request_id: u64,
5747    received_at: Instant,
5748    rr_message_id: Option<&str>,
5749) -> Result<()> {
5750    if let Some(rejection) =
5751        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5752    {
5753        refuse_malformed_fresh_offer(
5754            &source,
5755            offer.key,
5756            rejection,
5757            ctx,
5758            request_id,
5759            rr_message_id,
5760        )
5761        .await;
5762        return Ok(());
5763    }
5764
5765    // Join the work already in flight for this key before taking an admission
5766    // permit, so the duplicates a single client PUT produces cost one permit
5767    // between them rather than one each.
5768    //
5769    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5770    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5771    // already held for the key. That is what lets its payload be dropped here
5772    // and only its proof retained: the handler will try that proof against the
5773    // bytes it already has.
5774    let key = offer.key;
5775    let admission_outcome = FreshOfferEntryGuard::admit(
5776        &ctx.fresh_offer_in_flight,
5777        offer,
5778        source,
5779        request_id,
5780        rr_message_id.map(ToOwned::to_owned),
5781        received_at,
5782    );
5783    let mut entry = match admission_outcome {
5784        FreshOfferAdmission::Opened(entry) => entry,
5785        FreshOfferAdmission::Joined => {
5786            // No response yet: this proof has not been judged. The handler that
5787            // owns the key answers every queued sender once it settles.
5788            debug!(
5789                "Fresh offer for {} from {source} queued behind the handler already \
5790                 holding the key",
5791                hex::encode(key)
5792            );
5793            return Ok(());
5794        }
5795        // Surplus, not suspect: the proofs already queued are enough to place
5796        // the record, so neither case is charged as misbehaviour.
5797        surplus => {
5798            debug!(
5799                "Fresh offer for {} from {source} refused: {}",
5800                hex::encode(key),
5801                surplus.surplus_reason()
5802            );
5803            refuse_fresh_offer(
5804                &source,
5805                key,
5806                "Duplicate offer already in flight".to_string(),
5807                ctx,
5808                request_id,
5809                rr_message_id,
5810            )
5811            .await;
5812            return Ok(());
5813        }
5814    };
5815
5816    let admission = match admit_bounded_responder(
5817        &ctx.fresh_offer_admission_semaphore,
5818        &ctx.fresh_offer_responder_inflight,
5819        &source,
5820        FRESH_OFFER_MAX_OUTSTANDING,
5821        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5822    )
5823    .await
5824    {
5825        Ok(guard) => guard,
5826        Err(failure) => {
5827            audit_metrics::record_responder_admission_drop(
5828                ReplicationResponderClass::FreshOffer,
5829                failure.reason.into(),
5830            );
5831            // WARN, not DEBUG: a healthy node should never refuse a legitimate
5832            // fresh offer. The sender does not read this refusal, so it
5833            // resurfaces as a missing key at the delayed possession check and
5834            // is charged to US at audit severity. Log the binding ceiling
5835            // locally; the wire reason stays generic so a probing peer cannot
5836            // map out this node's live occupancy.
5837            warn!(
5838                responder_class = "fresh_offer",
5839                source = %source,
5840                key = %hex::encode(key),
5841                penalty_suspended = config::close_group_storage_penalty_suspended(),
5842                "Fresh offer refused at admission; the resulting absence is recorded \
5843                 against this node, and penalised unless the release withholds it: \
5844                 {failure}"
5845            );
5846            // Release the key explicitly rather than on drop, so the next offer
5847            // opens a fresh entry rather than queueing behind a handler that was
5848            // never spawned — and so any proof that joined in the window between
5849            // opening the entry and failing here is answered rather than
5850            // discarded with it.
5851            let stranded = entry.release();
5852            refuse_fresh_offer(
5853                &source,
5854                key,
5855                "Receiver at fresh-offer capacity".to_string(),
5856                ctx,
5857                request_id,
5858                rr_message_id,
5859            )
5860            .await;
5861            refuse_stranded_fresh_offers(key, stranded, ctx).await;
5862            return Ok(());
5863        }
5864    };
5865
5866    let ctx = ctx.clone();
5867    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5868    // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
5869    // those references be released before the caller reopens the environment.
5870    ctx.detached_task_tracker
5871        .clone()
5872        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5873    Ok(())
5874}
5875
5876/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5877///
5878/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5879/// A started handler is never cancelled: `storage.put()` awaits
5880/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5881/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5882/// and from `handle_fresh_offer` racing the token around payment verification.
5883///
5884/// Works down the key's queued proofs rather than judging the key on the first
5885/// one. A proof that fails to establish payment disqualifies its *sender*, not
5886/// the record: the bytes are content-addressed and identical across every offer,
5887/// so the next sender's proof is tried against the copy already in hand — no
5888/// second payload, no second permit, no refetch. Only when a failure is about
5889/// the key itself (not responsible, no capacity, shutting down) does rotating
5890/// become pointless, because every remaining proof would meet the same wall.
5891async fn run_fresh_offer_worker(
5892    key: XorName,
5893    mut entry: Box<FreshOfferEntryGuard>,
5894    ctx: ReplicationMessageHandlerContext,
5895    admission: ResponderGuard,
5896) {
5897    // The admission permit is released on completion, freeing the payload's
5898    // memory budget and the opening source's per-peer share. The entry releases
5899    // the key itself, either as the queue empties or on drop.
5900    let _admission = admission;
5901    let received_at = entry.received_at();
5902    // Wait for a worker slot here rather than in the caller. The worker bound
5903    // caps concurrent EVM and storage pressure; making the message loop wait on
5904    // it is what put that pressure back on the loop.
5905    //
5906    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5907    // path for offers still queued behind a worker when the engine stops — not
5908    // dead code.
5909    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5910        .acquire_owned()
5911        .await
5912    else {
5913        debug!(
5914            "Fresh offer for {} dropped: worker pool shut down",
5915            hex::encode(key)
5916        );
5917        return;
5918    };
5919    // Fresh offers are fire-and-forget (`send_message`), so there is no
5920    // requester deadline to honour and a late store is still genuinely useful.
5921    // The threshold is the point past which the offer has already cost us what
5922    // it was going to cost: the possession check (ADR-0003) has run by then and
5923    // charged the absence to this node, and it does not re-offer the key —
5924    // repair comes later from neighbor sync. Shedding here trades a copy that
5925    // would have arrived after the penalty for the multi-MiB payload it is
5926    // holding, and keeps a backlog from outliving its own admission bound.
5927    //
5928    // Note this is a memory-pressure decision, not a redundancy one: the copy
5929    // is late, not useless, so on a node with headroom finishing it would still
5930    // beat waiting for neighbor sync.
5931    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5932        debug!(
5933            responder_class = "fresh_offer",
5934            key = %hex::encode(key),
5935            request_age_ms = received_at.elapsed().as_millis(),
5936            "Superseded fresh offer shed at dequeue"
5937        );
5938        return;
5939    }
5940
5941    let mut verdict = FreshOfferOutcome::Abandoned;
5942    while let Some(attempt) = entry.next_attempt() {
5943        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5944            Ok(outcome) => {
5945                verdict = outcome;
5946                match outcome {
5947                    // Settled: the record is down and every remaining sender
5948                    // wanted exactly that. Abandoned: the key cannot be placed
5949                    // by anyone right now, so the proofs behind this one would
5950                    // fail identically. Either way there is nothing left to try.
5951                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5952                    // This sender's claim to have paid did not hold up. Say so
5953                    // to that sender alone and try the next proof.
5954                    FreshOfferOutcome::ProofRejected => {}
5955                }
5956            }
5957            Err(e) => {
5958                debug!(
5959                    "Fresh replication offer for {} from {} error: {e}",
5960                    hex::encode(key),
5961                    attempt.source
5962                );
5963                verdict = FreshOfferOutcome::Abandoned;
5964                break;
5965            }
5966        }
5967    }
5968
5969    // Answer the senders whose proofs were never reached. A stored record is
5970    // what they were asking for, so it is an acceptance even though their own
5971    // proof went untested.
5972    let unreached = entry.release();
5973    if unreached.is_empty() {
5974        return;
5975    }
5976    let response = match verdict {
5977        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5978        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5979            FreshReplicationResponse::Rejected {
5980                key,
5981                reason: "Record could not be stored from any offered proof".to_string(),
5982            }
5983        }
5984    };
5985    for attempt in unreached {
5986        send_replication_response(
5987            &attempt.source,
5988            &ctx.p2p_node,
5989            attempt.request_id,
5990            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5991            attempt.rr_message_id.as_deref(),
5992        )
5993        .await;
5994    }
5995}
5996
5997/// What one proof concluded, and whether another proof for the same key is worth
5998/// trying.
5999///
6000/// The distinction the worker acts on is *what the failure was about*. A
6001/// rejected proof is a statement about its sender; anything else is a statement
6002/// about the key or this node, which no other sender's proof can change.
6003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6004enum FreshOfferOutcome {
6005    /// The record is stored. The key is done.
6006    Settled,
6007    /// This proof did not establish payment. A different sender's proof for the
6008    /// same bytes may still succeed.
6009    ProofRejected,
6010    /// Nothing about this key can succeed right now — not responsible, no disk,
6011    /// shutting down, or a write that failed. Rotating repeats the failure.
6012    Abandoned,
6013}
6014
6015// A linear sequence of protocol steps — structural recheck, responsibility,
6016// capacity, payment, write — each with its own refusal response. Splitting it
6017// would scatter one decision across several functions.
6018#[allow(clippy::too_many_lines)]
6019async fn handle_fresh_offer(
6020    key: &XorName,
6021    data: &[u8],
6022    attempt: &FreshOfferAttempt,
6023    ctx: &ReplicationMessageHandlerContext,
6024) -> Result<FreshOfferOutcome> {
6025    let source = &attempt.source;
6026    let request_id = attempt.request_id;
6027    let rr_message_id = attempt.rr_message_id.as_deref();
6028    let p2p_node = &ctx.p2p_node;
6029    let config = &ctx.config;
6030    let self_id = *p2p_node.peer_id();
6031
6032    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6033    // proof, bad proof size, oversized payload, content-address mismatch —
6034    // before opening the entry or taking an admission permit, so nothing
6035    // reaching a worker should trip them. Kept so the handler is correct in
6036    // isolation. Note this re-checks the *pairing* actually being used: these
6037    // bytes against this attempt's proof.
6038    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6039    {
6040        if rejection.penalise {
6041            warn!(
6042                "Rejecting fresh offer for key {}: {}",
6043                hex::encode(key),
6044                rejection.reason
6045            );
6046            p2p_node
6047                .report_trust_event(
6048                    source,
6049                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6050                )
6051                .await;
6052        }
6053        send_replication_response(
6054            source,
6055            p2p_node,
6056            request_id,
6057            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6058                key: *key,
6059                reason: rejection.reason,
6060            }),
6061            rr_message_id,
6062        )
6063        .await;
6064        // Structurally invalid is a fact about this attempt, not the key.
6065        return Ok(FreshOfferOutcome::ProofRejected);
6066    }
6067
6068    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6069    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6070    // the same width client PUTs use), not just the close group plus a small
6071    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6072    // table may still list closer full nodes it hasn't evicted yet, ranking it
6073    // outside the narrow window in its own view; the wider accept window absorbs
6074    // that transient skew so the chunk still lands. Retention (pruning) stays at
6075    // `storage_admission_width`, so steady-state replication is unchanged.
6076    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6077    {
6078        send_replication_response(
6079            source,
6080            p2p_node,
6081            request_id,
6082            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6083                key: *key,
6084                reason: "Not in storage-admission range for this key".to_string(),
6085            }),
6086            rr_message_id,
6087        )
6088        .await;
6089        // About the key and this node's place in the routing table, not about
6090        // the sender: every queued proof would be refused identically.
6091        return Ok(FreshOfferOutcome::Abandoned);
6092    }
6093
6094    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6095    // never store this record, so reject it before the expensive payment
6096    // verification (EVM on-chain query / merkle pool work) rather than verifying
6097    // and only then failing at `storage.put` below. Reuses the cached capacity
6098    // check (passing results only, so freed space is detected promptly), and the
6099    // store path keeps its own check as defence-in-depth.
6100    if let Err(e) = ctx.storage.check_capacity() {
6101        info!(
6102            target: "ant_node::storage::disk_precheck",
6103            key = %hex::encode(key),
6104            "Rejecting fresh replication offer before payment verification: {e}"
6105        );
6106        send_replication_response(
6107            source,
6108            p2p_node,
6109            request_id,
6110            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6111                key: *key,
6112                reason: e.to_string(),
6113            }),
6114            rr_message_id,
6115        )
6116        .await;
6117        // A full disk is this node's condition, not the sender's.
6118        return Ok(FreshOfferOutcome::Abandoned);
6119    }
6120
6121    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6122    // part of the immediate write fan-out: this receiver is about to store the
6123    // record as if the client had PUT it here directly. Storage admission
6124    // was checked above before proof work. FreshReplication verification is
6125    // identical to ClientPut — store-strength cache semantics, paid-quote
6126    // issuer K-closeness checks for single-node proofs, merkle candidate
6127    // closeness for merkle proofs, and the same price-floor policy — the
6128    // distinct context only labels price-floor telemetry.
6129    let Some(verification) = verify_payment_until_shutdown(
6130        &ctx.payment_verifier,
6131        key,
6132        &attempt.proof_of_payment,
6133        fresh_offer_payment_context(),
6134        &ctx.shutdown,
6135    )
6136    .await
6137    else {
6138        debug!(
6139            "Fresh offer for {} from {source} abandoned: engine shutting down \
6140             during payment verification",
6141            hex::encode(key)
6142        );
6143        return Ok(FreshOfferOutcome::Abandoned);
6144    };
6145    match verification {
6146        Ok(status) if status.can_store() => {
6147            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6148        }
6149        // The chain has no record of this payment. That is a statement about
6150        // *this sender's* proof, so the key rotates to the next one rather than
6151        // being written off — the whole point of queueing them.
6152        //
6153        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6154        // not "definitively unpaid", so a lagging or reorganising chain view
6155        // renders honest senders indistinguishable from forgers, and penalising
6156        // would land on the entire close group at once. The structural checks in
6157        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6158        // because those cannot be produced by an honest sender at all.
6159        Ok(_) => {
6160            debug!(
6161                "Fresh offer for {} from {source}: no payment found for this proof",
6162                hex::encode(key)
6163            );
6164            send_replication_response(
6165                source,
6166                p2p_node,
6167                request_id,
6168                ReplicationMessageBody::FreshReplicationResponse(
6169                    FreshReplicationResponse::Rejected {
6170                        key: *key,
6171                        reason: "Payment verification failed: payment required".to_string(),
6172                    },
6173                ),
6174                rr_message_id,
6175            )
6176            .await;
6177            return Ok(FreshOfferOutcome::ProofRejected);
6178        }
6179        // A verification *error* is usually ours — an unreachable or failing EVM
6180        // endpoint — so it is neither penalised nor treated as this sender's
6181        // fault. Another proof still gets its turn, since the next call may well
6182        // succeed against a recovered endpoint.
6183        Err(e) => {
6184            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6185            send_replication_response(
6186                source,
6187                p2p_node,
6188                request_id,
6189                ReplicationMessageBody::FreshReplicationResponse(
6190                    FreshReplicationResponse::Rejected {
6191                        key: *key,
6192                        reason: format!("Payment verification error: {e}"),
6193                    },
6194                ),
6195                rr_message_id,
6196            )
6197            .await;
6198            return Ok(FreshOfferOutcome::ProofRejected);
6199        }
6200    }
6201
6202    // Rule 6: add to PaidForList.
6203    if let Err(e) = ctx.paid_list.insert(key).await {
6204        warn!("Failed to add key to PaidForList: {e}");
6205    }
6206
6207    // Store the record.
6208    match ctx.storage.put(key, data).await {
6209        Ok(_) => {
6210            send_replication_response(
6211                source,
6212                p2p_node,
6213                request_id,
6214                ReplicationMessageBody::FreshReplicationResponse(
6215                    FreshReplicationResponse::Accepted { key: *key },
6216                ),
6217                rr_message_id,
6218            )
6219            .await;
6220            Ok(FreshOfferOutcome::Settled)
6221        }
6222        Err(e) => {
6223            send_replication_response(
6224                source,
6225                p2p_node,
6226                request_id,
6227                ReplicationMessageBody::FreshReplicationResponse(
6228                    FreshReplicationResponse::Rejected {
6229                        key: *key,
6230                        reason: e.to_string(),
6231                    },
6232                ),
6233                rr_message_id,
6234            )
6235            .await;
6236            // The payment was good and the write still failed, so this is local
6237            // storage trouble that another proof cannot get around.
6238            Ok(FreshOfferOutcome::Abandoned)
6239        }
6240    }
6241}
6242
6243/// Admit a paid-list notification for handling on a worker, or drop it.
6244///
6245/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6246/// meant one message could park every other non-audit message behind a full
6247/// payment verification. That verification is not a bounded local computation:
6248/// on the merkle path it performs an iterative Kademlia lookup capped only by
6249/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6250/// the loop for minutes while the bounded inbound queue behind it overflowed
6251/// and dropped unrelated replication traffic wholesale.
6252///
6253/// It now follows the same detached-responder pattern as neighbor sync and
6254/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6255/// when stale, and run on a tracked worker.
6256///
6257/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6258/// refused notify is simply dropped. The sender's own paid-list convergence
6259/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6260/// the recovery path, exactly as for a notify lost in transit.
6261async fn dispatch_paid_notify(
6262    source: PeerId,
6263    notify: protocol::PaidNotify,
6264    ctx: &ReplicationMessageHandlerContext,
6265    received_at: Instant,
6266) -> Result<()> {
6267    let admission = match admit_bounded_responder(
6268        &ctx.paid_notify_admission_semaphore,
6269        &ctx.paid_notify_responder_inflight,
6270        &source,
6271        PAID_NOTIFY_MAX_OUTSTANDING,
6272        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6273    )
6274    .await
6275    {
6276        Ok(guard) => guard,
6277        Err(failure) => {
6278            audit_metrics::record_responder_admission_drop(
6279                ReplicationResponderClass::PaidNotify,
6280                failure.reason.into(),
6281            );
6282            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6283            // so a refusal discards durable paid-list evidence outright rather
6284            // than pushing work back onto a requester.
6285            warn!(
6286                responder_class = "paid_notify",
6287                source = %source,
6288                key = %hex::encode(notify.key),
6289                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6290            );
6291            return Ok(());
6292        }
6293    };
6294
6295    let ctx = ctx.clone();
6296    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6297    // Deliberately NOT the verification request deadline used by the
6298    // request/response responders. Nobody is waiting on a notify, and shedding
6299    // one discards durable paid-list evidence rather than a reply a requester
6300    // has already given up on. The threshold is instead the point at which the
6301    // pull path would have learned the same fact anyway: one slow-cadence
6302    // neighbor-sync interval, after which the verification cycle's paid-list
6303    // quorum makes this notify genuinely redundant.
6304    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6305    ctx.detached_task_tracker.clone().spawn(async move {
6306        let _admission = admission;
6307        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6308        // still queued behind a worker when the engine stops.
6309        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6310            debug!("Paid notify from {source} dropped: worker pool shut down");
6311            return;
6312        };
6313        if request_is_stale(received_at, queue_max_age) {
6314            debug!(
6315                responder_class = "paid_notify",
6316                source = %source,
6317                request_age_ms = received_at.elapsed().as_millis(),
6318                "Redundant paid notify shed at dequeue"
6319            );
6320            return;
6321        }
6322        if let Err(e) = handle_paid_notify(
6323            &source,
6324            &notify,
6325            &ctx.paid_list,
6326            &ctx.payment_verifier,
6327            &ctx.p2p_node,
6328            &ctx.config,
6329            &ctx.shutdown,
6330        )
6331        .await
6332        {
6333            debug!("Paid notify from {source} error: {e}");
6334        }
6335    });
6336
6337    Ok(())
6338}
6339
6340async fn handle_paid_notify(
6341    _source: &PeerId,
6342    notify: &protocol::PaidNotify,
6343    paid_list: &Arc<PaidList>,
6344    payment_verifier: &Arc<PaymentVerifier>,
6345    p2p_node: &Arc<P2PNode>,
6346    config: &ReplicationConfig,
6347    shutdown: &CancellationToken,
6348) -> Result<()> {
6349    let self_id = *p2p_node.peer_id();
6350
6351    // Rule 3: validate PoP presence before adding.
6352    if notify.proof_of_payment.is_empty() {
6353        return Ok(());
6354    }
6355
6356    // Check if we're in PaidCloseGroup for this key.
6357    if !admission::is_in_paid_close_group(
6358        &self_id,
6359        &notify.key,
6360        p2p_node,
6361        config.paid_list_close_group_size,
6362    )
6363    .await
6364    {
6365        return Ok(());
6366    }
6367
6368    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6369    // paid-list metadata, so local paid-list close-group membership was checked
6370    // above before proof work. The verifier then runs the same payment proof
6371    // checks as ClientPut while writing a paid-list-strength cache entry.
6372    let Some(verification) = verify_payment_until_shutdown(
6373        payment_verifier,
6374        &notify.key,
6375        &notify.proof_of_payment,
6376        paid_notify_payment_context(),
6377        shutdown,
6378    )
6379    .await
6380    else {
6381        debug!(
6382            "Paid notify for {} abandoned: engine shutting down during payment \
6383             verification",
6384            hex::encode(notify.key)
6385        );
6386        return Ok(());
6387    };
6388    match verification {
6389        Ok(status) if status.can_store() => {
6390            debug!(
6391                "PoP validated for paid notify key {}",
6392                hex::encode(notify.key)
6393            );
6394        }
6395        Ok(_) => {
6396            warn!(
6397                "Paid notify rejected: payment required for key {}",
6398                hex::encode(notify.key)
6399            );
6400            return Ok(());
6401        }
6402        Err(e) => {
6403            warn!(
6404                "PoP verification error for paid notify key {}: {e}",
6405                hex::encode(notify.key)
6406            );
6407            return Ok(());
6408        }
6409    }
6410
6411    if let Err(e) = paid_list.insert(&notify.key).await {
6412        warn!("Failed to add paid notify key to PaidForList: {e}");
6413    }
6414
6415    Ok(())
6416}
6417
6418#[allow(clippy::too_many_arguments)]
6419async fn dispatch_neighbor_sync_request(
6420    source: PeerId,
6421    request: protocol::NeighborSyncRequest,
6422    ctx: &ReplicationMessageHandlerContext,
6423    is_bootstrapping: bool,
6424    my_commitment: Option<StorageCommitment>,
6425    request_id: u64,
6426    received_at: Instant,
6427    rr_message_id: Option<&str>,
6428) -> Result<()> {
6429    let guard = match admit_bounded_responder(
6430        &ctx.neighbor_sync_responder_admission_semaphore,
6431        &ctx.neighbor_sync_responder_inflight,
6432        &source,
6433        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6434        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6435    )
6436    .await
6437    {
6438        Ok(guard) => guard,
6439        Err(failure) => {
6440            audit_metrics::record_responder_admission_drop(
6441                ReplicationResponderClass::NeighborSync,
6442                failure.reason.into(),
6443            );
6444            warn!(
6445                responder_class = "neighbor_sync",
6446                source = %source,
6447                "Neighbor-sync response dropped at admission: {failure}"
6448            );
6449            return Ok(());
6450        }
6451    };
6452
6453    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6454    let p2p_node = Arc::clone(&ctx.p2p_node);
6455    let storage = Arc::clone(&ctx.storage);
6456    let paid_list = Arc::clone(&ctx.paid_list);
6457    let queues = Arc::clone(&ctx.queues);
6458    let config = Arc::clone(&ctx.config);
6459    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6460    let sync_history = Arc::clone(&ctx.sync_history);
6461    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6462    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6463    let request_timeout = ctx.config.verification_request_timeout;
6464    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6465    ctx.detached_task_tracker.spawn(async move {
6466        let _guard = guard;
6467        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6468            debug!(
6469                responder_class = "neighbor_sync",
6470                source = %source,
6471                "Neighbor-sync responder worker pool closed before dequeue"
6472            );
6473            return;
6474        };
6475        if request_is_stale(received_at, request_timeout) {
6476            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6477            debug!(
6478                responder_class = "neighbor_sync",
6479                source = %source,
6480                request_age_ms = received_at.elapsed().as_millis(),
6481                "Stale neighbor-sync request shed at dequeue"
6482            );
6483            return;
6484        }
6485        if let Err(e) = handle_neighbor_sync_request(
6486            &source,
6487            &request,
6488            &p2p_node,
6489            &storage,
6490            &paid_list,
6491            &queues,
6492            &config,
6493            is_bootstrapping,
6494            &bootstrap_state,
6495            &sync_history,
6496            &sync_cycle_epoch,
6497            &repair_proofs,
6498            my_commitment,
6499            request_id,
6500            rr_message_id.as_deref(),
6501        )
6502        .await
6503        {
6504            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6505        }
6506    });
6507
6508    Ok(())
6509}
6510
6511#[allow(clippy::too_many_arguments)]
6512async fn handle_neighbor_sync_request(
6513    source: &PeerId,
6514    request: &protocol::NeighborSyncRequest,
6515    p2p_node: &Arc<P2PNode>,
6516    storage: &Arc<ChunkStore>,
6517    paid_list: &Arc<PaidList>,
6518    queues: &Arc<RwLock<ReplicationQueues>>,
6519    config: &ReplicationConfig,
6520    is_bootstrapping: bool,
6521    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6522    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6523    sync_cycle_epoch: &Arc<RwLock<u64>>,
6524    repair_proofs: &Arc<RwLock<RepairProofs>>,
6525    my_commitment: Option<StorageCommitment>,
6526    request_id: u64,
6527    rr_message_id: Option<&str>,
6528) -> Result<()> {
6529    let self_id = *p2p_node.peer_id();
6530
6531    // No per-request hint count limit: the wire message size limit
6532    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6533    // challenges, sync hints don't drive expensive computation — they just
6534    // enter the verification queue. A per-request limit here would break
6535    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6536
6537    // Build response (outbound hints).
6538    let (response, sent_replica_hints, sender_in_rt) =
6539        neighbor_sync::handle_sync_request_with_proofs(
6540            source,
6541            request,
6542            p2p_node,
6543            storage,
6544            paid_list,
6545            config,
6546            is_bootstrapping,
6547            my_commitment.clone(),
6548        )
6549        .await;
6550
6551    // Send response.
6552    let response_sent = send_replication_response_checked(
6553        source,
6554        p2p_node,
6555        request_id,
6556        ReplicationMessageBody::NeighborSyncResponse(response),
6557        rr_message_id,
6558        None,
6559    )
6560    .await;
6561
6562    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6563    if !sender_in_rt {
6564        return Ok(());
6565    }
6566
6567    // Update sync history for this peer before recording repair proofs so a
6568    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6569    {
6570        let mut history = sync_history.write().await;
6571        let record = history.entry(*source).or_insert(PeerSyncRecord {
6572            last_sync: None,
6573            cycles_since_sync: 0,
6574        });
6575        record.last_sync = Some(Instant::now());
6576        record.cycles_since_sync = 0;
6577    }
6578
6579    if response_sent && !request.bootstrapping {
6580        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6581            .await;
6582    }
6583
6584    // Admit inbound hints and queue for verification.
6585    let outcome = admit_and_queue_hints(
6586        &self_id,
6587        source,
6588        &request.replica_hints,
6589        &request.paid_hints,
6590        p2p_node,
6591        config,
6592        storage,
6593        paid_list,
6594        queues,
6595    )
6596    .await;
6597
6598    // Track discovered keys for bootstrap drain detection so that hints
6599    // admitted via inbound sync requests are not missed. Capacity-rejected
6600    // hints keep this source on the "not yet drained" list until its next
6601    // sync re-admits them; a clean cycle clears the source.
6602    if is_bootstrapping {
6603        let live_discovered = outcome.discovered.clone();
6604        let outcomes = [(*source, outcome)];
6605        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6606    }
6607
6608    Ok(())
6609}
6610
6611/// Test-only record of who *sent* a verification request covering a watched key.
6612///
6613/// The capacity gate's entire effect is a request that is never sent, and a
6614/// request that was not sent leaves no production counter anywhere — not on the
6615/// sender, whose traffic counters are process-global and so cannot separate one
6616/// node of a single-process testnet from another, and not on the responder,
6617/// which simply never hears from it. Recording who asked is what lets a test
6618/// tell "held the key back" apart from "probed the close group, was refused at
6619/// the dial, and then held the key back", which are otherwise identical from the
6620/// queue's point of view.
6621///
6622/// Arming replaces the previous watch, so the outer map holds exactly the keys
6623/// the current test named, and each inner map holds at most one entry per node
6624/// in the process. Nothing is recorded until a test arms it, and the armed path
6625/// costs one read lock on the sending side.
6626///
6627/// Counting is per key because a node that cannot write legitimately keeps
6628/// sending verification requests for keys it has not yet authorized — that is
6629/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
6630/// would assert something untrue.
6631///
6632/// It counts *send attempts*, deliberately, recorded immediately before the wire
6633/// call. A responder sheds requests at admission and as stale, so a
6634/// receiver-side count would report zero for probes that were really sent, and
6635/// an assertion that this node asked nobody would pass on the strength of the
6636/// receiver dropping the question. It is not proof of delivery: a send that
6637/// fails immediately, with no route or during shutdown, is still counted.
6638///
6639/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
6640/// MSRV.
6641#[cfg(any(test, feature = "test-utils"))]
6642type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
6643
6644#[cfg(any(test, feature = "test-utils"))]
6645static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
6646    std::sync::OnceLock::new();
6647
6648#[cfg(any(test, feature = "test-utils"))]
6649fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
6650    VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
6651}
6652
6653/// Test-only: start counting verification requests for `keys`, from zero.
6654///
6655/// Replaces any previous watch rather than adding to it, so the map is bounded
6656/// by the keys of the test that armed it last and nothing accumulates across a
6657/// process running many tests.
6658#[cfg(any(test, feature = "test-utils"))]
6659pub fn watch_verification_requests_for_test(keys: &[XorName]) {
6660    if let Ok(mut watch) = verification_watch().write() {
6661        watch.clear();
6662        for key in keys {
6663            watch.insert(*key, HashMap::new());
6664        }
6665    }
6666}
6667
6668/// Record that `requester` sent a verification request covering `keys`, for
6669/// whichever of them are watched. A poisoned lock is ignored rather than
6670/// propagated: this is observation for tests and must never change behaviour.
6671#[cfg(any(test, feature = "test-utils"))]
6672pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
6673    // Fast path under a read lock: with nothing watched — every production
6674    // build, and every test that did not ask — this is all the sender pays.
6675    match verification_watch().read() {
6676        Ok(watch) if watch.is_empty() => return,
6677        Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
6678        Ok(_) => {}
6679        Err(_) => return,
6680    }
6681    if let Ok(mut watch) = verification_watch().write() {
6682        for key in keys {
6683            if let Some(by_peer) = watch.get_mut(key) {
6684                *by_peer.entry(*requester).or_insert(0) += 1;
6685            }
6686        }
6687    }
6688}
6689
6690/// Test-only: how many times `requester` has asked this process about `key`.
6691/// Zero unless the key was registered with `watch_verification_requests_for_test`.
6692#[cfg(any(test, feature = "test-utils"))]
6693#[must_use]
6694pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
6695    verification_watch().read().map_or(0, |watch| {
6696        watch
6697            .get(key)
6698            .and_then(|by_peer| by_peer.get(requester))
6699            .copied()
6700            .unwrap_or(0)
6701    })
6702}
6703
6704async fn handle_verification_request(
6705    source: &PeerId,
6706    request: &protocol::VerificationRequest,
6707    storage: &Arc<ChunkStore>,
6708    paid_list: &Arc<PaidList>,
6709    p2p_node: &Arc<P2PNode>,
6710    request_id: u64,
6711    rr_message_id: Option<&str>,
6712) -> Result<()> {
6713    #[derive(Clone, Copy)]
6714    enum CachedPaidLookup {
6715        NotChecked,
6716        Checked(Option<bool>),
6717    }
6718
6719    #[derive(Clone, Copy)]
6720    struct CachedVerificationLookup {
6721        present: Option<bool>,
6722        paid: CachedPaidLookup,
6723    }
6724
6725    if verification_request_exceeds_limit(request.keys.len()) {
6726        warn!(
6727            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6728            request.keys.len(),
6729        );
6730        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6731        return Ok(());
6732    }
6733
6734    let requested_keys = request.keys.as_slice();
6735
6736    if request.paid_list_check_indices.len() > request.keys.len() {
6737        warn!(
6738            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6739            request.paid_list_check_indices.len(),
6740            request.keys.len(),
6741        );
6742        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6743        return Ok(());
6744    }
6745
6746    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6747    let paid_check_set: HashSet<u32> = request
6748        .paid_list_check_indices
6749        .iter()
6750        .copied()
6751        .filter(|&idx| {
6752            if idx >= keys_len {
6753                warn!(
6754                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6755                    requested_keys.len(),
6756                );
6757                false
6758            } else {
6759                true
6760            }
6761        })
6762        .collect();
6763
6764    let mut results = Vec::with_capacity(requested_keys.len());
6765    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6766    for (i, key) in requested_keys.iter().enumerate() {
6767        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6768        let cached = lookup_cache.entry(*key).or_insert_with(|| {
6769            let present = match storage.exists(key) {
6770                Ok(present) => Some(present),
6771                Err(e) => {
6772                    warn!(
6773                        "Verification request from {source}: failed to check storage for {}: {e}",
6774                        hex::encode(key)
6775                    );
6776                    None
6777                }
6778            };
6779            CachedVerificationLookup {
6780                present,
6781                paid: CachedPaidLookup::NotChecked,
6782            }
6783        });
6784
6785        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6786            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6787                Ok(paid) => Some(paid),
6788                Err(e) => {
6789                    warn!(
6790                        "Verification request from {source}: failed to check paid-list for {}: {e}",
6791                        hex::encode(key)
6792                    );
6793                    None
6794                }
6795            });
6796        }
6797
6798        let paid = if needs_paid {
6799            match cached.paid {
6800                CachedPaidLookup::Checked(paid) => paid,
6801                CachedPaidLookup::NotChecked => None,
6802            }
6803        } else {
6804            None
6805        };
6806
6807        if cached.present.is_none() && paid.is_none() {
6808            continue;
6809        }
6810
6811        results.push(protocol::KeyVerificationResult {
6812            key: *key,
6813            present: cached.present.unwrap_or(false),
6814            paid,
6815        });
6816    }
6817
6818    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6819
6820    Ok(())
6821}
6822
6823async fn dispatch_verification_request(
6824    source: PeerId,
6825    request: protocol::VerificationRequest,
6826    ctx: &ReplicationMessageHandlerContext,
6827    request_id: u64,
6828    received_at: Instant,
6829    rr_message_id: Option<&str>,
6830) -> Result<()> {
6831    let guard = match admit_bounded_responder(
6832        &ctx.verification_responder_admission_semaphore,
6833        &ctx.verification_responder_inflight,
6834        &source,
6835        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6836        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6837    )
6838    .await
6839    {
6840        Ok(guard) => guard,
6841        Err(failure) => {
6842            audit_metrics::record_responder_admission_drop(
6843                ReplicationResponderClass::Verification,
6844                failure.reason.into(),
6845            );
6846            warn!(
6847                responder_class = "verification",
6848                source = %source,
6849                "Verification response dropped at admission: {failure}"
6850            );
6851            return Ok(());
6852        }
6853    };
6854
6855    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6856    let storage = Arc::clone(&ctx.storage);
6857    let paid_list = Arc::clone(&ctx.paid_list);
6858    let p2p_node = Arc::clone(&ctx.p2p_node);
6859    let request_timeout = ctx.config.verification_request_timeout;
6860    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6861    ctx.detached_task_tracker.spawn(async move {
6862        let _guard = guard;
6863        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6864            debug!(
6865                responder_class = "verification",
6866                source = %source,
6867                "Verification responder worker pool closed before dequeue"
6868            );
6869            return;
6870        };
6871        if request_is_stale(received_at, request_timeout) {
6872            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6873            debug!(
6874                responder_class = "verification",
6875                source = %source,
6876                request_age_ms = received_at.elapsed().as_millis(),
6877                "Stale verification request shed at dequeue"
6878            );
6879            return;
6880        }
6881        if let Err(e) = handle_verification_request(
6882            &source,
6883            &request,
6884            &storage,
6885            &paid_list,
6886            &p2p_node,
6887            request_id,
6888            rr_message_id.as_deref(),
6889        )
6890        .await
6891        {
6892            debug!(source = %source, "Verification request handling failed: {e}");
6893        }
6894    });
6895
6896    Ok(())
6897}
6898
6899const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6900    key_count > MAX_INCOMING_VERIFICATION_KEYS
6901}
6902
6903async fn send_verification_results(
6904    source: &PeerId,
6905    p2p_node: &Arc<P2PNode>,
6906    request_id: u64,
6907    results: Vec<protocol::KeyVerificationResult>,
6908    rr_message_id: Option<&str>,
6909) {
6910    send_replication_response(
6911        source,
6912        p2p_node,
6913        request_id,
6914        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6915        rr_message_id,
6916    )
6917    .await;
6918}
6919
6920async fn dispatch_fetch_request(
6921    source: PeerId,
6922    request: protocol::FetchRequest,
6923    ctx: &ReplicationMessageHandlerContext,
6924    request_id: u64,
6925    received_at: Instant,
6926    rr_message_id: Option<&str>,
6927) -> Result<()> {
6928    let guard = match admit_bounded_responder(
6929        &ctx.fetch_responder_admission_semaphore,
6930        &ctx.fetch_responder_inflight,
6931        &source,
6932        FETCH_RESPONDER_MAX_OUTSTANDING,
6933        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6934    )
6935    .await
6936    {
6937        Ok(guard) => guard,
6938        Err(failure) => {
6939            audit_metrics::record_responder_admission_drop(
6940                ReplicationResponderClass::Fetch,
6941                failure.reason.into(),
6942            );
6943            warn!(
6944                responder_class = "fetch",
6945                source = %source,
6946                "Fetch response dropped at admission: {failure}"
6947            );
6948            return Ok(());
6949        }
6950    };
6951
6952    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6953    let storage = Arc::clone(&ctx.storage);
6954    let p2p_node = Arc::clone(&ctx.p2p_node);
6955    let request_timeout = ctx.config.fetch_request_timeout;
6956    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6957    ctx.detached_task_tracker.spawn(async move {
6958        let _guard = guard;
6959        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6960            debug!(
6961                responder_class = "fetch",
6962                source = %source,
6963                "Fetch responder worker pool closed before dequeue"
6964            );
6965            return;
6966        };
6967        if request_is_stale(received_at, request_timeout) {
6968            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6969            debug!(
6970                responder_class = "fetch",
6971                source = %source,
6972                request_age_ms = received_at.elapsed().as_millis(),
6973                "Stale fetch request shed at dequeue"
6974            );
6975            return;
6976        }
6977        if let Err(e) = handle_fetch_request(
6978            &source,
6979            &request,
6980            &storage,
6981            &p2p_node,
6982            request_id,
6983            rr_message_id.as_deref(),
6984        )
6985        .await
6986        {
6987            debug!(source = %source, "Fetch request handling failed: {e}");
6988        }
6989    });
6990
6991    Ok(())
6992}
6993
6994fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6995    received_at.elapsed() >= timeout
6996}
6997
6998/// How a fetch responder's answer is charged against its reputation.
6999#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7000enum FetchFault {
7001    /// The peer does not hold a chunk it was expected to hold.
7002    ///
7003    /// This is the lane the release withholds, because a node part-way through moving
7004    /// off the legacy store answers exactly this way about chunks it has legitimately
7005    /// given up.
7006    UnheldChunk,
7007    /// The peer's own storage failed, or served bytes that no longer hash to their
7008    /// address.
7009    ///
7010    /// Never withheld. `FetchResponse::Error` has one producer, and it is the responder's
7011    /// storage read returning an error: an I/O fault, an exhausted descriptor table, or a
7012    /// failed integrity check. A peer that merely does not hold the chunk answers
7013    /// `NotFound` instead, so nothing about the migration produces this.
7014    ResponderFault,
7015}
7016
7017/// Classify a fetch response that did not carry the chunk.
7018///
7019/// `Success` yields `None`. Every other answer is a fault of one kind or the other, and
7020/// which kind decides whether this release charges for it.
7021fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
7022    match response {
7023        protocol::FetchResponse::Success { .. } => None,
7024        protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
7025        protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
7026    }
7027}
7028
7029/// Charge a fetch fault to the responder.
7030///
7031/// The only place the two kinds are treated differently. An unheld chunk goes through the
7032/// release switch, which is currently withholding it; a responder fault is charged
7033/// directly and is not affected by the switch at all.
7034async fn charge_fetch_fault(
7035    p2p_node: &Arc<P2PNode>,
7036    source: &PeerId,
7037    fault: FetchFault,
7038    lane: &'static str,
7039) {
7040    match fault {
7041        FetchFault::UnheldChunk => {
7042            config::penalise_unheld_close_group_chunk(
7043                p2p_node,
7044                source,
7045                lane,
7046                REPLICATION_TRUST_WEIGHT,
7047            )
7048            .await;
7049        }
7050        FetchFault::ResponderFault => {
7051            p2p_node
7052                .report_trust_event(
7053                    source,
7054                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7055                )
7056                .await;
7057        }
7058    }
7059}
7060
7061/// Turn the responder's storage read into the answer it sends back.
7062///
7063/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7064/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7065/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7066/// Nothing about a node giving chunks up produces the second.
7067fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7068    match read {
7069        Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7070        Ok(None) => protocol::FetchResponse::NotFound { key },
7071        Err(e) => protocol::FetchResponse::Error {
7072            key,
7073            reason: format!("{e}"),
7074        },
7075    }
7076}
7077
7078async fn handle_fetch_request(
7079    source: &PeerId,
7080    request: &protocol::FetchRequest,
7081    storage: &Arc<ChunkStore>,
7082    p2p_node: &Arc<P2PNode>,
7083    request_id: u64,
7084    rr_message_id: Option<&str>,
7085) -> Result<()> {
7086    let response = fetch_response_for(request.key, storage.get(&request.key).await);
7087
7088    send_replication_response(
7089        source,
7090        p2p_node,
7091        request_id,
7092        ReplicationMessageBody::FetchResponse(response),
7093        rr_message_id,
7094    )
7095    .await;
7096
7097    Ok(())
7098}
7099
7100/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7101/// the prune-confirmation audit, which reuses the same wire message): reply with
7102/// per-key possession digests.
7103struct AuditResponderCompletion {
7104    response_kind: &'static str,
7105    sent: bool,
7106    processing: Duration,
7107    response_send: Duration,
7108}
7109
7110async fn handle_audit_challenge_msg(
7111    source: &PeerId,
7112    challenge: &protocol::AuditChallenge,
7113    storage: &Arc<ChunkStore>,
7114    p2p_node: &Arc<P2PNode>,
7115    is_bootstrapping: bool,
7116    reply: ReplyRoute<'_>,
7117) -> Result<AuditResponderCompletion> {
7118    #[allow(clippy::cast_possible_truncation)]
7119    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7120    info!(
7121        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7122        challenge.keys.len(),
7123        is_bootstrapping,
7124        reply.rr_message_id.is_some(),
7125    );
7126
7127    let processing_started = Instant::now();
7128    let response = audit::handle_audit_challenge(
7129        challenge,
7130        storage,
7131        p2p_node.peer_id(),
7132        is_bootstrapping,
7133        stored_chunks,
7134    )
7135    .await;
7136    let processing = processing_started.elapsed();
7137    let response_kind = audit_response_kind(&response);
7138
7139    let response_send_started = Instant::now();
7140    let sent = send_replication_response_checked(
7141        source,
7142        p2p_node,
7143        reply.request_id,
7144        ReplicationMessageBody::AuditResponse(response),
7145        reply.rr_message_id,
7146        Some(reply.protocol),
7147    )
7148    .await;
7149    let response_send = response_send_started.elapsed();
7150
7151    Ok(AuditResponderCompletion {
7152        response_kind,
7153        sent,
7154        processing,
7155        response_send,
7156    })
7157}
7158
7159#[allow(clippy::too_many_arguments)]
7160fn log_audit_responder_completion(
7161    metrics: &AuditResponderMetrics,
7162    source: PeerId,
7163    class: AuditResponderClass,
7164    kind: &'static str,
7165    challenge_id: u64,
7166    work_items: usize,
7167    response_kind: &'static str,
7168    sent: bool,
7169    received_at: Instant,
7170    worker_started: Instant,
7171    processing: Duration,
7172    response_send: Duration,
7173) {
7174    let dispatch = worker_started.saturating_duration_since(received_at);
7175    let total = received_at.elapsed();
7176    metrics.record_completed(source, processing, total, sent);
7177    if sent {
7178        info!(
7179            target: "ant_node::replication::audit_responder",
7180            event = "completed",
7181            kind,
7182            responder_class = class.as_str(),
7183            source = %source,
7184            challenge_id,
7185            work_items,
7186            response = response_kind,
7187            sent,
7188            dispatch_ms = dispatch.as_millis(),
7189            processing_ms = processing.as_millis(),
7190            response_send_ms = response_send.as_millis(),
7191            total_ms = total.as_millis(),
7192            "Audit responder request completed"
7193        );
7194    } else {
7195        warn!(
7196            target: "ant_node::replication::audit_responder",
7197            event = "completed",
7198            kind,
7199            responder_class = class.as_str(),
7200            source = %source,
7201            challenge_id,
7202            work_items,
7203            response = response_kind,
7204            sent,
7205            dispatch_ms = dispatch.as_millis(),
7206            processing_ms = processing.as_millis(),
7207            response_send_ms = response_send.as_millis(),
7208            total_ms = total.as_millis(),
7209            "Audit responder request completed without sending a reply"
7210        );
7211    }
7212}
7213
7214/// Where a reply goes and how it is addressed.
7215///
7216/// Grouped because the audit responder needs all three together and one of them
7217/// is not derivable from the body: during the rollout window a possession reply
7218/// may have to go out on the core id rather than its family's own (see
7219/// [`is_legacy_possession_challenge`]).
7220struct ReplyRoute<'a> {
7221    /// Correlates the reply with the challenge, at the replication layer.
7222    request_id: u64,
7223    /// Present when the challenge arrived over request-response, in which case
7224    /// the reply rides the same exchange back.
7225    rr_message_id: Option<&'a str>,
7226    /// The protocol id to answer on.
7227    protocol: &'static str,
7228}
7229
7230fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7231    match response {
7232        protocol::AuditResponse::Digests { .. } => "digests",
7233        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7234        protocol::AuditResponse::Rejected { .. } => "rejected",
7235    }
7236}
7237
7238fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7239    match response {
7240        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7241        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7242        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7243    }
7244}
7245
7246fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7247    match response {
7248        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7249        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7250        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7251    }
7252}
7253
7254fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7255    match response {
7256        protocol::SubtreeSliceResponse::Items { .. } => "items",
7257        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7258        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7259    }
7260}
7261
7262fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7263    match response {
7264        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7265        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7266    }
7267}
7268
7269// ---------------------------------------------------------------------------
7270// Message sending helper
7271// ---------------------------------------------------------------------------
7272
7273/// Send a replication response message as a best-effort reply.
7274///
7275/// Encode and send failures are logged by the checked helper. Most response
7276/// paths do not need to branch on send success, so this wrapper keeps those
7277/// call sites explicit about their best-effort behavior.
7278async fn send_replication_response(
7279    peer: &PeerId,
7280    p2p_node: &Arc<P2PNode>,
7281    request_id: u64,
7282    body: ReplicationMessageBody,
7283    rr_message_id: Option<&str>,
7284) {
7285    let _ =
7286        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7287            .await;
7288}
7289
7290/// Send a replication response message and report whether it was accepted.
7291///
7292/// Returns `true` after the message is encoded and accepted by the P2P send
7293/// path. Returns `false` after logging an encode or send failure. Repair-proof
7294/// recording uses this to avoid trusting hints that were not actually sent.
7295///
7296/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7297/// request-response path so saorsa-core can route it back to the caller's
7298/// `send_request` future. Otherwise it is sent as a plain message.
7299///
7300/// `protocol` overrides the id the body would route on by family. Exactly one
7301/// caller needs it: a possession challenge from a peer that predates the family
7302/// split has to be answered where it was asked (see
7303/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7304/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7305async fn send_replication_response_checked(
7306    peer: &PeerId,
7307    p2p_node: &Arc<P2PNode>,
7308    request_id: u64,
7309    body: ReplicationMessageBody,
7310    rr_message_id: Option<&str>,
7311    protocol: Option<&'static str>,
7312) -> bool {
7313    let msg = ReplicationMessage { request_id, body };
7314    let encoded = match msg.encode() {
7315        Ok(data) => data,
7316        Err(e) => {
7317            warn!("Failed to encode replication response: {e}");
7318            return false;
7319        }
7320    };
7321    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7322    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7323    // included for completeness. Other response variants (verification/audit/
7324    // commitment) are intentionally excluded — the round-2 audit reply is now a
7325    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7326    if matches!(
7327        msg.body,
7328        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7329    ) {
7330        protocol::record_served(peer, encoded.len());
7331    }
7332    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7333    let result = if let Some(msg_id) = rr_message_id {
7334        p2p_node
7335            .send_response(peer, protocol, msg_id, encoded)
7336            .await
7337    } else {
7338        p2p_node.send_message(peer, protocol, encoded, &[]).await
7339    };
7340    if let Err(e) = result {
7341        debug!("Failed to send replication response to {peer}: {e}");
7342        return false;
7343    }
7344    true
7345}
7346
7347async fn record_sent_replica_hints(
7348    peer: &PeerId,
7349    hints: &[neighbor_sync::SentReplicaHint],
7350    repair_proofs: &Arc<RwLock<RepairProofs>>,
7351    sync_cycle_epoch: &Arc<RwLock<u64>>,
7352) {
7353    if hints.is_empty() {
7354        return;
7355    }
7356
7357    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7358    let mut proofs = repair_proofs.write().await;
7359    for hint in hints {
7360        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7361            debug!(
7362                "Recorded repair hint proof for peer {peer} and key {}",
7363                hex::encode(hint.key)
7364            );
7365        }
7366    }
7367}
7368
7369// ---------------------------------------------------------------------------
7370// Neighbor sync round
7371// ---------------------------------------------------------------------------
7372
7373/// Run one neighbor sync round.
7374#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7375async fn run_neighbor_sync_round(
7376    p2p_node: &Arc<P2PNode>,
7377    storage: &Arc<ChunkStore>,
7378    paid_list: &Arc<PaidList>,
7379    queues: &Arc<RwLock<ReplicationQueues>>,
7380    config: &ReplicationConfig,
7381    sync_state: &Arc<RwLock<NeighborSyncState>>,
7382    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7383    sync_cycle_epoch: &Arc<RwLock<u64>>,
7384    repair_proofs: &Arc<RwLock<RepairProofs>>,
7385    is_bootstrapping: &Arc<RwLock<bool>>,
7386    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7387    commitment_state: &Arc<ResponderCommitmentState>,
7388    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7389    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7390    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7391    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7392    gossip_audit: &GossipAuditTrigger,
7393) {
7394    let self_id = *p2p_node.peer_id();
7395    let bootstrapping = *is_bootstrapping.read().await;
7396
7397    // Check if cycle is complete; start new one if needed.
7398    // We check under a read lock, then release it before the expensive
7399    // prune pass and DHT snapshot so other tasks are not starved.
7400    let cycle_complete = sync_state.read().await.is_cycle_complete();
7401    if cycle_complete {
7402        // A completed local neighbor-sync cycle advances the epoch component
7403        // of repair-proof maturity. The per-key wall-clock minimum age is
7404        // checked when audits are selected.
7405        {
7406            let mut history = sync_history.write().await;
7407            for record in history.values_mut() {
7408                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7409            }
7410        }
7411        {
7412            let mut epoch = sync_cycle_epoch.write().await;
7413            *epoch = epoch.saturating_add(1);
7414        }
7415
7416        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7417        // Prune candidacy is unconditional once the hysteresis elapses;
7418        // bootstrap state only defers the remote prune-confirmation audits
7419        // until bootstrap has drained.
7420        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7421        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7422            self_id: &self_id,
7423            storage,
7424            paid_list,
7425            p2p_node,
7426            config,
7427            sync_state,
7428            repair_proofs,
7429            allow_remote_prune_audits,
7430            commitment_state: Some(commitment_state),
7431            audit_challenge_coordinator,
7432        })
7433        .await;
7434
7435        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7436        let neighbors =
7437            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7438                .await;
7439
7440        // Now re-acquire write lock and re-check before swapping cycle.
7441        let mut state = sync_state.write().await;
7442        if state.is_cycle_complete() {
7443            // Preserve cooldown and bootstrap-claim tracking across cycles.
7444            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7445            // would reset the abuse detection timer every cycle.
7446            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7447            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7448            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7449            let old_prune_cursor = state.prune_cursor;
7450            *state = NeighborSyncState::new_cycle(neighbors);
7451            state.last_sync_times = old_sync_times;
7452            state.bootstrap_claims = old_bootstrap_claims;
7453            state.bootstrap_claim_history = old_bootstrap_claim_history;
7454            state.prune_cursor = old_prune_cursor;
7455        }
7456    }
7457
7458    // Select batch of peers.
7459    let batch = {
7460        let mut state = sync_state.write().await;
7461        neighbor_sync::select_sync_batch(
7462            &mut state,
7463            config.neighbor_sync_peer_count,
7464            config.neighbor_sync_cooldown,
7465        )
7466    };
7467
7468    if batch.is_empty() {
7469        return;
7470    }
7471
7472    debug!("Neighbor sync: syncing with {} peers", batch.len());
7473
7474    // Snapshot our current commitment once per round so all peers in
7475    // this batch see the same thing (gossip is the responder's attestation;
7476    // same value across the batch is fine and reduces RwLock churn). Atomically
7477    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7478    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7479    let gossiped = commitment_state.current_for_gossip();
7480    // The hash actually put on the wire, captured with the payload. A rotation later in
7481    // the round must not let a reply be credited to a root the peer never saw.
7482    let gossiped_hash = gossiped.as_ref().map(|b| b.hash());
7483    let my_commitment = gossiped.map(|b| b.commitment().clone());
7484
7485    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7486        &batch,
7487        storage,
7488        paid_list,
7489        p2p_node,
7490        config.close_group_size,
7491        config.paid_list_close_group_size,
7492    )
7493    .await;
7494
7495    // Sync with each peer in the batch.
7496    for peer in &batch {
7497        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7498        let outcome = neighbor_sync::sync_with_peer_with_hints(
7499            peer,
7500            p2p_node,
7501            config,
7502            bootstrapping,
7503            hints,
7504            my_commitment.clone(),
7505        )
7506        .await;
7507
7508        if let Some(outcome) = outcome {
7509            // The peer answered, so the request that carried our commitment root arrived.
7510            // That is proof of delivery rather than proof of emission, and the storage
7511            // migration will not let a node give anything up until its close group has
7512            // actually seen the reduced root.
7513            if let Some(hash) = gossiped_hash {
7514                commitment_state.note_commitment_delivered(*peer, hash);
7515            }
7516            handle_sync_response(
7517                &self_id,
7518                peer,
7519                &outcome.response,
7520                &outcome.sent_replica_hints,
7521                p2p_node,
7522                config,
7523                bootstrapping,
7524                bootstrap_state,
7525                storage,
7526                paid_list,
7527                queues,
7528                sync_state,
7529                sync_history,
7530                sync_cycle_epoch,
7531                repair_proofs,
7532                last_commitment_by_peer,
7533                ever_capable_peers,
7534                sig_verify_attempts,
7535                gossip_audit,
7536            )
7537            .await;
7538        } else {
7539            // Sync failed -- remove peer and try to fill slot.
7540            let replacement = {
7541                let mut state = sync_state.write().await;
7542                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7543            };
7544
7545            // Attempt sync with the replacement peer (if one was found).
7546            if let Some(replacement_peer) = replacement {
7547                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7548                    std::slice::from_ref(&replacement_peer),
7549                    storage,
7550                    paid_list,
7551                    p2p_node,
7552                    config.close_group_size,
7553                    config.paid_list_close_group_size,
7554                )
7555                .await;
7556                let hints = replacement_hints
7557                    .remove(&replacement_peer)
7558                    .unwrap_or_default();
7559                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7560                    &replacement_peer,
7561                    p2p_node,
7562                    config,
7563                    bootstrapping,
7564                    hints,
7565                    my_commitment.clone(),
7566                )
7567                .await;
7568
7569                if let Some(outcome) = replacement_outcome {
7570                    // Same payload, same round trip, same proof: a reply can only come
7571                    // back if the request carrying the root reached this peer. Omitting it
7572                    // here made the counter under-report on any node whose primary syncs
7573                    // often fall through to a replacement, which is exactly the node most
7574                    // likely to be short of disk, and stalled its migration indefinitely.
7575                    if let Some(hash) = gossiped_hash {
7576                        commitment_state.note_commitment_delivered(replacement_peer, hash);
7577                    }
7578                    handle_sync_response(
7579                        &self_id,
7580                        &replacement_peer,
7581                        &outcome.response,
7582                        &outcome.sent_replica_hints,
7583                        p2p_node,
7584                        config,
7585                        bootstrapping,
7586                        bootstrap_state,
7587                        storage,
7588                        paid_list,
7589                        queues,
7590                        sync_state,
7591                        sync_history,
7592                        sync_cycle_epoch,
7593                        repair_proofs,
7594                        last_commitment_by_peer,
7595                        ever_capable_peers,
7596                        sig_verify_attempts,
7597                        gossip_audit,
7598                    )
7599                    .await;
7600                }
7601            }
7602        }
7603    }
7604}
7605
7606/// Process a successful neighbor sync response: record the sync, check for
7607/// bootstrap claim abuse, and admit inbound hints.
7608#[allow(clippy::too_many_arguments)]
7609async fn handle_sync_response(
7610    self_id: &PeerId,
7611    peer: &PeerId,
7612    resp: &NeighborSyncResponse,
7613    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7614    p2p_node: &Arc<P2PNode>,
7615    config: &ReplicationConfig,
7616    bootstrapping: bool,
7617    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7618    storage: &Arc<ChunkStore>,
7619    paid_list: &Arc<PaidList>,
7620    queues: &Arc<RwLock<ReplicationQueues>>,
7621    sync_state: &Arc<RwLock<NeighborSyncState>>,
7622    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7623    sync_cycle_epoch: &Arc<RwLock<u64>>,
7624    repair_proofs: &Arc<RwLock<RepairProofs>>,
7625    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7626    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7627    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7628    gossip_audit: &GossipAuditTrigger,
7629) {
7630    // Ingest the peer's commitment if they piggybacked one on the response.
7631    // Same verification as the request path (peer-id binding + signature);
7632    // forged commitments are dropped at the edge. A *changed* commitment here
7633    // is a gossip-audit trigger just like on the request path — so a peer that
7634    // only ever answers sync (never initiates) is still audited (ADR-0002).
7635    if let Some(target) = ingest_peer_commitment(
7636        peer,
7637        resp.commitment.as_ref(),
7638        p2p_node,
7639        last_commitment_by_peer,
7640        ever_capable_peers,
7641        sig_verify_attempts,
7642    )
7643    .await
7644    {
7645        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7646    }
7647
7648    // Record successful sync.
7649    {
7650        let mut state = sync_state.write().await;
7651        neighbor_sync::record_successful_sync(&mut state, peer);
7652    }
7653    {
7654        let mut history = sync_history.write().await;
7655        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7656            last_sync: None,
7657            cycles_since_sync: 0,
7658        });
7659        record.last_sync = Some(Instant::now());
7660        record.cycles_since_sync = 0;
7661    }
7662
7663    // Process inbound hints from response (skip if peer is bootstrapping).
7664    if resp.bootstrapping {
7665        // Gap 6: BootstrapClaimAbuse grace period enforcement.
7666        // Separate state mutation from network I/O to avoid holding the
7667        // write lock across report_trust_event.
7668        let should_report = {
7669            let now = Instant::now();
7670            let mut state = sync_state.write().await;
7671            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7672                BootstrapClaimObservation::WithinGrace { .. } => false,
7673                BootstrapClaimObservation::PastGrace { first_seen } => {
7674                    warn!(
7675                        "Peer {peer} has been claiming bootstrap for {:?}, \
7676                         exceeding grace period of {:?} — reporting abuse",
7677                        now.duration_since(first_seen),
7678                        config.bootstrap_claim_grace_period,
7679                    );
7680                    true
7681                }
7682                BootstrapClaimObservation::Repeated { first_seen } => {
7683                    warn!(
7684                        "Peer {peer} repeated bootstrap claim after previously stopping; \
7685                         first claim was {:?} ago — reporting abuse",
7686                        now.duration_since(first_seen),
7687                    );
7688                    true
7689                }
7690            }
7691        };
7692        if should_report {
7693            p2p_node
7694                .report_trust_event(
7695                    peer,
7696                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7697                )
7698                .await;
7699        }
7700    } else {
7701        // Peer is not claiming bootstrap; clear active claim while retaining
7702        // history so the peer cannot start a second grace window later.
7703        {
7704            let mut state = sync_state.write().await;
7705            state.clear_active_bootstrap_claim(peer);
7706        }
7707        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7708        let outcome = admit_and_queue_hints(
7709            self_id,
7710            peer,
7711            &resp.replica_hints,
7712            &resp.paid_hints,
7713            p2p_node,
7714            config,
7715            storage,
7716            paid_list,
7717            queues,
7718        )
7719        .await;
7720
7721        // Track discovered keys for bootstrap drain detection so that hints
7722        // admitted via regular neighbor sync are not missed. Capacity-
7723        // rejected hints keep this source on the "not yet drained" list
7724        // until its next sync replays them; a clean cycle clears it.
7725        if bootstrapping {
7726            let live_discovered = outcome.discovered.clone();
7727            let outcomes = [(*peer, outcome)];
7728            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7729                .await;
7730        }
7731    }
7732}
7733
7734/// Admit hints and queue them for verification, returning newly-discovered keys.
7735///
7736/// Shared by neighbor-sync request handling, response handling, and bootstrap
7737/// sync so that admission + queueing logic lives in one place.
7738#[allow(clippy::too_many_arguments)]
7739/// Outcome of [`admit_and_queue_hints`].
7740///
7741/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7742/// available; that source is kept outstanding until it re-hints. `displaced`
7743/// tracks older borrowed hints reclaimed for another sender; only the key is
7744/// dropped from bootstrap tracking — the former owner's standing is untouched
7745/// (see [`publish_bootstrap_admission_outcomes`]).
7746struct AdmissionOutcome {
7747    discovered: HashSet<XorName>,
7748    capacity_rejected_count: usize,
7749    displaced: Vec<CapacityDisplacement>,
7750}
7751
7752/// Publish one atomic admission unit into bootstrap drain accounting.
7753///
7754/// Only sources that were themselves capacity-rejected are kept outstanding.
7755/// A fairness displacement forfeits the displaced *key* but never stamps its
7756/// former owner: reclaiming a borrowed slot is this node's own fairness
7757/// decision, so charging it to the victim would let a sustained flooder wedge
7758/// our bootstrap drain open through an unrelated honest peer. Clean sources
7759/// are cleared only after every outcome in the unit is known, so peer
7760/// iteration order cannot falsely clear a rejection recorded later in the same
7761/// bootstrap batch.
7762async fn publish_bootstrap_admission_outcomes(
7763    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7764    outcomes: &[(PeerId, AdmissionOutcome)],
7765    live_discovered: &HashSet<XorName>,
7766) {
7767    let mut rejected_sources = HashSet::new();
7768    let mut clean_sources = HashSet::new();
7769    let mut displaced_keys = HashSet::new();
7770
7771    for (source, outcome) in outcomes {
7772        if outcome.capacity_rejected_count > 0 {
7773            rejected_sources.insert(*source);
7774        } else {
7775            clean_sources.insert(*source);
7776        }
7777        // Only the *key* of a fairness displacement is forfeited here, never
7778        // its owner's standing. Reclaiming a borrowed slot is our own fairness
7779        // decision, not a failure by the peer that held it: stamping the victim
7780        // would let a sustained flooder block our bootstrap drain through an
7781        // unrelated honest peer that never overflowed us. The displaced key
7782        // falls to the same post-bootstrap neighbor-sync and audit/repair
7783        // recovery path that TTL expiry already relies on.
7784        for displacement in &outcome.displaced {
7785            displaced_keys.insert(displacement.key);
7786        }
7787    }
7788    clean_sources.retain(|source| !rejected_sources.contains(source));
7789
7790    let now = Instant::now();
7791    let mut state = bootstrap_state.write().await;
7792    for key in displaced_keys {
7793        state.remove_key(&key);
7794    }
7795    state.pending_keys.extend(live_discovered);
7796    for source in clean_sources {
7797        state.capacity_rejected_sources.remove(&source);
7798    }
7799    for source in rejected_sources {
7800        // First-seen: a source that keeps overflowing us must not keep its own
7801        // record fresh, or bootstrap never drains and auditing stays off.
7802        state.note_capacity_rejected(source, now);
7803    }
7804}
7805
7806#[allow(clippy::too_many_arguments)]
7807async fn admit_and_queue_hints(
7808    self_id: &PeerId,
7809    source_peer: &PeerId,
7810    replica_hints: &[XorName],
7811    paid_hints: &[XorName],
7812    p2p_node: &Arc<P2PNode>,
7813    config: &ReplicationConfig,
7814    storage: &Arc<ChunkStore>,
7815    paid_list: &Arc<PaidList>,
7816    queues: &Arc<RwLock<ReplicationQueues>>,
7817) -> AdmissionOutcome {
7818    let pending_keys: HashSet<XorName> = {
7819        let q = queues.read().await;
7820        q.pending_keys().into_iter().collect()
7821    };
7822
7823    let admitted = admission::admit_hints(
7824        self_id,
7825        replica_hints,
7826        paid_hints,
7827        p2p_node,
7828        config,
7829        storage,
7830        paid_list,
7831        &pending_keys,
7832    )
7833    .await;
7834
7835    let mut q = queues.write().await;
7836    queue_admitted_hints(source_peer, admitted, storage, &mut q)
7837}
7838
7839fn queue_admitted_hints(
7840    source_peer: &PeerId,
7841    admitted: admission::AdmissionResult,
7842    storage: &ChunkStore,
7843    q: &mut ReplicationQueues,
7844) -> AdmissionOutcome {
7845    let mut discovered = HashSet::new();
7846    let mut capacity_rejected_count: usize = 0;
7847    let mut displaced = Vec::new();
7848    let now = Instant::now();
7849
7850    for key in admitted.replica_keys {
7851        if !storage.exists(&key).unwrap_or(false) {
7852            let result = q.add_pending_verify(
7853                key,
7854                VerificationEntry {
7855                    state: VerificationState::PendingVerify,
7856                    verified_sources: Vec::new(),
7857                    tried_sources: HashSet::new(),
7858                    created_at: now,
7859                    next_verify_at: now,
7860                    hint_sources: HashSet::from([*source_peer]),
7861                    // Non-empty: this peer claimed possession, so it is a
7862                    // fetch-source candidate. Derives HintPipeline::Replica.
7863                    replica_hint_sources: HashSet::from([*source_peer]),
7864                    unresolved_retries: 0,
7865                    no_holder_reported: false,
7866                },
7867            );
7868            match result {
7869                crate::replication::scheduling::AdmissionResult::Admitted => {
7870                    discovered.insert(key);
7871                }
7872                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7873                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7874                    capacity_rejected_count += 1;
7875                }
7876            }
7877        }
7878    }
7879
7880    for key in admitted.paid_only_keys {
7881        let result = q.add_pending_verify(
7882            key,
7883            VerificationEntry {
7884                state: VerificationState::PendingVerify,
7885                verified_sources: Vec::new(),
7886                tried_sources: HashSet::new(),
7887                created_at: now,
7888                next_verify_at: now,
7889                hint_sources: HashSet::from([*source_peer]),
7890                // Empty: a paid hint makes no possession claim, so this peer is
7891                // not a fetch source. Derives HintPipeline::PaidOnly.
7892                replica_hint_sources: HashSet::new(),
7893                unresolved_retries: 0,
7894                no_holder_reported: false,
7895            },
7896        );
7897        match result {
7898            crate::replication::scheduling::AdmissionResult::Admitted => {
7899                discovered.insert(key);
7900            }
7901            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7902            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7903                capacity_rejected_count += 1;
7904            }
7905        }
7906    }
7907
7908    if capacity_rejected_count > 0 {
7909        debug!(
7910            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7911             rejected at queue capacity; source will need to re-hint after pending_verify drains"
7912        );
7913    }
7914
7915    displaced.extend(q.take_capacity_displacements());
7916
7917    AdmissionOutcome {
7918        discovered,
7919        capacity_rejected_count,
7920        displaced,
7921    }
7922}
7923
7924// ---------------------------------------------------------------------------
7925// Verification cycle
7926// ---------------------------------------------------------------------------
7927
7928/// Run one verification cycle: process pending keys through quorum checks.
7929#[allow(clippy::too_many_lines)]
7930async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7931    let cycle_started = Instant::now();
7932    let VerificationCycleContext {
7933        p2p_node,
7934        paid_list,
7935        storage,
7936        queues,
7937        config,
7938        bootstrap_state,
7939        is_bootstrapping,
7940        bootstrap_complete_notify,
7941        last_commitment_by_peer,
7942        ever_capable_peers,
7943        recent_provers,
7944    } = ctx;
7945
7946    // Self-heal the bootstrap drain before any early-return below: abandoned
7947    // capacity-rejection records must expire, and a drain condition that
7948    // became true without a triggering event must still be observed. Pending
7949    // peer requests legitimately block the drain check itself, but not this.
7950    expire_and_recheck_bootstrap_drain(
7951        bootstrap_state,
7952        queues,
7953        is_bootstrapping,
7954        bootstrap_complete_notify,
7955        config.capacity_rejected_max_age(),
7956    )
7957    .await;
7958
7959    // Bootstrap admits one concurrent neighbor batch as an atomic source
7960    // aggregation unit. Do not select newly queued keys until that batch's
7961    // hints and drain accounting have both been published.
7962    if bootstrap_state.read().await.pending_peer_requests > 0 {
7963        return;
7964    }
7965
7966    // Evict stale entries that have been pending too long (e.g. unreachable
7967    // verification targets during a network partition).
7968    let stale_pending_keys = {
7969        let mut q = queues.write().await;
7970        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7971    };
7972    if !stale_pending_keys.is_empty() {
7973        update_bootstrap_after_verification(
7974            &stale_pending_keys,
7975            bootstrap_state,
7976            queues,
7977            is_bootstrapping,
7978            bootstrap_complete_notify,
7979        )
7980        .await;
7981    }
7982
7983    let pending_keys = {
7984        let mut q = queues.write().await;
7985        // Re-check while holding the queue write lock used by fair selection.
7986        // This closes the race
7987        // where a bootstrap batch starts after the early check: the batch
7988        // cannot publish its hints under the queue write lock until this
7989        // selection either returns or declines to run.
7990        if bootstrap_state.read().await.pending_peer_requests > 0 {
7991            return;
7992        }
7993        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7994    };
7995
7996    if pending_keys.is_empty() {
7997        return;
7998    }
7999    let initial_pending_count = pending_keys.len();
8000
8001    // Capacity verdict for this cycle — the same pre-check the PUT handler and
8002    // the fresh-offer path already run (V2-411), read once and reused below.
8003    //
8004    // It gates only the two steps that exist to enable a fetch: the presence
8005    // probe that discovers holders, and the promotion that queues the download.
8006    // Everything a cycle does that does not need a local write still runs on a
8007    // full node — the local paid-list fast path, `PaidForList` convergence
8008    // through the quorum round, and the terminal checks that retire a key this
8009    // node already holds or is no longer admitted for. Gating earlier than this
8010    // would stop a full node learning which of its keys were paid for, and
8011    // would strand keys that should have retired, which keeps bootstrap drain
8012    // pending and audits disabled until stale eviction.
8013    // Only a *full* disk is a standing condition worth minutes of backoff. A
8014    // failed `statvfs` says nothing about available space and may have cleared
8015    // by the next cycle, so it is treated as writable here and left to the
8016    // pre-check at the dial, which queries again and may well permit the write.
8017    let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8018    // Counted per gate rather than combined. `local_paid_probe` below counts
8019    // probes actually sent, so it reads zero once the first gate fires; keeping
8020    // the two deferral counts apart is what lets an operator see which branch a
8021    // full node's keys are taking without adding a code path to find out.
8022    let mut capacity_deferred_probe = 0usize;
8023    let mut capacity_deferred_promote = 0usize;
8024
8025    let self_id = *p2p_node.peer_id();
8026
8027    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8028    // step 4). Paid-list membership settles *validity* — the key is known-paid,
8029    // so no quorum round is needed. It says nothing about whether we must hold
8030    // the bytes; that is decided below.
8031    let mut local_paid_keys = Vec::new();
8032    let mut keys_needing_network = Vec::new();
8033    let mut terminal_keys: Vec<XorName> = Vec::new();
8034    {
8035        let mut q = queues.write().await;
8036        for key in &pending_keys {
8037            if paid_list.contains(key).unwrap_or(false) {
8038                if q.set_pending_state(key, VerificationState::PaidListVerified) {
8039                    local_paid_keys.push(*key);
8040                }
8041            } else {
8042                keys_needing_network.push(*key);
8043            }
8044        }
8045    }
8046
8047    // Storage responsibility is a live routing question, decided identically
8048    // for every known-paid key regardless of how the advertising peer labelled
8049    // its hint — a replica hint is a possession *claim* by the sender, never
8050    // permission for us to store. Held outside the queue lock: `is_responsible`
8051    // awaits into the DHT manager.
8052    let mut local_paid_presence_probe_keys = Vec::new();
8053    if !local_paid_keys.is_empty() {
8054        let mut terminal_paid = Vec::new();
8055        for key in local_paid_keys {
8056            if storage.exists(&key).unwrap_or(false) {
8057                terminal_paid.push(key);
8058            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8059                // We carry storage responsibility and lack the bytes. The
8060                // presence probe below discovers holders to fetch from; it is
8061                // source discovery, not re-verification.
8062                local_paid_presence_probe_keys.push(key);
8063            } else {
8064                terminal_paid.push(key);
8065            }
8066        }
8067
8068        if !terminal_paid.is_empty() {
8069            let mut q = queues.write().await;
8070            for key in terminal_paid {
8071                q.remove_pending(&key);
8072                terminal_keys.push(key);
8073            }
8074        }
8075
8076        // Capacity gate, first of two. Everything above this point has already
8077        // run: authorization succeeded via the local `PaidForList` hit, and the
8078        // keys that should retire (already held, or no longer storage-admitted)
8079        // have retired. What is left is a probe whose only purpose is finding a
8080        // holder to download from, and this node cannot write what it would
8081        // download.
8082        if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8083            let mut q = queues.write().await;
8084            for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8085                if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8086                    capacity_deferred_probe += 1;
8087                }
8088            }
8089        }
8090    }
8091
8092    let local_paid_probe_count = local_paid_presence_probe_keys.len();
8093    let keys_needing_network_count = keys_needing_network.len();
8094    // Keys this cycle put back because no peer claimed possession. Reported in
8095    // aggregate below; the per-key line is warned once per entry, not per retry.
8096    let mut no_holder_deferrals = 0usize;
8097
8098    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8099    // step 4, authorization succeeds immediately; run a presence-only probe
8100    // to find any holder we can fetch from.
8101    if !local_paid_presence_probe_keys.is_empty() {
8102        let targets = quorum::compute_presence_targets(
8103            &local_paid_presence_probe_keys,
8104            p2p_node,
8105            config,
8106            &self_id,
8107        )
8108        .await;
8109        let evidence = quorum::run_verification_round(
8110            &local_paid_presence_probe_keys,
8111            &targets,
8112            p2p_node,
8113            config,
8114        )
8115        .await;
8116
8117        let mut q = queues.write().await;
8118        for key in local_paid_presence_probe_keys {
8119            if storage.exists(&key).unwrap_or(false) {
8120                q.remove_pending(&key);
8121                terminal_keys.push(key);
8122                continue;
8123            }
8124            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8125                quorum::present_sources_for_key(&key, ev, &targets)
8126            });
8127            if let Some(entry) = q.get_pending(&key) {
8128                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8129            }
8130            if sources.is_empty() {
8131                no_holder_deferrals += 1;
8132                let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8133                let first_report = q.claim_no_holder_report(&key);
8134                report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8135            } else {
8136                // A holder answered, so whatever came before is not a run of
8137                // consecutive failures any more. Clear before promoting: if the
8138                // fetch queue is full the entry stays pending, and it must not
8139                // carry the old backoff.
8140                q.clear_unresolved(&key);
8141                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8142                // Atomic remove+enqueue: if fetch_queue is at capacity, the
8143                // pending entry is preserved and retried next cycle (no
8144                // silent drop of verified replica-repair work).
8145                let _ = q.promote_pending_to_fetch(key, distance, sources);
8146            }
8147        }
8148    }
8149
8150    // Steps 2-5: Network verification (skipped if all keys resolved locally).
8151    if !keys_needing_network.is_empty() {
8152        // Step 2: Compute targets and run network verification round.
8153        let targets =
8154            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8155                .await;
8156
8157        let evidence =
8158            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8159
8160        // Step 3: Evaluate results — collect outcomes without holding the write
8161        // lock across paid-list I/O.
8162        //
8163        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8164        // table and recent_provers cache up front so the synchronous
8165        // evaluate_key_evidence_with_holder_check predicate can consult
8166        // them without awaiting. The predicate downgrades a Present
8167        // claim to Unresolved unless the peer is credited for that key.
8168        // Snapshot per-peer commitment data. We need two views:
8169        //   - `commitment_by_peer_snapshot`: peers that currently have
8170        //     a verified commitment record on file (used to look up
8171        //     their current hash).
8172        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
8173        //     set. Sourced from a separate set rather than the
8174        //     commitment map so eviction (PeerRemoved cleanup, sybil
8175        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8176        //     a previously-v12 peer to "legacy" credit-unconditionally.
8177        //     Legacy / pre-v12 peers that have never sent a commitment
8178        //     remain absent from the set and are credited via the
8179        //     legacy path so mixed-version networks stay live.
8180        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8181            let map = last_commitment_by_peer.read().await;
8182            map.iter()
8183                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8184                // of every peer's ~5 KiB commitment.
8185                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8186                .collect()
8187        };
8188        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8189        // Take a full snapshot of recent_provers under the read lock,
8190        // then release. The cache is bounded (16/key × keys), so the
8191        // clone is cheap.
8192        let provers_snapshot = recent_provers.read().await.clone();
8193        // For the replica-fetch path, we need to know whether THIS
8194        // node already holds the key being verified. The v12 §6
8195        // holder-credit gate is meant to prevent uncredited Present
8196        // claims from contributing to paid-list / reward quorum for
8197        // keys we DO hold (and could audit ourselves). For keys we
8198        // are trying to FETCH (i.e. not in local storage), there is
8199        // no possible local audit credit, and gating the presence
8200        // quorum on credit would deadlock replica-repair in a
8201        // fully v12-capable close group.
8202        let mut locally_held: HashSet<XorName> = HashSet::new();
8203        for key in &keys_needing_network {
8204            if storage.exists(key).unwrap_or(false) {
8205                locally_held.insert(*key);
8206            }
8207        }
8208        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8209            if !locally_held.contains(key) {
8210                // Replica-fetch path: we don't hold this key, so we
8211                // cannot have collected audit credit for it. Trust
8212                // Present claims to drive fetch-source promotion;
8213                // chunk-PUT payment_verifier is the security backstop
8214                // when the bytes actually arrive.
8215                return true;
8216            }
8217            if !capable_peer_snapshot.contains(peer) {
8218                // Pre-v12 / legacy peer that has never gossiped a
8219                // commitment. The v12 §6 holder-eligibility check
8220                // doesn't apply: their Present evidence comes through
8221                // the legacy path and we credit it unconditionally
8222                // so a mixed-version network stays live during
8223                // transition.
8224                return true;
8225            }
8226            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8227                // Peer is commitment_capable (sticky) but currently
8228                // has no live commitment record on file (e.g. their
8229                // last gossip was evicted from the LRU cache, or it
8230                // failed verification). Withhold credit until they
8231                // re-prove storage under a fresh commitment.
8232                return false;
8233            };
8234            provers_snapshot.is_credited_holder(key, peer, hash)
8235        };
8236
8237        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8238        {
8239            let q = queues.read().await;
8240            for key in &keys_needing_network {
8241                let Some(ev) = evidence.get(key) else {
8242                    continue;
8243                };
8244                if q.get_pending(key).is_none() {
8245                    continue;
8246                }
8247                let outcome = quorum::evaluate_key_evidence_with_holder_check(
8248                    key,
8249                    ev,
8250                    &targets,
8251                    config,
8252                    holder_credit,
8253                );
8254                evaluated.push((*key, outcome));
8255            }
8256        } // read lock released
8257
8258        // Step 4: Insert verified keys into PaidForList (no lock held).
8259        let mut paid_insert_keys: Vec<XorName> = Vec::new();
8260        for (key, outcome) in &evaluated {
8261            if matches!(
8262                outcome,
8263                KeyVerificationOutcome::QuorumVerified { .. }
8264                    | KeyVerificationOutcome::PaidListVerified { .. }
8265            ) {
8266                paid_insert_keys.push(*key);
8267            }
8268        }
8269        for key in &paid_insert_keys {
8270            if let Err(e) = paid_list.insert(key).await {
8271                warn!("Failed to add verified key to PaidForList: {e}");
8272            }
8273        }
8274
8275        // Verification established validity; the paid-list insert above records
8276        // it. Downloading the bytes is a separate duty, owed only by the
8277        // storage-admission group, asked on the same terms for every verified
8278        // key — the advertising peer's replica/paid labelling is a claim about
8279        // itself and carries no authority over what we store. This check is a
8280        // cheap pre-filter that keeps never-responsible keys out of the fetch
8281        // queue entirely; the authoritative gate is the per-attempt recheck in
8282        // `execute_single_fetch`, because a key can wait in the nearest-first
8283        // fetch queue long enough for this promotion-time answer to go stale.
8284        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8285        for (key, outcome) in &evaluated {
8286            if matches!(
8287                outcome,
8288                KeyVerificationOutcome::QuorumVerified { .. }
8289                    | KeyVerificationOutcome::PaidListVerified { .. }
8290            ) && !storage.exists(key).unwrap_or(false)
8291                && is_storage_admitted(&self_id, key, p2p_node, config).await
8292            {
8293                fetch_allowed_keys.insert(*key);
8294            }
8295        }
8296
8297        // Step 5: Update queues with the evaluated outcomes.
8298        let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
8299        let mut q = queues.write().await;
8300        for (key, outcome) in evaluated {
8301            let replica_hint_sources = q
8302                .get_pending(&key)
8303                .map(|entry| entry.replica_hint_sources.clone())
8304                .unwrap_or_default();
8305            if let Some(ev) = evidence.get(&key) {
8306                if let Some(source) =
8307                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8308                {
8309                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8310                }
8311            }
8312            match outcome {
8313                KeyVerificationOutcome::QuorumVerified { sources }
8314                | KeyVerificationOutcome::PaidListVerified { sources } => {
8315                    let mut fetch_sources = sources;
8316                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8317                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8318                    if fetch_eligible && write_blocked {
8319                        // Capacity gate, second of two, and deliberately after
8320                        // Step 4: the key is now recorded in `PaidForList` and
8321                        // its verification stands. Only the download is held,
8322                        // because `execute_single_fetch` would refuse it and
8323                        // hand the key straight back here.
8324                        if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8325                            capacity_deferred_promote += 1;
8326                        }
8327                    } else if fetch_eligible && !fetch_sources.is_empty() {
8328                        // A holder answered; see the matching clear on the
8329                        // local-paid path.
8330                        q.clear_unresolved(&key);
8331                        let distance =
8332                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8333                        // Atomic remove+enqueue: on fetch_queue capacity miss
8334                        // the pending entry is preserved so this verified key
8335                        // is retried on the next cycle (no silent drop).
8336                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8337                        // Not terminal — either moved to fetch queue, or
8338                        // retained as pending until queue drains.
8339                    } else if fetch_eligible && fetch_sources.is_empty() {
8340                        no_holder_deferrals += 1;
8341                        let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8342                        let first_report = q.claim_no_holder_report(&key);
8343                        report_unresolved_deferral(
8344                            "Verified storage-admitted key",
8345                            &key,
8346                            outcome,
8347                            first_report,
8348                        );
8349                    } else {
8350                        q.remove_pending(&key);
8351                        terminal_keys.push(key);
8352                    }
8353                }
8354                KeyVerificationOutcome::QuorumFailed => {
8355                    q.remove_pending(&key);
8356                    terminal_keys.push(key);
8357                }
8358                KeyVerificationOutcome::QuorumInconclusive => {
8359                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8360                    // Backed off like any other unresolved round, but it does
8361                    // NOT claim the no-holder report: nothing yet says this key
8362                    // has no holder, so the first round that does say so must
8363                    // still be the one that warns.
8364                    let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8365                }
8366            }
8367        }
8368        drop(q);
8369
8370        for ((peer, fault), bad_hint_count) in bad_singleton_hints {
8371            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8372            warn!(
8373                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8374                 sole-source replica hints ({fault:?}); \
8375                 reporting {reports} bounded trust failure(s)"
8376            );
8377            for _ in 0..reports {
8378                match fault {
8379                    // A claim about a key that does not exist. Punishable whatever the
8380                    // sender's disk is doing.
8381                    SingletonHintFault::RejectedByCloseGroup => {
8382                        p2p_node
8383                            .report_trust_event(
8384                                &peer,
8385                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8386                            )
8387                            .await;
8388                    }
8389                    // "I advertised it and no longer have it." That is the one statement a
8390                    // node short of disk cannot avoid making while it moves its chunks, so
8391                    // it goes through the release switch.
8392                    SingletonHintFault::DeniedPossession => {
8393                        config::penalise_unheld_close_group_chunk(
8394                            p2p_node,
8395                            &peer,
8396                            "replica_hint_denied_possession",
8397                            REPLICATION_TRUST_WEIGHT,
8398                        )
8399                        .await;
8400                    }
8401                }
8402            }
8403        }
8404    }
8405
8406    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8407    // the drain condition.
8408    update_bootstrap_after_verification(
8409        &terminal_keys,
8410        bootstrap_state,
8411        queues,
8412        is_bootstrapping,
8413        bootstrap_complete_notify,
8414    )
8415    .await;
8416
8417    let (pending_after, fetch_after, in_flight_after) = {
8418        let q = queues.read().await;
8419        (
8420            q.pending_count(),
8421            q.fetch_queue_count(),
8422            q.in_flight_count(),
8423        )
8424    };
8425    let terminal_key_count = terminal_keys.len();
8426    let elapsed_ms = cycle_started.elapsed().as_millis();
8427
8428    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8429        info!(
8430            target: "ant_node::replication::verification",
8431            "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}",
8432        );
8433    } else {
8434        debug!(
8435            target: "ant_node::replication::verification",
8436            "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}",
8437        );
8438    }
8439}
8440
8441/// Report a verification round that left a key without a usable holder.
8442///
8443/// Warns once per entry — the first failure is news, and by the hundredth the
8444/// node is re-asking peers it has already exhausted. Later failures stay at
8445/// `debug`, and the per-cycle count is carried in the cycle summary so the
8446/// scale of a backlog is still visible without a line per key per retry.
8447///
8448/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8449/// number: a round may advance the count without producing a no-holder result,
8450/// and such a round must not consume the warning.
8451///
8452/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8453/// a holder clears it, so a later relapse warns again: "once per episode", not
8454/// "once ever".
8455fn report_unresolved_deferral(
8456    what: &str,
8457    key: &XorName,
8458    outcome: Option<DeferralOutcome>,
8459    first_report: bool,
8460) {
8461    let Some(outcome) = outcome else {
8462        // The entry left `pending_verify` under the same lock; nothing deferred.
8463        return;
8464    };
8465    if first_report {
8466        warn!(
8467            "{what} {} has no responding holders yet; deferring retry",
8468            hex::encode(key)
8469        );
8470    } else {
8471        debug!(
8472            "{what} {} still has no responding holders after {} attempts; \
8473             retrying in {}s",
8474            hex::encode(key),
8475            outcome.attempt,
8476            outcome.retry_after.as_secs()
8477        );
8478    }
8479}
8480
8481/// Add peers that claimed possession as fallback fetch sources.
8482///
8483/// Paid-only advertisers make no possession claim and are absent from
8484/// `replica_hint_sources` by construction, so they are never added.
8485fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8486    for source in replica_hint_sources {
8487        if !sources.contains(source) {
8488            sources.push(*source);
8489        }
8490    }
8491}
8492
8493/// Why a sole-source replica hint is punishable.
8494///
8495/// The two cases look alike and are not. A hint the close group rejects outright is a
8496/// claim about a key that does not exist, which is a bad hint however the sender's disk is
8497/// doing. A sender that advertised a key and then answers `Absent` for it is making a
8498/// statement about its own storage, and that is the one thing a node short of disk cannot
8499/// avoid saying while it moves its chunks out of a store that will not give the space back.
8500#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8501enum SingletonHintFault {
8502    /// The close group says the key does not exist.
8503    RejectedByCloseGroup,
8504    /// The sender advertised the key and then denied holding it.
8505    DeniedPossession,
8506}
8507
8508/// Return the sole replica advertiser when either the close group definitively
8509/// rejects the key or the advertiser explicitly denies possessing it, and say which.
8510/// Paid-only advertisements, corroborated replica hints, and inconclusive
8511/// rounds without that direct contradiction are deliberately non-penalizing.
8512fn punishable_singleton_replica_hint_source(
8513    replica_hint_sources: &HashSet<PeerId>,
8514    outcome: &KeyVerificationOutcome,
8515    evidence: &crate::replication::types::KeyVerificationEvidence,
8516) -> Option<(PeerId, SingletonHintFault)> {
8517    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8518    // reserved for peers that actually claimed possession.
8519    if replica_hint_sources.len() != 1 {
8520        return None;
8521    }
8522    let source = *replica_hint_sources.iter().next()?;
8523    if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
8524        return Some((source, SingletonHintFault::RejectedByCloseGroup));
8525    }
8526    if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
8527        return Some((source, SingletonHintFault::DeniedPossession));
8528    }
8529    None
8530}
8531
8532/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8533/// bootstrap pending set and transition out of bootstrapping when drained.
8534async fn update_bootstrap_after_verification(
8535    terminal_keys: &[XorName],
8536    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8537    queues: &Arc<RwLock<ReplicationQueues>>,
8538    is_bootstrapping: &Arc<RwLock<bool>>,
8539    bootstrap_complete_notify: &Arc<Notify>,
8540) {
8541    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8542        return;
8543    }
8544    {
8545        let mut bs = bootstrap_state.write().await;
8546        for key in terminal_keys {
8547            bs.remove_key(key);
8548        }
8549    }
8550    let q = queues.read().await;
8551    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8552        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8553    }
8554}
8555
8556/// Retire bootstrap work owed by a peer that permanently left the routing
8557/// table, then immediately re-check drain so this removal can complete
8558/// bootstrap without waiting for an unrelated pipeline event.
8559async fn update_bootstrap_after_peer_removed(
8560    peer: &PeerId,
8561    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8562    queues: &Arc<RwLock<ReplicationQueues>>,
8563    is_bootstrapping: &Arc<RwLock<bool>>,
8564    bootstrap_complete_notify: &Arc<Notify>,
8565) {
8566    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8567    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8568
8569    if !orphaned_keys.is_empty() {
8570        let mut state = bootstrap_state.write().await;
8571        for key in &orphaned_keys {
8572            state.remove_key(key);
8573        }
8574    }
8575
8576    if orphaned_keys.is_empty() && !cleared_rejection {
8577        return;
8578    }
8579    let q = queues.read().await;
8580    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8581        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8582    }
8583}
8584
8585/// Periodic bootstrap-drain self-healing, run on every verification worker
8586/// tick until bootstrap drains.
8587///
8588/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8589/// recording of a capacity rejection leaves an entry no future event can
8590/// clear — `max_age` expiry is its only exit. And a clean-cycle
8591/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8592/// quiet node the drain condition can become true with nothing left to
8593/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8594/// drain itself, so this is invoked before `run_verification_cycle`'s
8595/// early-returns.
8596async fn expire_and_recheck_bootstrap_drain(
8597    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8598    queues: &Arc<RwLock<ReplicationQueues>>,
8599    is_bootstrapping: &Arc<RwLock<bool>>,
8600    bootstrap_complete_notify: &Arc<Notify>,
8601    max_age: Duration,
8602) {
8603    if bootstrap_state.read().await.is_drained() {
8604        return;
8605    }
8606    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8607    let q = queues.read().await;
8608    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8609        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8610    }
8611}
8612
8613/// Set `is_bootstrapping` to `false` and wake all waiters.
8614async fn complete_bootstrap(
8615    is_bootstrapping: &Arc<RwLock<bool>>,
8616    bootstrap_complete_notify: &Arc<Notify>,
8617) {
8618    *is_bootstrapping.write().await = false;
8619    bootstrap_complete_notify.notify_waiters();
8620    info!("Replication bootstrap complete");
8621}
8622
8623// ---------------------------------------------------------------------------
8624// Fetch types and single-fetch executor
8625// ---------------------------------------------------------------------------
8626
8627/// Result classification for a single fetch attempt.
8628enum FetchResult {
8629    /// Data fetched, integrity-checked, and stored successfully.
8630    Stored,
8631    /// Content-address integrity check failed — do not retry.
8632    IntegrityFailed,
8633    /// Source failed (network error or non-success response) — retryable.
8634    SourceFailed,
8635    /// This node could not write the chunk locally: the capacity pre-check
8636    /// refused before the dial, or `put` failed after the bytes arrived.
8637    ///
8638    /// Distinct from [`Self::SourceFailed`] because nothing about the source
8639    /// is implicated, and because the remedy is the opposite one. A source
8640    /// failure should move on to the next holder; a local write failure must
8641    /// not — every remaining source would send the same chunk into the same
8642    /// full disk. The key returns to verification instead, so a later cycle
8643    /// retries it once local capacity allows. That is a retry path, not a
8644    /// liveness guarantee: `evict_stale` still expires the entry at
8645    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8646    /// which re-acquisition depends on a fresh hint.
8647    LocalWriteFailed,
8648    /// This node already holds the key, so there is nothing to fetch —
8649    /// terminal, exactly like [`Self::Stored`], because the duty is already
8650    /// discharged.
8651    ///
8652    /// Responsibility is rechecked at download time; possession has to be too.
8653    /// The earlier gates already drop held keys out of the fetch pipeline —
8654    /// `queue_admitted_hints` skips them, and the promotion-time
8655    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8656    /// them. (`is_relevant` is not one of them: possession there makes a key
8657    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8658    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8659    /// client PUT, or another source landing first. The nearest-first fetch
8660    /// queue is deep enough for that window to be real.
8661    ///
8662    /// This check must also precede the capacity pre-check below, because
8663    /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
8664    /// it, a full node would decline a key it already holds, which `put` would
8665    /// have accepted as a duplicate.
8666    AlreadyHeld,
8667    /// Live routing state no longer places this node in the storage-admission
8668    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8669    /// the fetch was serving has lapsed, so no alternate source is tried and
8670    /// no trust event is reported: the source did nothing wrong.
8671    NoLongerResponsible,
8672}
8673
8674/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8675/// worker loop to update queue state.
8676struct FetchOutcome {
8677    key: XorName,
8678    result: FetchResult,
8679}
8680
8681/// What the fetch worker must do next for a key whose fetch attempt resolved.
8682#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8683enum FetchFollowUp {
8684    /// The key terminally left the fetch pipeline (its in-flight entry is
8685    /// removed and any verification retry-slot reservation released); the
8686    /// caller must run bootstrap accounting for it.
8687    Terminal,
8688    /// The key returned to `pending_verify` for a later verification round.
8689    RequeuedForVerification,
8690    /// Retry immediately from this next untried verified source.
8691    RetryFrom(PeerId),
8692}
8693
8694/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8695///
8696/// Split out of the fetch-worker loop so the per-variant queue transitions
8697/// are unit-testable without a live network. The caller holds the queues
8698/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8699/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8700/// retry-slot reservation, and the caller's terminal handling shrinks the
8701/// bootstrap pending set — dropping the key without that accounting would
8702/// stall bootstrap drain forever.
8703///
8704/// The nursery `option_if_let_else` rewrite is impossible here: both
8705/// `map_or_else` closures would need `&mut *q` simultaneously.
8706#[allow(clippy::option_if_let_else)]
8707fn apply_fetch_result(
8708    q: &mut ReplicationQueues,
8709    key: &XorName,
8710    result: &FetchResult,
8711    verification_retry_after: Duration,
8712) -> FetchFollowUp {
8713    match result {
8714        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8715            q.complete_fetch(key);
8716            FetchFollowUp::Terminal
8717        }
8718        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8719            if let Some(next_peer) = q.retry_fetch(key) {
8720                FetchFollowUp::RetryFrom(next_peer)
8721            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8722                FetchFollowUp::RequeuedForVerification
8723            } else {
8724                FetchFollowUp::Terminal
8725            }
8726        }
8727        // No `retry_fetch`: the local write is what failed, so every other
8728        // source would be asked to send the same chunk into the same full
8729        // disk. Requeueing for verification is what keeps the key from being
8730        // stranded — it comes back once capacity allows — and the fallthrough
8731        // to `Terminal` when there is no retry metadata is what keeps
8732        // bootstrap drain accounting correct, exactly as for a source failure.
8733        //
8734        // The ordinary requeue delay, deliberately. A standing capacity block
8735        // does not need a longer one here: the key returns to pending, and the
8736        // gate at the head of the next cycle defers it for minutes. A separate
8737        // backoff on this path would duplicate that to save one 15 s round, on
8738        // a race the gate already makes rare.
8739        FetchResult::LocalWriteFailed => {
8740            if q.requeue_fetch_for_verification(key, verification_retry_after) {
8741                FetchFollowUp::RequeuedForVerification
8742            } else {
8743                FetchFollowUp::Terminal
8744            }
8745        }
8746    }
8747}
8748
8749/// Whether this node currently sits inside the storage-admission group for
8750/// `key`, per live local routing state.
8751///
8752/// This is the one question every storage decision in this module asks; see
8753/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8754/// network I/O — but it awaits into the DHT manager, so callers must not
8755/// hold the queues lock across it.
8756async fn is_storage_admitted(
8757    self_id: &PeerId,
8758    key: &XorName,
8759    p2p_node: &Arc<P2PNode>,
8760    config: &ReplicationConfig,
8761) -> bool {
8762    admission::is_responsible(
8763        self_id,
8764        key,
8765        p2p_node,
8766        storage_admission_width(config.close_group_size),
8767    )
8768    .await
8769}
8770
8771#[allow(clippy::too_many_lines)]
8772/// Execute a single fetch request against `source` for `key`.
8773///
8774/// Handles encoding, network I/O, integrity checking, storage, and trust
8775/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8776/// queue state without holding any locks during the network round-trip.
8777///
8778/// This is the authoritative storage-responsibility gate: each attempt —
8779/// including every per-source retry, which re-enters here — rechecks live
8780/// routing state before spending bandwidth, and once more before writing
8781/// bytes that arrived after a round-trip. The verification-time check that
8782/// promoted the key into the fetch queue is only a pre-filter; the queue is
8783/// nearest-first and deep, so a promotion decision can go stale under
8784/// topology churn before the key is ever dequeued.
8785async fn execute_single_fetch(
8786    p2p_node: Arc<P2PNode>,
8787    storage: Arc<ChunkStore>,
8788    config: Arc<ReplicationConfig>,
8789    key: XorName,
8790    source: PeerId,
8791) -> FetchOutcome {
8792    let self_id = *p2p_node.peer_id();
8793    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8794        debug!(
8795            "Skipping fetch for {}: no longer in the storage-admission group",
8796            hex::encode(key)
8797        );
8798        return FetchOutcome {
8799            key,
8800            result: FetchResult::NoLongerResponsible,
8801        };
8802    }
8803
8804    // Possession, then capacity — both before the dial, and in that order.
8805    //
8806    // `ChunkStore::put` tests `exists` before it tests disk space, so a full
8807    // node still accepts a key it already holds. Checking possession first is
8808    // what keeps this pair of gates from declining work `put` would have
8809    // taken.
8810    if storage.exists(&key).unwrap_or(false) {
8811        debug!(
8812            "Skipping fetch for {}: already held locally",
8813            hex::encode(key)
8814        );
8815        return FetchOutcome {
8816            key,
8817            result: FetchResult::AlreadyHeld,
8818        };
8819    }
8820
8821    // Capacity is checked before the dial rather than after the bytes arrive.
8822    // `put` runs this same check on every write of a key it does not already
8823    // hold, so this reaches the same verdict `put` would reach *at this
8824    // instant*. It is not a guarantee about the later write: both answers can
8825    // change across the round trip. Space freed in between would have let a
8826    // post-download `put` succeed, so a refusal here can cost a fleeting
8827    // acquisition and one retry cycle of delay; space lost in between is why
8828    // the check inside `put` still has to stay.
8829    //
8830    // What it buys is that the refusal costs no bandwidth. Without it a
8831    // disk-full node pulls the whole chunk over the network first, and the
8832    // failure is then classified as the source's — no trust event, but the
8833    // worker walks to every remaining holder, and each re-uploads the same
8834    // chunk into the same full disk.
8835    if let Err(e) = storage.check_capacity() {
8836        debug!(
8837            "Skipping fetch for {}: local storage cannot accept a write: {e}",
8838            hex::encode(key)
8839        );
8840        return FetchOutcome {
8841            key,
8842            result: FetchResult::LocalWriteFailed,
8843        };
8844    }
8845
8846    let request = protocol::FetchRequest { key };
8847    let msg = ReplicationMessage {
8848        request_id: rand::thread_rng().gen::<u64>(),
8849        body: ReplicationMessageBody::FetchRequest(request),
8850    };
8851
8852    let encoded = match msg.encode() {
8853        Ok(data) => data,
8854        Err(e) => {
8855            warn!("Failed to encode fetch request: {e}");
8856            return FetchOutcome {
8857                key,
8858                result: FetchResult::SourceFailed,
8859            };
8860        }
8861    };
8862
8863    let result = p2p_node
8864        .send_request(
8865            &source,
8866            REPLICATION_PROTOCOL_ID,
8867            encoded,
8868            config.fetch_request_timeout,
8869        )
8870        .await;
8871
8872    match result {
8873        Ok(response) => {
8874            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8875                p2p_node
8876                    .report_trust_event(
8877                        &source,
8878                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8879                    )
8880                    .await;
8881                return FetchOutcome {
8882                    key,
8883                    result: FetchResult::SourceFailed,
8884                };
8885            };
8886
8887            match resp_msg.body {
8888                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8889                    key: resp_key,
8890                    data,
8891                }) => {
8892                    // Validate the response key matches the requested key.
8893                    // A malicious peer could serve valid data for a different
8894                    // key, passing integrity checks while the requested key
8895                    // is falsely marked as fetched.
8896                    if resp_key != key {
8897                        warn!(
8898                            "Fetch response key mismatch: requested {}, got {}",
8899                            hex::encode(key),
8900                            hex::encode(resp_key)
8901                        );
8902                        p2p_node
8903                            .report_trust_event(
8904                                &source,
8905                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8906                            )
8907                            .await;
8908                        return FetchOutcome {
8909                            key,
8910                            result: FetchResult::IntegrityFailed,
8911                        };
8912                    }
8913
8914                    // Enforce chunk size invariant on fetched data.
8915                    // Checked before the content-address hash to avoid
8916                    // hashing up to 10 MiB of oversized junk data.
8917                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8918                        warn!(
8919                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8920                            hex::encode(resp_key),
8921                            data.len(),
8922                            crate::ant_protocol::MAX_CHUNK_SIZE,
8923                        );
8924                        p2p_node
8925                            .report_trust_event(
8926                                &source,
8927                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8928                            )
8929                            .await;
8930                        return FetchOutcome {
8931                            key,
8932                            result: FetchResult::IntegrityFailed,
8933                        };
8934                    }
8935
8936                    // Content-address integrity check.
8937                    let computed = crate::client::compute_address(&data);
8938                    if computed != resp_key {
8939                        warn!(
8940                            "Fetched record integrity check failed: expected {}, got {}",
8941                            hex::encode(resp_key),
8942                            hex::encode(computed)
8943                        );
8944                        p2p_node
8945                            .report_trust_event(
8946                                &source,
8947                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8948                            )
8949                            .await;
8950                        return FetchOutcome {
8951                            key,
8952                            result: FetchResult::IntegrityFailed,
8953                        };
8954                    }
8955
8956                    // Responsibility can lapse during the network round-trip.
8957                    // The bandwidth is already spent; declining the write is
8958                    // what still avoids the disk write and the later
8959                    // fetch→store→prune churn. Edge flapping is dampened by
8960                    // the margin `storage_admission_width` adds over
8961                    // `close_group_size`.
8962                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8963                        debug!(
8964                            "Fetched {} but responsibility lapsed in transit; not storing",
8965                            hex::encode(key)
8966                        );
8967                        return FetchOutcome {
8968                            key,
8969                            result: FetchResult::NoLongerResponsible,
8970                        };
8971                    }
8972
8973                    if let Err(e) = storage.put(&resp_key, &data).await {
8974                        // The bytes arrived and passed the content-address
8975                        // check, so the source did its job; the failure is
8976                        // entirely local (disk-full, or an LMDB error). Any
8977                        // valid source must serve identical content, so trying
8978                        // the next one cannot cure a local error — it only
8979                        // re-downloads the same chunk into the same store.
8980                        warn!(
8981                            "Failed to store fetched record {}: {e}",
8982                            hex::encode(resp_key)
8983                        );
8984                        return FetchOutcome {
8985                            key,
8986                            result: FetchResult::LocalWriteFailed,
8987                        };
8988                    }
8989
8990                    FetchOutcome {
8991                        key,
8992                        result: FetchResult::Stored,
8993                    }
8994                }
8995                ReplicationMessageBody::FetchResponse(
8996                    ref response @ (protocol::FetchResponse::NotFound { .. }
8997                    | protocol::FetchResponse::Error { .. }),
8998                ) => {
8999                    // This peer was selected as a fetch source because it recently
9000                    // answered `Present` during verification, so either answer is
9001                    // evidence of something. Which one decides what it is charged: a peer
9002                    // that does not hold the chunk is the lane this release withholds, a
9003                    // peer whose own read failed is not.
9004                    if let protocol::FetchResponse::Error { reason, .. } = response {
9005                        warn!(
9006                            "Fetch: peer {source} returned error for {}: {reason}",
9007                            hex::encode(key)
9008                        );
9009                    } else {
9010                        warn!(
9011                            "Fetch: verified source {source} returned NotFound for {}",
9012                            hex::encode(key)
9013                        );
9014                    }
9015                    if let Some(fault) = fetch_fault_for(response) {
9016                        let lane = match fault {
9017                            FetchFault::UnheldChunk => "fetch_not_found",
9018                            FetchFault::ResponderFault => "fetch_error",
9019                        };
9020                        charge_fetch_fault(&p2p_node, &source, fault, lane).await;
9021                    }
9022                    FetchOutcome {
9023                        key,
9024                        result: FetchResult::SourceFailed,
9025                    }
9026                }
9027                _ => {
9028                    // Unexpected message type — treat as malformed.
9029                    p2p_node
9030                        .report_trust_event(
9031                            &source,
9032                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9033                        )
9034                        .await;
9035                    FetchOutcome {
9036                        key,
9037                        result: FetchResult::SourceFailed,
9038                    }
9039                }
9040            }
9041        }
9042        Err(e) => {
9043            debug!("Fetch request to {source} failed: {e}");
9044            // No ApplicationFailure here — P2PNode::send_request() already
9045            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9046            FetchOutcome {
9047                key,
9048                result: FetchResult::SourceFailed,
9049            }
9050        }
9051    }
9052}
9053
9054// ---------------------------------------------------------------------------
9055// Audit result handler
9056// ---------------------------------------------------------------------------
9057
9058/// Format the first confirmed-failed key as a 16-hex-char label.
9059///
9060/// Pairs with `challenged_peer` to form a stable cross-host correlation
9061/// handle in the audit-failure log line, e.g.
9062///
9063/// ```text
9064/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9065/// ```
9066///
9067/// Falls back to `"0x"` when the list is empty so the log line never
9068/// contains a misleading default.
9069fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9070    confirmed_failed_keys.first().map_or_else(
9071        || "0x".to_string(),
9072        |k| format!("0x{}", hex::encode(&k[..8])),
9073    )
9074}
9075
9076/// Execute the side effects for a subtree storage-commitment audit failure.
9077///
9078/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9079/// legitimately time out on slow or loaded honest peers, so it never touches the
9080/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9081/// failures still penalise immediately and revoke holder credit.
9082async fn handle_subtree_failed_audit(
9083    challenged_peer: &PeerId,
9084    confirmed_failed_key_count: usize,
9085    reason: &AuditFailureReason,
9086    p2p_node: &Arc<P2PNode>,
9087    sync_state: &Arc<RwLock<NeighborSyncState>>,
9088    recent_provers: &Arc<RwLock<RecentProvers>>,
9089) {
9090    if matches!(reason, AuditFailureReason::Timeout) {
9091        debug!(
9092            "Audit timeout for {challenged_peer} fully graced \
9093             (subtree audit does not evict on timeout)"
9094        );
9095        return;
9096    }
9097
9098    // The caller already logged the rich failure line with reason + per-category
9099    // summary; avoid a redundant second error log here.
9100    let _ = confirmed_failed_key_count;
9101    {
9102        let mut state = sync_state.write().await;
9103        state.clear_active_bootstrap_claim(challenged_peer);
9104    }
9105    {
9106        let mut provers_guard = recent_provers.write().await;
9107        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9108    }
9109    // Deliberately NOT routed through the release switch. This is the commitment-bound
9110    // subtree audit: the peer published a signed claim to hold these keys and could not
9111    // answer for them. That contract is enforced in every release, including the one that
9112    // withholds the penalty for merely not holding a close-group chunk, because the whole
9113    // migration depends on a node's reduced commitment still meaning something.
9114    p2p_node
9115        .report_trust_event(
9116            challenged_peer,
9117            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9118        )
9119        .await;
9120}
9121
9122/// Handle audit result: log findings and emit trust events.
9123async fn handle_subtree_audit_result(
9124    result: &AuditTickResult,
9125    p2p_node: &Arc<P2PNode>,
9126    sync_state: &Arc<RwLock<NeighborSyncState>>,
9127    recent_provers: &Arc<RwLock<RecentProvers>>,
9128    config: &ReplicationConfig,
9129) {
9130    match result {
9131        AuditTickResult::Passed {
9132            challenged_peer,
9133            keys_checked,
9134        } => {
9135            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9136            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9137            // Peer responded normally — clear the active bootstrap claim while
9138            // retaining history so a later claim is treated as repeated abuse.
9139            {
9140                let mut state = sync_state.write().await;
9141                state.clear_active_bootstrap_claim(challenged_peer);
9142            }
9143            p2p_node
9144                .report_trust_event(
9145                    challenged_peer,
9146                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9147                )
9148                .await;
9149        }
9150        AuditTickResult::Failed {
9151            evidence,
9152            no_response_class,
9153        } => {
9154            if let FailureEvidence::AuditFailure {
9155                challenged_peer,
9156                confirmed_failed_keys,
9157                summary,
9158                reason,
9159                ..
9160            } = evidence
9161            {
9162                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9163                // Rich diagnostics (from main's audit-failure logging) + the
9164                // first-failed-key correlation handle.
9165                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9166                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9167                error!(
9168                    "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}",
9169                    audit_failure_class,
9170                    confirmed_failed_keys.len(),
9171                    summary.challenged_keys,
9172                    summary.absent_keys,
9173                    summary.digest_mismatch_keys,
9174                );
9175                // Route the side effects through the subtree-only failure path.
9176                // Responsible-chunk `AuditChallenge` handling intentionally uses
9177                // its own old immediate-penalty handler below.
9178                handle_subtree_failed_audit(
9179                    challenged_peer,
9180                    confirmed_failed_keys.len(),
9181                    reason,
9182                    p2p_node,
9183                    sync_state,
9184                    recent_provers,
9185                )
9186                .await;
9187            }
9188        }
9189        AuditTickResult::BootstrapClaim { peer } => {
9190            // Gap 6: BootstrapClaimAbuse grace period in audit path.
9191            // Separate state mutation from network I/O to avoid holding the
9192            // write lock across report_trust_event.
9193            let should_report = {
9194                let now = Instant::now();
9195                let mut state = sync_state.write().await;
9196                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9197                {
9198                    BootstrapClaimObservation::WithinGrace { .. } => {
9199                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9200                        false
9201                    }
9202                    BootstrapClaimObservation::PastGrace { first_seen } => {
9203                        warn!(
9204                            "Audit: peer {peer} claiming bootstrap past grace period \
9205                             ({:?} > {:?}), reporting abuse",
9206                            now.duration_since(first_seen),
9207                            config.bootstrap_claim_grace_period,
9208                        );
9209                        true
9210                    }
9211                    BootstrapClaimObservation::Repeated { first_seen } => {
9212                        warn!(
9213                            "Audit: peer {peer} repeated bootstrap claim after previously \
9214                             stopping; first claim was {:?} ago, reporting abuse",
9215                            now.duration_since(first_seen),
9216                        );
9217                        true
9218                    }
9219                }
9220            };
9221            if should_report {
9222                p2p_node
9223                    .report_trust_event(
9224                        peer,
9225                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9226                    )
9227                    .await;
9228            }
9229        }
9230        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9231    }
9232}
9233
9234/// Whether a confirmed audit failure with this reason clears the peer's active
9235/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9236/// bootstrapping); every confirmed storage-integrity reason does.
9237///
9238/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9239/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9240/// still reports the normal audit trust penalty.
9241fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9242    !matches!(reason, AuditFailureReason::Timeout)
9243}
9244
9245/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9246/// events and manage bootstrap-claim state.
9247///
9248/// This is intentionally separate from the subtree audit result handler. A
9249/// responsible-chunk `AuditChallenge` `Failed` result reports
9250/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9251/// restoring the pre-ADR-0002 behaviour.
9252#[allow(clippy::too_many_lines)]
9253async fn handle_audit_result(
9254    result: &AuditTickResult,
9255    p2p_node: &Arc<P2PNode>,
9256    sync_state: &Arc<RwLock<NeighborSyncState>>,
9257    config: &ReplicationConfig,
9258) {
9259    match result {
9260        AuditTickResult::Passed {
9261            challenged_peer,
9262            keys_checked,
9263        } => {
9264            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9265            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9266            {
9267                let mut state = sync_state.write().await;
9268                state.clear_active_bootstrap_claim(challenged_peer);
9269            }
9270            p2p_node
9271                .report_trust_event(
9272                    challenged_peer,
9273                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9274                )
9275                .await;
9276        }
9277        AuditTickResult::Failed {
9278            evidence,
9279            no_response_class,
9280        } => {
9281            if let FailureEvidence::AuditFailure {
9282                challenged_peer,
9283                confirmed_failed_keys,
9284                summary,
9285                reason,
9286                ..
9287            } = evidence
9288            {
9289                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9290                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9291                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9292                error!(
9293                    "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
9294                    audit_failure_class,
9295                    confirmed_failed_keys.len(),
9296                    summary.challenged_keys,
9297                    summary.absent_keys,
9298                    summary.digest_mismatch_keys,
9299                );
9300                if audit_failure_clears_bootstrap_claim(reason) {
9301                    let mut state = sync_state.write().await;
9302                    state.clear_active_bootstrap_claim(challenged_peer);
9303                } else {
9304                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9305                }
9306                config::penalise_unheld_close_group_chunk(
9307                    p2p_node,
9308                    challenged_peer,
9309                    crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
9310                    config::AUDIT_FAILURE_TRUST_WEIGHT,
9311                )
9312                .await;
9313            }
9314        }
9315        AuditTickResult::BootstrapClaim { peer } => {
9316            let should_report = {
9317                let now = Instant::now();
9318                let mut state = sync_state.write().await;
9319                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9320                {
9321                    BootstrapClaimObservation::WithinGrace { .. } => {
9322                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9323                        false
9324                    }
9325                    BootstrapClaimObservation::PastGrace { first_seen } => {
9326                        warn!(
9327                            "Audit: peer {peer} claiming bootstrap past grace period \
9328                             ({:?} > {:?}), reporting abuse",
9329                            now.duration_since(first_seen),
9330                            config.bootstrap_claim_grace_period,
9331                        );
9332                        true
9333                    }
9334                    BootstrapClaimObservation::Repeated { first_seen } => {
9335                        warn!(
9336                            "Audit: peer {peer} repeated bootstrap claim after previously \
9337                             stopping; first claim was {:?} ago, reporting abuse",
9338                            now.duration_since(first_seen),
9339                        );
9340                        true
9341                    }
9342                }
9343            };
9344            if should_report {
9345                p2p_node
9346                    .report_trust_event(
9347                        peer,
9348                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9349                    )
9350                    .await;
9351            }
9352        }
9353        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9354    }
9355}
9356
9357/// Whether a confirmed audit failure with this reason should revoke the
9358/// peer's `recent_provers` holder credit immediately (v12 §6).
9359///
9360/// `true` for any reason where the peer actually answered (or admitted
9361/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9362/// bytes for committed key"), `MalformedResponse` — these prove the
9363/// peer no longer holds what it committed to, so it must not keep
9364/// holder credit for the proof TTL. `false` for `Timeout`: a single
9365/// dropped packet must not strip an honest peer; the 40-min TTL is the
9366/// deliberate liveness cushion there.
9367fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9368    !matches!(reason, AuditFailureReason::Timeout)
9369}
9370
9371/// Apply the holder-credit revocation decision for a confirmed audit
9372/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9373/// testable without a live `P2PNode`: the production `Failed` arm of
9374/// `handle_subtree_audit_result` calls exactly this.
9375fn apply_audit_failure_credit_revocation(
9376    provers: &mut RecentProvers,
9377    challenged_peer: &PeerId,
9378    reason: &AuditFailureReason,
9379) {
9380    if audit_failure_revokes_holder_credit(reason) {
9381        provers.forget_peer(challenged_peer);
9382    }
9383}
9384
9385// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9386
9387// ---------------------------------------------------------------------------
9388// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9389// ---------------------------------------------------------------------------
9390
9391/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9392/// message handler passes one value instead of a long argument list; all
9393/// fields are cheap `Arc` clones.
9394#[derive(Clone)]
9395struct GossipAuditTrigger {
9396    p2p_node: Arc<P2PNode>,
9397    config: Arc<ReplicationConfig>,
9398    recent_provers: Arc<RwLock<RecentProvers>>,
9399    sync_state: Arc<RwLock<NeighborSyncState>>,
9400    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9401    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9402    /// only when a real audit is about to be sent — never by a losing lottery
9403    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9404    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9405    detached_task_tracker: TaskTracker,
9406    /// Gossip-private lottery attempt window: stamped on every roll (win or
9407    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9408    /// The first-audit scheduler never reads this map.
9409    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9410}
9411
9412/// What a gossip ingest yields for the audit trigger: the commitment hash to
9413/// pin and the `key_count` needed to size the response deadline from the actual
9414/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9415/// or not) so a stable-keyset node stays auditable — not just on its first
9416/// commitment.
9417#[derive(Debug, Clone, Copy)]
9418struct AuditTarget {
9419    pin_hash: [u8; 32],
9420    key_count: u32,
9421}
9422
9423/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9424/// verifier's cross-check so it can receive a **deterministic first audit**.
9425///
9426/// Sent from the verifier to the replication engine's first-audit drainer. The
9427/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9428/// audits of the same peer revert to the gossip lottery), orders most-recently-
9429/// monetized first, and runs the same `run_subtree_audit` under the same
9430/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9431#[derive(Debug, Clone, Copy)]
9432pub struct MonetizedPinEvent {
9433    /// The peer whose commitment backed the payment.
9434    pub peer: PeerId,
9435    /// The pinned commitment hash.
9436    pub pin: [u8; 32],
9437    /// The committed key count (sizes the audit deadline).
9438    pub key_count: u32,
9439    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9440    /// pin whose quote is older than the answerability window (ADR-0004 A1
9441    /// guardrail A): with grace removed, challenging an aged-out pin would
9442    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9443    pub quote_ts: SystemTime,
9444}
9445
9446/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9447/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9448/// stamps `now`), `false` if it was audited within
9449/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9450/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9451/// without a live node: a burst of gossips from one peer yields at most one
9452/// `true` per cooldown window.
9453fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9454    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9455    let known = match map.get(peer) {
9456        Some(&last) => {
9457            if now.saturating_duration_since(last) < cooldown {
9458                return false;
9459            }
9460            true
9461        }
9462        None => false,
9463    };
9464    // Bound the map under churn like its siblings (drop the oldest stamp) before
9465    // admitting a brand-new peer.
9466    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9467        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9468            map.remove(&victim);
9469        }
9470    }
9471    map.insert(*peer, now);
9472    true
9473}
9474
9475/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9476/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9477/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9478/// already covered; the authoritative check-and-stamp still runs at promotion,
9479/// so this is only an optimization and never the security boundary.
9480fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9481    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9482    map.get(peer)
9483        .is_none_or(|&last| now.saturating_duration_since(last) >= cooldown)
9484}
9485
9486/// The gossip-audit launch decision in ONE place so the ordering is shared
9487/// between production and its test (ADR-0002 "occasional surprise exams").
9488///
9489/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9490/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9491/// sampled first, a gossip flood would re-roll it on every message until one
9492/// won, multiplying audits, so each peer gets at most one lottery roll per
9493/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9494/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9495/// also consults — only after a WIN, i.e. only when a real audit is about to be
9496/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9497/// wire, so it must not defer a paid first audit (repeatable losses could
9498/// otherwise hold a monetized pin past its answerability window). Production
9499/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9500/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9501/// here fails the test.
9502fn audit_launch_decision(
9503    attempts: &mut HashMap<PeerId, Instant>,
9504    launched: &mut HashMap<PeerId, Instant>,
9505    peer: &PeerId,
9506    now: Instant,
9507    lottery_wins: bool,
9508) -> bool {
9509    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9510    // window even on a loss; private to the gossip path).
9511    if !cooldown_allows_audit(attempts, peer, now) {
9512        return false;
9513    }
9514    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9515    // shared.
9516    if !lottery_wins {
9517        return false;
9518    }
9519    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9520    // either path still suppresses this launch), stamped only on launch.
9521    cooldown_allows_audit(launched, peer, now)
9522}
9523
9524/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9525/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9526/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9527/// handling is never blocked on a network round-trip.
9528async fn maybe_trigger_gossip_audit(
9529    trigger: &GossipAuditTrigger,
9530    peer: &PeerId,
9531    target: AuditTarget,
9532) {
9533    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9534    // lives in the pure `audit_launch_decision` so the ordering is shared with
9535    // its test. Sample the lottery here, then let the helper apply the gates.
9536    let now = Instant::now();
9537    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9538    {
9539        // Lock order: attempts before the shared cooldown; this is the only
9540        // place both are held together.
9541        let mut attempts = trigger.lottery_attempts.write().await;
9542        let mut launched = trigger.cooldown.write().await;
9543        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9544            return;
9545        }
9546    }
9547
9548    let detached_task_tracker = trigger.detached_task_tracker.clone();
9549    let trigger = trigger.clone();
9550    let peer = *peer;
9551    detached_task_tracker.spawn(async move {
9552        let credit = storage_commitment_audit::AuditCredit {
9553            recent_provers: &trigger.recent_provers,
9554        };
9555        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9556            &trigger.p2p_node,
9557            &trigger.config,
9558            &peer,
9559            target.pin_hash,
9560            target.key_count,
9561            Some(&credit),
9562            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9563        )
9564        .await;
9565        handle_subtree_audit_result(
9566            &result,
9567            &trigger.p2p_node,
9568            &trigger.sync_state,
9569            &trigger.recent_provers,
9570            &trigger.config,
9571        )
9572        .await;
9573    });
9574}
9575
9576/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9577///
9578/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9579/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9580/// of its last attempt. Holds one write lock across the decision so two
9581/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9582/// caller's expensive verify so a slow/failed verify still rate-limits the next
9583/// message. Bounds the map under a flood of distinct peer ids.
9584async fn sig_verify_rate_limit_ok(
9585    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9586    source: &PeerId,
9587    now: Instant,
9588) -> bool {
9589    let mut attempts = sig_verify_attempts.write().await;
9590    if let Some(&last) = attempts.get(source) {
9591        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9592            return false;
9593        }
9594    }
9595    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9596        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9597            attempts.remove(&victim);
9598        }
9599    }
9600    attempts.insert(*source, now);
9601    true
9602}
9603
9604/// Verify + store an inbound commitment from a gossip peer.
9605///
9606/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9607/// the bootstrap-sync loop. Drops the commitment unless all five gates
9608/// pass:
9609///   1. `source` is in our DHT routing table (sybil/churn cap).
9610///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9611///      binding to the authenticated transport peer).
9612///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9613///      (the embedded pubkey actually belongs to the claimed identity —
9614///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9615///   4. `verify_commitment_signature(commitment)` succeeds against the
9616///      embedded public key. The signed payload binds the pubkey, so an
9617///      adversary cannot swap the key while keeping the body.
9618///   5. The cache has room or this is an update for an existing entry
9619///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9620///
9621/// On all-pass, the commitment is stored as the auditor's per-peer
9622/// "last known commitment" for use as `expected_commitment_hash` in
9623/// future audits.
9624///
9625/// Failures (no commitment / mismatched peer id / bad signature) are
9626/// silent drops — gossip is best-effort and a malformed commitment from
9627/// one peer should not affect anything else.
9628///
9629/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9630/// or not its root changed), so the caller can run a probabilistic,
9631/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9632/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9633/// being auditable, so it cannot pass one audit and then delete data while
9634/// re-gossiping the same root forever. The cooldown + probability bound the
9635/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9636/// gate) or there is nothing to pin.
9637///
9638/// Handle a capable peer gossiping `None` (a commitment downgrade).
9639///
9640/// A capable peer that previously gossiped a commitment but now gossips `None`
9641/// is trying to drop off the audit path. Within the answerability window we keep
9642/// the cached commitment pinned AND return it as an audit target so this gossip
9643/// still schedules a subtree audit against the peer's last known commitment — if
9644/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9645/// the trigger MUST fire here or the downgrade is never re-challenged).
9646///
9647/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9648/// honours for its own retired commitment: once that elapses since we last
9649/// received the peer's commitment, an honest peer has legitimately retired that
9650/// root (its responder side `retire_current`s and lets it age out) and can no
9651/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9652/// failure, so we then forget the cached commitment (keeping the sticky
9653/// `commitment_capable` bit) and stop pinning it.
9654async fn handle_commitment_downgrade(
9655    source: &PeerId,
9656    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9657) -> Option<AuditTarget> {
9658    let now = Instant::now();
9659    let cached = {
9660        let map = last_commitment_by_peer.read().await;
9661        map.get(source).and_then(|rec| {
9662            if !rec.commitment_capable {
9663                return None;
9664            }
9665            let last = rec.last_commitment()?;
9666            let pin = rec.commitment_hash()?;
9667            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9668            Some((pin, last.key_count, fresh))
9669        })
9670    };
9671    match cached {
9672        Some((pin, key_count, true)) => {
9673            warn!(
9674                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9675                 (downgrade attempt); auditing against its last cached commitment"
9676            );
9677            Some(AuditTarget {
9678                pin_hash: pin,
9679                key_count,
9680            })
9681        }
9682        Some((_, _, false)) => {
9683            // Cached commitment has aged past the answerability window — forget
9684            // it so we stop pinning a root the peer is no longer obliged to
9685            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9686            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9687            // from this peer may have refreshed `received_at` in the gap between
9688            // our read and write locks; if so, leave its fresh commitment intact.
9689            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9690                let still_stale =
9691                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9692                if still_stale {
9693                    rec.clear_commitment();
9694                    debug!(
9695                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9696                         commitment aged past the answerability TTL; forgetting it"
9697                    );
9698                }
9699            }
9700            None
9701        }
9702        None => None,
9703    }
9704}
9705
9706async fn ingest_peer_commitment(
9707    source: &PeerId,
9708    commitment: Option<&StorageCommitment>,
9709    p2p_node: &Arc<P2PNode>,
9710    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9711    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9712    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9713) -> Option<AuditTarget> {
9714    let Some(c) = commitment else {
9715        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9716    };
9717    // RT-membership gate: only accept commitments from peers in our
9718    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9719    // populate the cache, which closes the hole where a flood of
9720    // off-RT identities could fill the cap and evict honest
9721    // peers. The neighbor-sync request handler applies the same gate
9722    // before admitting inbound replication hints (see neighbor_sync.rs
9723    // `sender_in_rt`); we mirror that policy here for the commitment
9724    // piggyback.
9725    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9726        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9727        return None;
9728    }
9729    // Peer-id binding: the commitment's claimed sender must match the
9730    // authenticated transport peer (`source`). Defeats relay/replay
9731    // and also pins which embedded public key we are about to verify
9732    // against — the verify itself trusts the embedded key, so the
9733    // peer-id binding is the link to a real identity.
9734    if &c.sender_peer_id != source.as_bytes() {
9735        warn!(
9736            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9737             (dropped, possible relay attempt)"
9738        );
9739        return None;
9740    }
9741    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9742    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9743    // with a throwaway key they own and lie about which identity it
9744    // belongs to (the embedded-key signature would verify trivially).
9745    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9746    if derived_peer_id != c.sender_peer_id {
9747        warn!(
9748            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9749             {source} (dropped, throwaway-key attack)"
9750        );
9751        return None;
9752    }
9753    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9754    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9755    // sybil/RT-membership-bypassing peer that flooded valid-looking
9756    // gossip would otherwise burn CPU on every message. The rate
9757    // limit is checked AFTER cheap structural gates (RT, peer-id
9758    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9759    //
9760    // Tracked in `sig_verify_attempts` (separate from
9761    // last_commitment_by_peer) so EVERY attempt — successful or not —
9762    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9763    // would skip the cap for peers we've never successfully verified,
9764    // letting a flood of invalid-but-structurally-plausible gossips
9765    // burn CPU.
9766    let now = Instant::now();
9767    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9768        debug!(
9769            "ingest_peer_commitment: rate-limited sig verify from {source} \
9770             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9771        );
9772        return None;
9773    }
9774    // Signature verify, using the public key embedded in the commitment
9775    // itself. The pubkey is bound by the signature payload (see
9776    // commitment_signed_payload) so an adversary cannot keep the body
9777    // and swap the key to one they hold the secret for.
9778    if !crate::replication::commitment::verify_commitment_signature(c) {
9779        warn!(
9780            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9781             (dropped, forged commitment)"
9782        );
9783        return None;
9784    }
9785    // The new commitment's hash, used to store and to pin for the audit target.
9786    let new_hash = commitment_hash(c);
9787    let mut map = last_commitment_by_peer.write().await;
9788    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9789    // evict an arbitrary existing entry to make room. Updates for peers
9790    // already in the map are always accepted (they replace, not grow).
9791    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9792        // Drop one arbitrary entry. HashMap iter order is random which
9793        // is fine — over time PeerRemoved cleanup keeps the working set
9794        // anchored on the real RT membership; this cap only fires under
9795        // active flooding attempts.
9796        if let Some(victim) = map.keys().next().copied() {
9797            map.remove(&victim);
9798            warn!(
9799                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9800                 evicted {victim} to admit {source}"
9801            );
9802        }
9803    }
9804    // Preserve sticky commitment_capable across updates — once true,
9805    // always true. New entries start with capable = true (we just
9806    // verified a valid commitment from this peer).
9807    map.entry(*source)
9808        .and_modify(|r| {
9809            // set_commitment refreshes the cached hash (§13) alongside the
9810            // commitment + received_at so they never drift.
9811            r.set_commitment(c.clone(), now);
9812            r.last_sig_verify_at = now;
9813            r.commitment_capable = true; // sticky-redundant but explicit
9814        })
9815        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9816    drop(map);
9817    // Record the sticky "ever v12-capable" bit in a set independent of
9818    // `last_commitment_by_peer` (whose entries can be evicted by
9819    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9820    // shield and the §6 holder-eligibility closure consult to decide
9821    // whether the peer is expected to speak v12.
9822    //
9823    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9824    // identity-rotation attacks: once full, new entries are refused.
9825    // Refusal degrades over-cap peers to the behaviour before this set
9826    // existed (treated as legacy on rejoin), which is not a security
9827    // regression and preserves the historic set stable.
9828    {
9829        let mut set = ever_capable_peers.write().await;
9830        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9831            set.insert(*source);
9832        } else {
9833            warn!(
9834                "ingest_peer_commitment: ever_capable_peers at cap \
9835                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9836            );
9837        }
9838    }
9839    // Return an audit target for EVERY valid stored commitment (changed or
9840    // not), so the caller's cooldown+probability-gated trigger keeps a
9841    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9842    // failure (new_hash == None, unreachable for a real commitment) yields None.
9843    new_hash.map(|pin_hash| AuditTarget {
9844        pin_hash,
9845        key_count: c.key_count,
9846    })
9847}
9848
9849// ---------------------------------------------------------------------------
9850// Storage-bound audit (v12) — responder commitment rotation
9851// ---------------------------------------------------------------------------
9852
9853/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9854/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9855/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9856async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9857    let bytes = match tokio::fs::read(path).await {
9858        Ok(b) => b,
9859        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9860            debug!(
9861                "Commitment retention: no snapshot at {} (fresh start)",
9862                path.display()
9863            );
9864            return;
9865        }
9866        Err(e) => {
9867            warn!(
9868                "Commitment retention: failed to read {}: {e}",
9869                path.display()
9870            );
9871            return;
9872        }
9873    };
9874    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9875        state.restore(&persisted);
9876        info!(
9877            "Commitment retention: reloaded {} slot(s) from {}",
9878            state.retained_slot_count(),
9879            path.display()
9880        );
9881    } else {
9882        warn!(
9883            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9884            path.display()
9885        );
9886    }
9887}
9888
9889/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9890/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9891/// needless disk writes on idle nodes. On success updates `last` to the bytes
9892/// written; on a serialization/write error the existing on-disk snapshot is left
9893/// intact (never truncated).
9894async fn persist_retention_if_changed(
9895    state: &ResponderCommitmentState,
9896    path: &Path,
9897    last: &mut Option<Vec<u8>>,
9898) {
9899    let Some(bytes) = state.snapshot().to_bytes() else {
9900        warn!("Commitment retention: serialization failed; keeping previous snapshot");
9901        return;
9902    };
9903    if last.as_deref() == Some(bytes.as_slice()) {
9904        return;
9905    }
9906    if write_retention_atomic(path, bytes.clone()).await {
9907        *last = Some(bytes);
9908    }
9909}
9910
9911/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9912/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9913/// success. Only the retention-persist loop writes this path, so a fixed temp
9914/// name is safe.
9915async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9916    let path = path.to_path_buf();
9917    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9918        let tmp = path.with_extension("tmp");
9919        std::fs::write(&tmp, &bytes)?;
9920        std::fs::File::open(&tmp)?.sync_all()?;
9921        std::fs::rename(&tmp, &path)?;
9922        // Fsync the directory so the rename (the durable-commit point) is not
9923        // lost on a crash right after it. An empty parent (relative filename)
9924        // means the current directory.
9925        let dir = path
9926            .parent()
9927            .filter(|p| !p.as_os_str().is_empty())
9928            .unwrap_or_else(|| Path::new("."));
9929        std::fs::File::open(dir)?.sync_all()?;
9930        Ok(())
9931    })
9932    .await;
9933    match res {
9934        Ok(Ok(())) => true,
9935        Ok(Err(e)) => {
9936            warn!("Commitment retention: persist failed: {e}");
9937            false
9938        }
9939        Err(e) => {
9940            warn!("Commitment retention: persist task join failed: {e}");
9941            false
9942        }
9943    }
9944}
9945
9946/// Read the current LMDB key set, build + sign a fresh
9947/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9948/// The prior `current` is demoted to `previous`; the prior `previous` is
9949/// dropped (per `ResponderCommitmentState::rotate`).
9950///
9951/// For content-addressed chunks (Autonomi's chunk store), `address ==
9952/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9953/// re-read each chunk's bytes to compute the leaf hash.
9954///
9955/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9956/// rotate. The auditor side handles "no commitment for this peer" by
9957/// falling back to the legacy plain-digest audit path.
9958async fn rebuild_and_rotate_commitment(
9959    storage: &Arc<ChunkStore>,
9960    identity: &Arc<NodeIdentity>,
9961    state: &Arc<ResponderCommitmentState>,
9962    p2p: &Arc<P2PNode>,
9963    config: &Arc<ReplicationConfig>,
9964) -> Result<()> {
9965    // Not `all_keys()`. While the node is bridging off the legacy store these are the
9966    // same thing, but once it has settled on what it can hold this narrows to the
9967    // file-backed set, which is what stops it claiming keys it is about to give up. It is
9968    // also what lets `is_held` eventually go false for those keys, which is the gate on
9969    // removing the legacy environment at all.
9970    let stored_keys = storage
9971        .committable_keys()
9972        .await
9973        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9974
9975    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9976    // everything currently on disk ("hold"). This is the half of the retention
9977    // contract that lets out-of-range chunks age out: a key that has left our
9978    // close group is excluded from the NEXT commitment, so once its last gossip
9979    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9980    // set, `ResponderCommitmentState::is_held` goes false,
9981    // and the pruner (which until then vetoes its deletion) reclaims it. Without
9982    // this filter the pruner's reprieve would keep re-committing stale keys
9983    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9984    // re-committed and re-gossiped every rotation — a permanent pin).
9985    let self_id = *p2p.peer_id();
9986    let mut keys = Vec::with_capacity(stored_keys.len());
9987    for k in stored_keys {
9988        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9989            keys.push(k);
9990        }
9991    }
9992
9993    if keys.is_empty() {
9994        // There used to be a second branch here that dropped every retained root outright
9995        // when the node looked empty. It is gone, and the reason is worth keeping.
9996        //
9997        // "Empty" was decided from key counts, and every version of that test was wrong in
9998        // the same direction. It read the committable set, which narrows to the file-backed
9999        // keys once the migration settles, so a node whose disk filled before it could copy
10000        // anything looked empty with a full legacy store beside it. Adding the raw file index
10001        // still missed a file dropped from the index by a failed read while its legacy copy
10002        // was being put back. Adding the legacy environment still missed a files-only node
10003        // that had published bytes to disk but not yet indexed them, because a file is
10004        // published before it is indexed. Each fix closed one window and left another.
10005        //
10006        // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10007        // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10008        // lane, which is enforced in every release and is not the lane the migration holds
10009        // off — so a node that still holds the bytes is slashed for holding them. Retiring
10010        // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10011        // instead of vanishing now. Both set `has_current = false`; they differ only in
10012        // whether the node goes on being answerable in the meantime. A genuinely empty node
10013        // cannot answer either way, so retiring costs it nothing it had.
10014        //
10015        // So there is one branch, and no emptiness question to get wrong.
10016        //
10017        // A peer may still be pinning a root we gossiped
10018        // moments ago and could demand its bytes in a round-2 challenge, which
10019        // we can still answer (the bytes are present). But we must STOP
10020        // advertising the stale commitment: retire it so `current()` returns
10021        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10022        // The retired slot then ages out by its gossip-answerability TTL while
10023        // remaining answerable for in-flight pins until then. Once it ages out,
10024        // `is_held` flips false and the pruner reclaims the now-uncommitted,
10025        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10026        // pointing at the stale root, which the gossip loop would keep
10027        // re-stamping — pinning its keys forever.)
10028        debug!(
10029            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10030             (stays answerable until its gossip TTL lapses, bytes still on disk)"
10031        );
10032        state.retire_current();
10033        storage.note_commitment_rebuilt();
10034        return Ok(());
10035    }
10036
10037    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10038    // to more than the protocol limit; auditor would reject the
10039    // commitment otherwise).
10040    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10041    if keys.len() > cap {
10042        warn!(
10043            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
10044             truncating — investigate as this likely means a misconfiguration",
10045            keys.len(),
10046            cap
10047        );
10048    }
10049
10050    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10051    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10052    // full chunk re-read per rotation.
10053    //
10054    // Consequence to be precise about: because the leaf is `(key, key)`,
10055    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10056    // commitment therefore binds "which keys I claim to hold"; it does NOT
10057    // by itself prove byte possession. Byte possession is enforced by the
10058    // round-2 slice audit: a Bao verified slice decoded against the chunk
10059    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10060    // nonce, so a responder that holds the key list but dropped the bytes
10061    // cannot answer. This is sound ONLY while keys are content addresses;
10062    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10063    // (`evaluate_subtree_structure`), so a non-content-addressed
10064    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10065    // earn credit for `key`. If this module is ever reused for
10066    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10067    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10068    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
10069
10070    // No-op-rotation guard: compute just the Merkle root from `entries`
10071    // and compare against the currently-advertised commitment's root.
10072    // If they match, the key set is unchanged and a new rotation would
10073    // only swap a randomized ML-DSA signature for a fresh one — same
10074    // content, different commitment_hash. That invalidates every
10075    // outstanding `recent_provers` credit on this node across the
10076    // close group with no security benefit, breaking steady-state
10077    // quorum liveness on large nodes that can't re-audit every key
10078    // every rotation interval. Skip the rotation entirely when the
10079    // tree is unchanged.
10080    // Build the tree ONCE here (moving `entries`): it serves both the no-op
10081    // root check below and, if we proceed, the signed commitment via
10082    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10083    // inside `BuiltCommitment::build`).
10084    let candidate_tree = commitment::MerkleTree::build(entries)
10085        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10086    let candidate_root = candidate_tree.root();
10087    if let Some(current) = state.current() {
10088        if current.commitment().root == candidate_root {
10089            debug!(
10090                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10091                hex::encode(candidate_root)
10092            );
10093            // Even though we skip re-signing (to avoid invalidating holder
10094            // credit), retention must still advance on the wall clock: a
10095            // previously-gossiped commitment that holds a now-out-of-range key
10096            // must be able to age out of the answerability window even when the
10097            // committed key set is frozen here for many rotations. Without this,
10098            // the no-op guard would pin a stale slot — and its key — forever.
10099            state.age_out();
10100            // The advertised commitment already equals the committable set, which is
10101            // exactly what the retirement gate is counting.
10102            storage.note_commitment_rebuilt();
10103            return Ok(());
10104        }
10105    }
10106
10107    let sk_bytes = identity.secret_key_bytes().to_vec();
10108    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10109        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10110    let pk_bytes = identity.public_key().as_bytes().to_vec();
10111    let peer_id_bytes = *p2p.peer_id().as_bytes();
10112
10113    let built = commitment_state::BuiltCommitment::build_from_tree(
10114        candidate_tree,
10115        &peer_id_bytes,
10116        &sk,
10117        &pk_bytes,
10118    )
10119    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10120
10121    let hash = hex::encode(built.hash());
10122    let key_count = built.commitment().key_count;
10123    state.rotate(built);
10124    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
10125    // Counted only on the paths where the advertised commitment now genuinely reflects
10126    // the committable set, never merely on having read it. The retirement gate is what
10127    // consumes this, and it authorises deleting the legacy store.
10128    storage.note_commitment_rebuilt();
10129    Ok(())
10130}
10131
10132#[cfg(test)]
10133#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10134mod tests {
10135
10136    /// The two fetch failures mean different things and must be charged differently.
10137    ///
10138    /// `NotFound` is a peer saying it does not hold the chunk, which is what a node
10139    /// part-way through the migration says about chunks it has legitimately given up, so
10140    /// it is the lane this release withholds. `Error` has a single producer, the
10141    /// responder's own storage read failing, and that is never about the migration.
10142    #[test]
10143    fn a_missing_chunk_and_a_failed_read_are_different_faults() {
10144        let key = [7u8; 32];
10145        assert_eq!(
10146            fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
10147            Some(FetchFault::UnheldChunk)
10148        );
10149        assert_eq!(
10150            fetch_fault_for(&protocol::FetchResponse::Error {
10151                key,
10152                reason: "read failed".to_string(),
10153            }),
10154            Some(FetchFault::ResponderFault)
10155        );
10156        assert_eq!(
10157            fetch_fault_for(&protocol::FetchResponse::Success {
10158                key,
10159                data: vec![1, 2, 3],
10160            }),
10161            None
10162        );
10163    }
10164
10165    /// The responder's answer says which fault it is, so the mapping from a storage read
10166    /// to a response is what the classification above rests on.
10167    ///
10168    /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10169    /// an I/O fault or a failed integrity check, reads as `Err`. Nothing in the migration
10170    /// turns the first into the second.
10171    #[tokio::test]
10172    async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10173        let dir = tempfile::tempdir().expect("temp dir");
10174        let storage = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
10175            root_dir: dir.path().to_path_buf(),
10176            verify_on_read: true,
10177            max_map_size: 0,
10178            disk_reserve: 0,
10179        })
10180        .await
10181        .expect("open store");
10182
10183        let absent = [9u8; 32];
10184        assert!(
10185            matches!(storage.get(&absent).await, Ok(None)),
10186            "a chunk this node does not hold must read as a plain miss, not a fault"
10187        );
10188
10189        // And the answer each read produces. A miss is `NotFound`, which is the withheld
10190        // lane; a failed read is `Error`, which is not.
10191        assert!(matches!(
10192            fetch_response_for(absent, Ok(None)),
10193            protocol::FetchResponse::NotFound { .. }
10194        ));
10195        assert!(matches!(
10196            fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10197            protocol::FetchResponse::Success { .. }
10198        ));
10199        assert!(matches!(
10200            fetch_response_for(
10201                absent,
10202                Err(crate::error::Error::Storage("read failed".into()))
10203            ),
10204            protocol::FetchResponse::Error { .. }
10205        ));
10206    }
10207    use super::*;
10208    use super::{
10209        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10210        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10211        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10212        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10213        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10214        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10215        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10216        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10217    };
10218    use crate::payment::VerificationContext;
10219    use crate::replication::audit::AuditTickResult;
10220    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10221    use crate::replication::recent_provers::RecentProvers;
10222    use crate::replication::types::{AuditFailureReason, FailureEvidence};
10223    use lru::LruCache;
10224    use saorsa_core::identity::PeerId;
10225    use std::collections::HashMap;
10226    use std::num::NonZeroUsize;
10227    use std::sync::atomic::Ordering;
10228    use std::sync::Arc;
10229    use std::time::Duration;
10230    use std::time::Instant;
10231    use std::time::SystemTime;
10232
10233    #[test]
10234    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10235        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10236            assert_eq!(match_replication_protocol(id), Some((id, false)));
10237            assert_eq!(
10238                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10239                Some((id, true))
10240            );
10241        }
10242        assert_eq!(
10243            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10244            None
10245        );
10246        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10247        assert_eq!(match_replication_protocol(RR_PREFIX), None);
10248    }
10249
10250    #[test]
10251    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10252        use crate::replication::protocol::{
10253            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10254            SubtreeSliceChallenge,
10255        };
10256
10257        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10258            challenge_id: 1,
10259            nonce: [0u8; 32],
10260            challenged_peer_id: [0u8; 32],
10261            expected_commitment_hash: [0u8; 32],
10262            openings: vec![],
10263        });
10264        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10265            challenge_id: 1,
10266            nonce: [0u8; 32],
10267            challenged_peer_id: [0u8; 32],
10268            keys: vec![[0u8; 32]],
10269        });
10270        let digest_response =
10271            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10272        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10273            key: [0u8; 32],
10274            data: vec![],
10275            proof_of_payment: vec![],
10276        });
10277
10278        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10279        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10280
10281        for body in [&digest_challenge, &digest_response, &core] {
10282            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10283            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10284        }
10285
10286        for body in [&subtree, &digest_challenge, &digest_response, &core] {
10287            assert!(body_matches_protocol(body, response_protocol_for(body)));
10288        }
10289    }
10290
10291    fn test_peer(b: u8) -> PeerId {
10292        let mut bytes = [0u8; 32];
10293        bytes[0] = b;
10294        PeerId::from_bytes(bytes)
10295    }
10296
10297    /// A structurally valid offer for `data`: real content address, a proof of
10298    /// the minimum accepted size, distinguished by `proof_marker` so a test can
10299    /// tell whose proof came back out of the queue.
10300    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10301        protocol::FreshReplicationOffer {
10302            key: crate::client::compute_address(&data),
10303            data,
10304            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10305        }
10306    }
10307
10308    fn admit_test_offer(
10309        in_flight: &FreshOfferInFlight,
10310        offer: protocol::FreshReplicationOffer,
10311        source: PeerId,
10312    ) -> FreshOfferAdmission {
10313        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10314    }
10315
10316    #[test]
10317    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10318        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10319        let data = vec![0x11u8; 64];
10320
10321        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10322        let FreshOfferAdmission::Opened(entry) = opened else {
10323            panic!("first offer for a key should open the entry")
10324        };
10325
10326        // A second sender contributes its proof instead of being turned away:
10327        // its bytes are provably the same, so only the proof is worth keeping.
10328        assert!(
10329            matches!(
10330                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10331                FreshOfferAdmission::Joined
10332            ),
10333            "a duplicate from a new source should queue its proof"
10334        );
10335        // The same peer twice is not extra evidence, just extra work.
10336        assert!(
10337            matches!(
10338                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10339                FreshOfferAdmission::DuplicateSource
10340            ),
10341            "one source should hold at most one queued proof per key"
10342        );
10343
10344        // An entry that outlived its handler would bar the key forever.
10345        drop(entry);
10346        assert!(
10347            matches!(
10348                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10349                FreshOfferAdmission::Opened(_)
10350            ),
10351            "a released key should be openable again"
10352        );
10353    }
10354
10355    #[test]
10356    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10357        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10358
10359        // A node only receives offers for keys close to its own ID, so accepted
10360        // keys share a long prefix. Any prefix-derived shard index would have
10361        // funnelled these two onto one lock and serialized them.
10362        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10363        assert!(
10364            matches!(
10365                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10366                FreshOfferAdmission::Opened(_)
10367            ),
10368            "distinct keys should never block each other"
10369        );
10370    }
10371
10372    /// The regression that motivated queueing proofs at all.
10373    ///
10374    /// A sender whose proof does not verify must cost the network its own
10375    /// attempt and nothing more. Refusing every later offer outright made the
10376    /// first arrival the only arrival, so one bad proof lost the record — and
10377    /// the delayed possession check then charged that absence to this node.
10378    #[test]
10379    fn a_failing_proof_hands_the_key_to_the_next_sender() {
10380        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10381        let data = vec![0x5Au8; 128];
10382        let forger = test_peer(0xF0);
10383        let genuine = test_peer(0x0F);
10384
10385        let FreshOfferAdmission::Opened(mut entry) =
10386            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10387        else {
10388            panic!("the first offer should open the entry");
10389        };
10390        assert!(
10391            matches!(
10392                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10393                FreshOfferAdmission::Joined
10394            ),
10395            "the genuine sender must not be turned away by the forger"
10396        );
10397
10398        let first = entry
10399            .next_attempt()
10400            .expect("the opener's proof comes first");
10401        assert_eq!(first.source, forger);
10402
10403        // Treat the forger's proof as failed: the next one is still reachable,
10404        // and it is tried against the bytes already held rather than a refetch.
10405        let second = entry
10406            .next_attempt()
10407            .expect("a failed proof must not consume the key");
10408        assert_eq!(second.source, genuine);
10409        assert_eq!(
10410            second.proof_of_payment,
10411            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10412        );
10413        assert_eq!(
10414            entry.data(),
10415            data.as_slice(),
10416            "every proof is tried against the one copy of the bytes"
10417        );
10418
10419        // Draining the queue releases the key rather than stranding it.
10420        assert!(entry.next_attempt().is_none());
10421        assert!(
10422            matches!(
10423                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10424                FreshOfferAdmission::Opened(_)
10425            ),
10426            "an exhausted entry should release its key"
10427        );
10428    }
10429
10430    /// The cap has to be a lifetime budget, not a queue depth.
10431    ///
10432    /// The handler pops a proof before verifying it, so gating admission on the
10433    /// *instantaneous* queue length lets a fresh source refill the slot that pop
10434    /// just freed. Each refill is another on-chain payment verification, run
10435    /// sequentially while the entry holds its admission permit and a worker
10436    /// slot, so a stream of distinct sources could keep one key's handler — and
10437    /// one of only four workers — busy indefinitely.
10438    #[test]
10439    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10440        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10441        let data = vec![0x3Du8; 32];
10442
10443        let FreshOfferAdmission::Opened(mut entry) =
10444            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10445        else {
10446            panic!("the first offer should open the entry")
10447        };
10448
10449        // Drive pop-then-admit with a fresh source every time, exactly as a
10450        // sybil stream would. The budget must be spent by admissions, not
10451        // returned by pops.
10452        let mut admitted = 1;
10453        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10454            let _ = entry.next_attempt();
10455            if matches!(
10456                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10457                FreshOfferAdmission::Joined
10458            ) {
10459                admitted += 1;
10460            }
10461        }
10462
10463        assert!(
10464            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10465            "a key accepted {admitted} proofs over its lifetime, but the budget is \
10466             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10467        );
10468    }
10469
10470    #[test]
10471    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10472        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10473        let data = vec![0x2Cu8; 32];
10474
10475        // The opener occupies the first slot, so the cap is reached after
10476        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10477        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10478        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10479            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10480            assert!(
10481                matches!(
10482                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10483                    FreshOfferAdmission::Joined
10484                ),
10485                "sender {i} is within the legitimate close-group fan-out"
10486            );
10487        }
10488
10489        let surplus = test_peer(0xEE);
10490        assert!(
10491            matches!(
10492                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10493                FreshOfferAdmission::Full
10494            ),
10495            "past the cap a proof is surplus: enough are already queued to place the record"
10496        );
10497    }
10498
10499    #[test]
10500    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10501        assert!(!verification_request_exceeds_limit(
10502            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10503        ));
10504        assert!(verification_request_exceeds_limit(
10505            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10506        ));
10507    }
10508
10509    // The heavy round-1 limiter enforces the per-peer rate cooldown
10510    // and single-use round-1 → round-2 sessions.
10511    #[tokio::test]
10512    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10513        let limiter = SubtreeRound1Limiter::new(
10514            Duration::from_hours(1),
10515            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10516        );
10517        let peer = test_peer(1);
10518
10519        // First round-1 is admitted; drop the guard so concurrency is free again.
10520        let guard = limiter.admit(&peer).await;
10521        assert!(guard.is_some(), "first round-1 admitted");
10522        drop(guard);
10523        // A second round-1 within the cooldown is dropped even though the heavy
10524        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10525        assert!(
10526            limiter.admit(&peer).await.is_none(),
10527            "second round-1 within cooldown is rate-dropped"
10528        );
10529        // A different peer has its own cooldown.
10530        assert!(limiter.admit(&test_peer(2)).await.is_some());
10531
10532        // Session: opened by round 1, consumed exactly once by the matching round 2.
10533        let hash = [7u8; 32];
10534        let nonce = [9u8; 32];
10535        limiter.open_session(peer, 42, hash, nonce).await;
10536        // Wrong nonce / commitment does not match.
10537        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10538        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10539        // A round 2 with no prior round 1 (wrong challenge_id) misses.
10540        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10541        // The matching round 2 consumes it — and only once (single-use).
10542        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10543        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10544    }
10545
10546    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10547    // so a party holding several identities refills its allowance by rotating
10548    // between them and can keep the heavy pool busy indefinitely. The work
10549    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10550    // so a fresh identity is refused exactly like a repeat caller once it is
10551    // spent. That is the difference between bounding concurrency and bounding
10552    // sustained work.
10553    #[tokio::test]
10554    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10555        // Cooldown disabled so only the work budget can refuse anything.
10556        let limiter =
10557            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10558        assert!(
10559            limiter.admit(&test_peer(1)).await.is_some(),
10560            "a node starts with budget in hand so it can serve audits at once"
10561        );
10562
10563        // Serve enough proof work to run the balance into debt. Charging exactly
10564        // the burst would leave it at zero, which the next nanosecond of refill
10565        // lifts back above the line — the debt is the point.
10566        limiter
10567            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10568            .await;
10569
10570        for id in 2..8u8 {
10571            assert!(
10572                limiter.admit(&test_peer(id)).await.is_none(),
10573                "a never-seen peer must still be refused while the budget is spent"
10574            );
10575        }
10576    }
10577
10578    // The budget is a rate, not a quota: it comes back on its own, so an honest
10579    // auditor blocked by a flood is only delayed. Carrying the debt is what
10580    // prices an expensive proof above a cheap one — without it, a proof reading
10581    // a maximal subtree would cost no more of the next caller's wait than a
10582    // one-leaf proof.
10583    #[test]
10584    fn round1_work_budget_carries_debt_and_refills_over_time() {
10585        let now = Instant::now();
10586        let at = |secs: u64| {
10587            now.checked_add(Duration::from_secs(secs))
10588                .unwrap_or_else(Instant::now)
10589        };
10590        let mut budget = Round1WorkBudget {
10591            balance: 0,
10592            last_refill: now,
10593        };
10594        assert!(!budget.has_budget(now), "empty means empty");
10595
10596        // A proof costing four seconds' worth of refill leaves four seconds of
10597        // debt, so the wait scales with what was actually served.
10598        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10599        assert!(
10600            !budget.has_budget(at(3)),
10601            "still in debt three seconds after an over-large proof"
10602        );
10603        assert!(
10604            budget.has_budget(at(5)),
10605            "the debt is worked off at the refill rate"
10606        );
10607
10608        // Idle time does not bank unbounded credit for a later flood.
10609        budget.refill(at(24 * 60 * 60));
10610        assert_eq!(
10611            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10612            "refill is capped at the burst size"
10613        );
10614    }
10615
10616    // The heavy round-1 pool size is the tightest bound the responder applies and
10617    // the one least backed by fleet measurement, so it is read from config rather
10618    // than baked into the binary: a fleet that lands on the wrong number retunes
10619    // instead of waiting for a release. These pin that the configured value is
10620    // what actually gates admission, and that a 0 degrades to slow, not to off —
10621    // a wedged-shut responder would read on every auditor as a graced timeout,
10622    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10623    #[tokio::test]
10624    async fn round1_pool_size_comes_from_config() {
10625        // Cooldown disabled so only concurrency can refuse anything.
10626        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10627        let held = limiter.admit(&test_peer(1)).await;
10628        assert!(held.is_some(), "the single configured slot is admitted");
10629        assert!(
10630            limiter.admit(&test_peer(2)).await.is_none(),
10631            "a second concurrent round 1 is refused at a configured pool of 1, \
10632             proving admission follows config rather than the compiled-in default"
10633        );
10634        drop(held);
10635        assert!(
10636            limiter.admit(&test_peer(2)).await.is_some(),
10637            "the slot is reusable once the first proof completes"
10638        );
10639    }
10640
10641    #[tokio::test]
10642    async fn round1_pool_size_of_zero_is_clamped_to_one() {
10643        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10644        assert!(
10645            limiter.admit(&test_peer(1)).await.is_some(),
10646            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10647        );
10648    }
10649
10650    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10651        let mut k = [0u8; 32];
10652        k[0] = b;
10653        k
10654    }
10655
10656    #[test]
10657    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10658        let source = test_peer(0x91);
10659        let corroborator = test_peer(0x92);
10660        let mut evidence = types::KeyVerificationEvidence {
10661            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10662            paid_list: HashMap::new(),
10663        };
10664        let failed = KeyVerificationOutcome::QuorumFailed;
10665
10666        assert_eq!(
10667            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10668            Some((source, SingletonHintFault::RejectedByCloseGroup)),
10669            "a close-group rejection outranks the denial: the key does not exist, which is \
10670             a bad hint however the sender's own disk is doing"
10671        );
10672        assert_eq!(
10673            punishable_singleton_replica_hint_source(
10674                &HashSet::from([source, corroborator]),
10675                &failed,
10676                &evidence,
10677            ),
10678            None,
10679            "corroborated hints must not use the sole-source penalty lane"
10680        );
10681        assert_eq!(
10682            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10683            None,
10684            "paid-list advertisements do not claim possession, so they leave the \
10685             replica-hint source set empty and cannot be penalized"
10686        );
10687
10688        evidence
10689            .presence
10690            .insert(source, PresenceEvidence::Unresolved);
10691        assert_eq!(
10692            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10693            Some((source, SingletonHintFault::RejectedByCloseGroup)),
10694            "definitive close-group rejection is punishable without direct contradiction"
10695        );
10696        assert_eq!(
10697            punishable_singleton_replica_hint_source(
10698                &HashSet::from([source]),
10699                &KeyVerificationOutcome::QuorumInconclusive,
10700                &evidence,
10701            ),
10702            None,
10703            "timeouts and inconclusive evidence are neutral"
10704        );
10705
10706        evidence.presence.insert(source, PresenceEvidence::Absent);
10707        assert_eq!(
10708            punishable_singleton_replica_hint_source(
10709                &HashSet::from([source]),
10710                &KeyVerificationOutcome::QuorumVerified {
10711                    sources: vec![corroborator],
10712                },
10713                &evidence,
10714            ),
10715            Some((source, SingletonHintFault::DeniedPossession)),
10716            "an explicit denial is punishable regardless of the overall outcome, and is \
10717             classified separately because it is a statement about the sender's own \
10718             storage rather than about the key"
10719        );
10720    }
10721
10722    /// Build a round-2 slice challenge matching an open session. `openings` is
10723    /// empty: these tests exercise admission and session handling only, which
10724    /// run before any block is opened.
10725    fn slice_challenge(
10726        challenge_id: u64,
10727        commitment_hash: [u8; 32],
10728        nonce: [u8; 32],
10729    ) -> protocol::SubtreeSliceChallenge {
10730        protocol::SubtreeSliceChallenge {
10731            challenge_id,
10732            nonce,
10733            challenged_peer_id: [0u8; 32],
10734            expected_commitment_hash: commitment_hash,
10735            openings: Vec::new(),
10736        }
10737    }
10738
10739    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10740    // responder caps MUST NOT burn the single-use round-1 session.
10741    //
10742    // The handler used to consume the session first and admit second, so a
10743    // transient local capacity drop permanently destroyed that audit exchange —
10744    // every retry hit the `no live round-1 session` path and got `Transient`,
10745    // even after load cleared. Turning momentary local load into a deterministic
10746    // round-2 miss costs the responder its whole-slice credit for that round.
10747    #[tokio::test]
10748    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10749        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10750        let inflight = Arc::new(RwLock::new(HashMap::new()));
10751        let round1 =
10752            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10753        let peer = test_peer(0xB1);
10754        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10755        let challenge = slice_challenge(id, hash, nonce);
10756
10757        round1.open_session(peer, id, hash, nonce).await;
10758
10759        // Saturate this peer's share so the next admission must be refused.
10760        let mut hold = Vec::new();
10761        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10762            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10763                .await
10764            {
10765                Ok(guard) => hold.push(guard),
10766                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10767            }
10768        }
10769
10770        let refused =
10771            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10772        assert!(
10773            matches!(refused, SliceAdmission::Capacity(_)),
10774            "a saturated peer share must refuse on capacity, not on session"
10775        );
10776
10777        // Load clears. The session must have survived the refusal.
10778        drop(hold);
10779        let retried =
10780            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10781        assert!(
10782            matches!(retried, SliceAdmission::Admitted(_)),
10783            "the round-1 session must survive a capacity refusal so the retry succeeds"
10784        );
10785
10786        // Still single-use: the successful admission consumed it exactly once.
10787        drop(retried);
10788        let replayed =
10789            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10790        assert!(
10791            matches!(replayed, SliceAdmission::NoSession),
10792            "a consumed session must not be replayable"
10793        );
10794    }
10795
10796    // The permit taken for the session probe is released when the probe misses,
10797    // so an unsessioned flood cannot pin the responder pool shut.
10798    #[tokio::test]
10799    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10800        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10801        let inflight = Arc::new(RwLock::new(HashMap::new()));
10802        let round1 =
10803            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10804        let peer = test_peer(0xB2);
10805        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10806
10807        // Far more unsessioned challenges than the per-peer cap would allow if
10808        // the slot leaked on the miss path.
10809        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10810            let outcome =
10811                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10812            assert!(
10813                matches!(outcome, SliceAdmission::NoSession),
10814                "no session was ever opened, so every attempt must miss"
10815            );
10816        }
10817
10818        assert_eq!(
10819            semaphore.available_permits(),
10820            MAX_CONCURRENT_AUDIT_RESPONSES,
10821            "every global permit must be returned"
10822        );
10823        assert!(
10824            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10825            "no per-peer slot may be left occupied"
10826        );
10827    }
10828
10829    #[test]
10830    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10831        assert!(!audit_failure_revokes_holder_credit(
10832            &AuditFailureReason::Timeout
10833        ));
10834        assert!(audit_failure_revokes_holder_credit(
10835            &AuditFailureReason::DigestMismatch
10836        ));
10837    }
10838
10839    #[tokio::test]
10840    async fn audit_responder_admission_reports_per_peer_cap_full() {
10841        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10842        let inflight = Arc::new(RwLock::new(HashMap::new()));
10843        let peer = test_peer(0xA1);
10844
10845        let mut guards = Vec::new();
10846        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10847            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10848                .await
10849            {
10850                Ok(guard) => guards.push(guard),
10851                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10852            }
10853        }
10854
10855        let Err(err) =
10856            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10857        else {
10858            panic!("admission should fail once per-peer cap is full");
10859        };
10860        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10861        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10862        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10863        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10864
10865        drop(guards);
10866    }
10867
10868    #[tokio::test]
10869    async fn audit_responder_admission_reports_global_pool_full() {
10870        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10871        let inflight = Arc::new(RwLock::new(HashMap::new()));
10872        let peer = test_peer(0xA2);
10873
10874        let mut held_global_permits = Vec::new();
10875        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10876            held_global_permits.push(
10877                Arc::clone(&semaphore)
10878                    .try_acquire_owned()
10879                    .expect("test should be able to exhaust the global pool"),
10880            );
10881        }
10882
10883        let Err(err) =
10884            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10885        else {
10886            panic!("admission should fail once global pool is full");
10887        };
10888        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10889        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10890        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10891        assert_eq!(err.peer_inflight, 0);
10892        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10893
10894        drop(held_global_permits);
10895    }
10896
10897    #[tokio::test]
10898    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10899        let semaphore = Arc::new(Semaphore::new(1));
10900        let inflight = Arc::new(RwLock::new(HashMap::new()));
10901        let peer = test_peer(0xA3);
10902
10903        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10904            .await
10905            .expect("first responder should be admitted");
10906        assert_eq!(semaphore.available_permits(), 0);
10907        assert_eq!(inflight.read().await.get(&peer), Some(&1));
10908
10909        drop(guard);
10910        assert_eq!(semaphore.available_permits(), 1);
10911        assert!(!inflight.read().await.contains_key(&peer));
10912    }
10913
10914    #[tokio::test]
10915    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10916        let semaphore = Arc::new(Semaphore::new(1));
10917        let inflight = Arc::new(RwLock::new(HashMap::new()));
10918        let peer = test_peer(0xA4);
10919        let held_map = inflight.write().await;
10920
10921        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10922        assert!(
10923            tokio::time::timeout(Duration::from_millis(10), waiting)
10924                .await
10925                .is_err(),
10926            "admission should still be waiting for the peer map"
10927        );
10928
10929        drop(held_map);
10930        assert_eq!(semaphore.available_permits(), 1);
10931        assert!(!inflight.read().await.contains_key(&peer));
10932    }
10933
10934    #[test]
10935    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10936        let timeout = Duration::from_secs(1);
10937        let old_received_at = Instant::now()
10938            .checked_sub(timeout)
10939            .unwrap_or_else(Instant::now);
10940
10941        assert!(request_is_stale(old_received_at, timeout));
10942        assert!(!request_is_stale(Instant::now(), timeout));
10943    }
10944
10945    #[tokio::test]
10946    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10947        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10948        let inflight = Arc::new(RwLock::new(HashMap::new()));
10949        let first_peer = test_peer(0xB3);
10950        let second_peer = test_peer(0xB4);
10951
10952        let first_guard = admit_bounded_responder(
10953            &semaphore,
10954            &inflight,
10955            &first_peer,
10956            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10957            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10958        )
10959        .await
10960        .expect("first sync from a peer should be admitted");
10961        let duplicate = admit_bounded_responder(
10962            &semaphore,
10963            &inflight,
10964            &first_peer,
10965            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10966            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10967        )
10968        .await;
10969        let other_peer = admit_bounded_responder(
10970            &semaphore,
10971            &inflight,
10972            &second_peer,
10973            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10974            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10975        )
10976        .await;
10977
10978        assert!(matches!(
10979            duplicate,
10980            Err(ResponderAdmissionFailure {
10981                reason: ResponderRejectReason::PerPeerCapFull,
10982                ..
10983            })
10984        ));
10985        assert!(other_peer.is_ok());
10986        drop(first_guard);
10987        drop(other_peer);
10988    }
10989
10990    /// One flooding peer must not be able to hold every fresh-offer slot.
10991    ///
10992    /// This is the eviction primitive the per-peer share closes: with only a
10993    /// global bound, a single source occupies the pool, every honest offer in
10994    /// that window is refused, and because a refusal reads as absence to the
10995    /// sender's delayed possession check those refusals land as
10996    /// audit-severity penalties on *this* node.
10997    #[tokio::test]
10998    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10999        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
11000        let inflight = Arc::new(RwLock::new(HashMap::new()));
11001        let flooder = test_peer(0xC1);
11002        let honest = test_peer(0xC2);
11003
11004        let mut held = Vec::new();
11005        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11006            held.push(
11007                admit_bounded_responder(
11008                    &semaphore,
11009                    &inflight,
11010                    &flooder,
11011                    FRESH_OFFER_MAX_OUTSTANDING,
11012                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11013                )
11014                .await
11015                .expect("offers within the per-peer share are admitted"),
11016            );
11017        }
11018
11019        let flooder_excess = admit_bounded_responder(
11020            &semaphore,
11021            &inflight,
11022            &flooder,
11023            FRESH_OFFER_MAX_OUTSTANDING,
11024            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11025        )
11026        .await;
11027        assert!(
11028            matches!(
11029                flooder_excess,
11030                Err(ResponderAdmissionFailure {
11031                    reason: ResponderRejectReason::PerPeerCapFull,
11032                    ..
11033                })
11034            ),
11035            "one source must not exceed its fresh-offer share"
11036        );
11037
11038        let honest_offer = admit_bounded_responder(
11039            &semaphore,
11040            &inflight,
11041            &honest,
11042            FRESH_OFFER_MAX_OUTSTANDING,
11043            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11044        )
11045        .await;
11046        assert!(
11047            honest_offer.is_ok(),
11048            "an honest sender must still be admitted while another peer floods"
11049        );
11050
11051        assert!(
11052            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11053                < FRESH_OFFER_MAX_OUTSTANDING,
11054            "the per-peer share must leave room for other sources"
11055        );
11056
11057        drop(held);
11058        drop(honest_offer);
11059    }
11060
11061    /// Paid notifies get the same per-source treatment as every other class.
11062    #[tokio::test]
11063    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11064        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11065        let inflight = Arc::new(RwLock::new(HashMap::new()));
11066        let flooder = test_peer(0xC3);
11067        let honest = test_peer(0xC4);
11068
11069        let mut held = Vec::new();
11070        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11071            held.push(
11072                admit_bounded_responder(
11073                    &semaphore,
11074                    &inflight,
11075                    &flooder,
11076                    PAID_NOTIFY_MAX_OUTSTANDING,
11077                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11078                )
11079                .await
11080                .expect("notifies within the per-peer share are admitted"),
11081            );
11082        }
11083
11084        assert!(
11085            matches!(
11086                admit_bounded_responder(
11087                    &semaphore,
11088                    &inflight,
11089                    &flooder,
11090                    PAID_NOTIFY_MAX_OUTSTANDING,
11091                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11092                )
11093                .await,
11094                Err(ResponderAdmissionFailure {
11095                    reason: ResponderRejectReason::PerPeerCapFull,
11096                    ..
11097                })
11098            ),
11099            "one source must not exceed its paid-notify share"
11100        );
11101        assert!(
11102            admit_bounded_responder(
11103                &semaphore,
11104                &inflight,
11105                &honest,
11106                PAID_NOTIFY_MAX_OUTSTANDING,
11107                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11108            )
11109            .await
11110            .is_ok(),
11111            "an honest sender must still be admitted while another peer floods"
11112        );
11113
11114        drop(held);
11115    }
11116
11117    /// The fresh-offer per-source bound must guarantee headroom for a peer
11118    /// holding nothing, without throttling a single legitimate fan-out.
11119    ///
11120    /// Sized as a quota rather than a reserve, this bound refused offers during
11121    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11122    /// refusal is charged to THIS node at audit severity because the sender
11123    /// never reads it.
11124    #[test]
11125    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11126        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11127
11128        assert_eq!(
11129            FRESH_OFFER_MAX_OUTSTANDING - share,
11130            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11131            "a source holding none must always find a free slot"
11132        );
11133        assert!(
11134            share < FRESH_OFFER_MAX_OUTSTANDING,
11135            "one peer must not be able to take the whole pool"
11136        );
11137        // The failure this pins: a share sized like the request/response
11138        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11139        // one-way bulk traffic.
11140        assert!(
11141            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11142            "fresh offers are one-way bulk, not request/response — their share \
11143             must not be sized like the request classes'"
11144        );
11145    }
11146
11147    /// A malformed offer must be refused before it can occupy an admission
11148    /// slot, so junk cannot hold capacity for the length of a verification.
11149    #[test]
11150    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11151        let key = test_key(0xC5);
11152
11153        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11154
11155        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11156            .expect("an offer with no proof must be refused");
11157        assert!(
11158            rejection.penalise,
11159            "an honest sender always attaches a proof"
11160        );
11161
11162        // A proof is retained per queued sender, so its size has to be bounded
11163        // here rather than at the verifier, which only sees it on a worker.
11164        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11165        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11166            .expect("an undersized proof must be refused");
11167        assert!(
11168            rejection.penalise,
11169            "no honest sender constructs an undersized proof"
11170        );
11171        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11172        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11173            .expect("an oversized proof must be refused");
11174        assert!(
11175            rejection.penalise,
11176            "no honest sender constructs an oversized proof"
11177        );
11178
11179        let rejection = fresh_offer_structural_rejection(
11180            &key,
11181            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11182            &valid_proof,
11183        )
11184        .expect("an oversized offer must be refused");
11185        assert!(
11186            rejection.penalise,
11187            "no honest sender constructs an oversized offer"
11188        );
11189
11190        let data = vec![0u8; 1];
11191        assert!(
11192            fresh_offer_structural_rejection(
11193                &crate::client::compute_address(&data),
11194                &data,
11195                &valid_proof
11196            )
11197            .is_none(),
11198            "a well-formed offer must reach admission"
11199        );
11200    }
11201
11202    /// Knowing a key must not be enough to enter its entry.
11203    ///
11204    /// Opening an entry on an unverified key/bytes association would let a peer
11205    /// that has only *learned* the key — every recipient of its `PaidNotify`,
11206    /// not just the close group that gets the chunk — seize it with junk.
11207    /// Joining one would be worse: the handler tries each queued proof against
11208    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11209    /// on bytes it never offered.
11210    #[test]
11211    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11212        let genuine_data = vec![0x5Au8; 128];
11213        let key = crate::client::compute_address(&genuine_data);
11214        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11215
11216        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11217            .expect("bytes that do not hash to the advertised key must be refused");
11218        assert!(
11219            rejection.penalise,
11220            "no honest sender offers bytes that do not hash to the advertised key"
11221        );
11222
11223        // Dispatch reaches the entry only past that rejection, so the forged
11224        // offer never touched the key and the genuine one still opens it.
11225        assert!(
11226            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11227            "the offer that actually carries the key's bytes must reach the entry"
11228        );
11229
11230        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11231        assert!(
11232            matches!(
11233                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11234                FreshOfferAdmission::Opened(_)
11235            ),
11236            "an offer refused on payload shape must leave the key openable"
11237        );
11238    }
11239
11240    #[tokio::test]
11241    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11242        let peer = test_peer(0xA5);
11243        let key = test_key(0xA5);
11244        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11245        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11246        let is_bootstrapping = Arc::new(RwLock::new(true));
11247        let bootstrap_complete_notify = Arc::new(Notify::new());
11248
11249        let now = Instant::now();
11250        queues.write().await.add_pending_verify(
11251            key,
11252            VerificationEntry {
11253                state: VerificationState::PendingVerify,
11254                verified_sources: Vec::new(),
11255                tried_sources: HashSet::new(),
11256                created_at: now,
11257                next_verify_at: now,
11258                hint_sources: HashSet::from([peer]),
11259                replica_hint_sources: HashSet::from([peer]),
11260                unresolved_retries: 0,
11261                no_holder_reported: false,
11262            },
11263        );
11264        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11265        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11266        {
11267            let q = queues.read().await;
11268            assert!(
11269                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11270                "capacity rejection should initially block bootstrap drain"
11271            );
11272        }
11273
11274        update_bootstrap_after_peer_removed(
11275            &peer,
11276            &bootstrap_state,
11277            &queues,
11278            &is_bootstrapping,
11279            &bootstrap_complete_notify,
11280        )
11281        .await;
11282
11283        let state = bootstrap_state.read().await;
11284        assert!(state.capacity_rejected_sources.is_empty());
11285        assert!(state.pending_keys.is_empty());
11286        assert!(state.is_drained());
11287        drop(state);
11288        assert!(!*is_bootstrapping.read().await);
11289    }
11290
11291    /// A fairness displacement forfeits the key but must not stamp its former
11292    /// owner: the owner did nothing wrong, and stamping it lets a flooding
11293    /// source block bootstrap drain through an unrelated honest peer.
11294    #[tokio::test]
11295    async fn fairness_displacement_does_not_stamp_its_victim() {
11296        let displaced_owner = test_peer(0xB1);
11297        let incoming_source = test_peer(0xB2);
11298        let displaced_key = test_key(0xB1);
11299        let admitted_key = test_key(0xB2);
11300        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11301        {
11302            let mut state = bootstrap_state.write().await;
11303            state.pending_keys.insert(displaced_key);
11304            state
11305                .capacity_rejected_sources
11306                .insert(incoming_source, Instant::now());
11307        }
11308        let outcomes = [(
11309            incoming_source,
11310            AdmissionOutcome {
11311                discovered: HashSet::from([admitted_key]),
11312                capacity_rejected_count: 0,
11313                displaced: vec![CapacityDisplacement {
11314                    key: displaced_key,
11315                    owner: displaced_owner,
11316                }],
11317            },
11318        )];
11319
11320        publish_bootstrap_admission_outcomes(
11321            &bootstrap_state,
11322            &outcomes,
11323            &HashSet::from([admitted_key]),
11324        )
11325        .await;
11326
11327        let state = bootstrap_state.read().await;
11328        assert!(!state.pending_keys.contains(&displaced_key));
11329        assert!(state.pending_keys.contains(&admitted_key));
11330        assert!(
11331            !state
11332                .capacity_rejected_sources
11333                .contains_key(&displaced_owner),
11334            "the displaced owner must not be charged for our own fairness reclaim"
11335        );
11336        assert!(!state
11337            .capacity_rejected_sources
11338            .contains_key(&incoming_source));
11339    }
11340
11341    /// A source that keeps overflowing us must not keep its own record fresh.
11342    ///
11343    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11344    /// rejection the debt could never age out, so `check_bootstrap_drained`
11345    /// stayed false forever and auditing never started (Invariant 19).
11346    #[tokio::test]
11347    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11348        const REJECTION_ROUNDS: usize = 5;
11349
11350        let source = test_peer(0xB3);
11351        let key = test_key(0xB3);
11352        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11353
11354        let first_seen = {
11355            let outcomes = [(
11356                source,
11357                AdmissionOutcome {
11358                    discovered: HashSet::new(),
11359                    capacity_rejected_count: 1,
11360                    displaced: Vec::new(),
11361                },
11362            )];
11363            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11364                .await;
11365            bootstrap_state
11366                .read()
11367                .await
11368                .capacity_rejected_sources
11369                .get(&source)
11370                .copied()
11371                .expect("first rejection recorded")
11372        };
11373
11374        for _ in 0..REJECTION_ROUNDS {
11375            let outcomes = [(
11376                source,
11377                AdmissionOutcome {
11378                    discovered: HashSet::from([key]),
11379                    capacity_rejected_count: 1,
11380                    displaced: Vec::new(),
11381                },
11382            )];
11383            publish_bootstrap_admission_outcomes(
11384                &bootstrap_state,
11385                &outcomes,
11386                &HashSet::from([key]),
11387            )
11388            .await;
11389        }
11390
11391        let recorded = bootstrap_state
11392            .read()
11393            .await
11394            .capacity_rejected_sources
11395            .get(&source)
11396            .copied()
11397            .expect("debt still outstanding");
11398        assert_eq!(
11399            recorded, first_seen,
11400            "repeat rejections must not restart the expiry clock"
11401        );
11402    }
11403
11404    /// The verification-worker tick's self-heal path: a capacity rejection
11405    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11406    /// blocks drain until the TTL expires it, at which point the same tick
11407    /// completes bootstrap without any external event.
11408    #[tokio::test]
11409    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11410        let peer = test_peer(0xA6);
11411        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11412        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11413        let is_bootstrapping = Arc::new(RwLock::new(true));
11414        let bootstrap_complete_notify = Arc::new(Notify::new());
11415
11416        // PeerRemoved was fully processed before the rejection landed, so no
11417        // future event will ever clear this entry.
11418        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11419
11420        // Within the TTL the tick keeps waiting for re-delivery.
11421        expire_and_recheck_bootstrap_drain(
11422            &bootstrap_state,
11423            &queues,
11424            &is_bootstrapping,
11425            &bootstrap_complete_notify,
11426            ReplicationConfig::default().capacity_rejected_max_age(),
11427        )
11428        .await;
11429        assert!(!bootstrap_state.read().await.is_drained());
11430        assert!(*is_bootstrapping.read().await);
11431
11432        // Past the TTL the tick expires the orphan and completes bootstrap.
11433        expire_and_recheck_bootstrap_drain(
11434            &bootstrap_state,
11435            &queues,
11436            &is_bootstrapping,
11437            &bootstrap_complete_notify,
11438            Duration::ZERO,
11439        )
11440        .await;
11441        assert!(bootstrap_state.read().await.is_drained());
11442        assert!(!*is_bootstrapping.read().await);
11443    }
11444
11445    #[test]
11446    fn first_audit_terminal_outcomes_are_stable() {
11447        let peer = test_peer(1);
11448        let passed = AuditTickResult::Passed {
11449            challenged_peer: peer,
11450            keys_checked: 1,
11451        };
11452        let timed_out = AuditTickResult::Failed {
11453            evidence: FailureEvidence::AuditFailure {
11454                challenge_id: 1,
11455                challenged_peer: peer,
11456                confirmed_failed_keys: vec![test_key(1)],
11457                summary: crate::replication::types::AuditFailureSummary::default(),
11458                reason: AuditFailureReason::Timeout,
11459            },
11460            no_response_class: Some("timeout"),
11461        };
11462
11463        assert_eq!(
11464            first_audit_terminal_outcome(&passed),
11465            FirstAuditTerminalOutcome::Passed
11466        );
11467        assert_eq!(
11468            first_audit_terminal_outcome(&timed_out),
11469            FirstAuditTerminalOutcome::Timeout
11470        );
11471        assert_eq!(
11472            first_audit_terminal_outcome(&AuditTickResult::Idle),
11473            FirstAuditTerminalOutcome::Idle
11474        );
11475        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11476        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11477        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11478        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11479        assert_eq!(
11480            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11481            "insufficient_keys"
11482        );
11483        assert_eq!(
11484            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11485            "bootstrap_claim"
11486        );
11487    }
11488
11489    #[test]
11490    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11491        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11492        let mut rng = StdRng::seed_from_u64(7);
11493        let peer = test_peer(1);
11494        let base = MonetizedPinEvent {
11495            peer,
11496            pin: [1; 32],
11497            key_count: 100,
11498            quote_ts: SystemTime::now(),
11499        };
11500
11501        // First insert into an empty slot: Queued.
11502        assert_eq!(
11503            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11504            FirstAuditQueueOutcome::Queued
11505        );
11506
11507        // A strictly LOWER-count same-peer nomination must NOT displace it.
11508        let lower = MonetizedPinEvent {
11509            pin: [2; 32],
11510            key_count: 50,
11511            ..base
11512        };
11513        assert_eq!(
11514            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11515            FirstAuditQueueOutcome::SuppressedLower
11516        );
11517        assert_eq!(
11518            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11519            Some(([1; 32], 100)),
11520            "the higher-count pin is retained"
11521        );
11522
11523        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11524        let higher = MonetizedPinEvent {
11525            pin: [3; 32],
11526            key_count: 400,
11527            ..base
11528        };
11529        assert_eq!(
11530            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11531            FirstAuditQueueOutcome::Coalesced
11532        );
11533        assert_eq!(
11534            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11535            Some(([3; 32], 400))
11536        );
11537
11538        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11539        let equal_newer = MonetizedPinEvent {
11540            pin: [4; 32],
11541            key_count: 400,
11542            ..base
11543        };
11544        assert_eq!(
11545            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11546            FirstAuditQueueOutcome::Coalesced
11547        );
11548        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11549        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11550        let equal_older = MonetizedPinEvent {
11551            pin: [5; 32],
11552            key_count: 400,
11553            ..base
11554        };
11555        assert_eq!(
11556            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11557            FirstAuditQueueOutcome::RetainedOnTie
11558        );
11559        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11560
11561        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11562        let other_peer = MonetizedPinEvent {
11563            peer: test_peer(2),
11564            pin: [6; 32],
11565            key_count: 100,
11566            ..base
11567        };
11568        assert_eq!(
11569            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11570            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11571        );
11572        assert_eq!(pending.len(), 1);
11573        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11574    }
11575
11576    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11577
11578    #[test]
11579    fn first_audit_limiter_enforces_burst_then_refills() {
11580        let base = Instant::now();
11581        let mut limiter = FirstAuditLimiter::new(base);
11582        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11583
11584        // The full burst is admitted back-to-back (distinct peers).
11585        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11586            let peer = test_peer(u8::try_from(i).expect("small burst"));
11587            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11588            limiter.commit_launch(peer, 10, base);
11589        }
11590        // Bucket empty: the next distinct peer is deferred, never dropped.
11591        let extra = test_peer(0xEE);
11592        assert_eq!(
11593            limiter.assess(&extra, 10, base, 0),
11594            LimiterVerdict::RateDeferred
11595        );
11596
11597        // One full interval later exactly one token is available again.
11598        let later = base + interval;
11599        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11600        limiter.commit_launch(extra, 10, later);
11601        let extra2 = test_peer(0xEF);
11602        assert_eq!(
11603            limiter.assess(&extra2, 10, later, 0),
11604            LimiterVerdict::RateDeferred
11605        );
11606    }
11607
11608    #[test]
11609    fn first_audit_limiter_refill_keeps_fractional_remainder() {
11610        let base = Instant::now();
11611        let mut limiter = FirstAuditLimiter::new(base);
11612        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11613        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11614            let peer = test_peer(u8::try_from(i).expect("small burst"));
11615            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11616            limiter.commit_launch(peer, 1, base);
11617        }
11618        // 1.5 intervals later one token is earned and the half interval is
11619        // NOT lost to drift...
11620        let at_1_5 = base + interval + interval / 2;
11621        let p = test_peer(0xAA);
11622        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11623        limiter.commit_launch(p, 1, at_1_5);
11624        // ...so the next token arrives at 2.0 intervals, not 2.5.
11625        let at_2_0 = base + interval * 2;
11626        let q = test_peer(0xAB);
11627        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11628    }
11629
11630    #[test]
11631    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11632        let base = Instant::now();
11633        let mut limiter = FirstAuditLimiter::new(base);
11634        let peer = test_peer(1);
11635        assert_eq!(
11636            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11637            LimiterVerdict::RateDeferred
11638        );
11639        // A freed slot admits without any clock movement.
11640        assert_eq!(
11641            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11642            LimiterVerdict::Admit
11643        );
11644    }
11645
11646    #[test]
11647    fn first_audit_limiter_assess_consumes_nothing() {
11648        let base = Instant::now();
11649        let mut limiter = FirstAuditLimiter::new(base);
11650        let peer = test_peer(3);
11651        // Repeated assessment must not burn budget or stamp the window: only
11652        // `commit_launch` consumes (the cooldown gate between assess and
11653        // commit can defer, and that deferral must be free).
11654        for _ in 0..10 {
11655            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11656        }
11657        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11658            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11659            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11660            limiter.commit_launch(p, 5, base);
11661        }
11662    }
11663
11664    #[test]
11665    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11666        let base = Instant::now();
11667        let mut limiter = FirstAuditLimiter::new(base);
11668        let peer = test_peer(7);
11669        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11670        limiter.commit_launch(peer, 100, base);
11671
11672        // A rotated pin with a similar count inside the window is dropped...
11673        let soon = base + Duration::from_mins(1);
11674        assert_eq!(
11675            limiter.assess(&peer, 100, soon, 0),
11676            LimiterVerdict::WindowDeduped
11677        );
11678        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11679        assert_eq!(
11680            limiter.assess(&peer, 150, soon, 0),
11681            LimiterVerdict::WindowDeduped
11682        );
11683        // ...but a >1.5x committed-count jump re-nominates immediately (an
11684        // inflated sidecar-only pin is invisible to the gossip lottery, so
11685        // the window must not shield it).
11686        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11687
11688        // Window expiry re-admits an unchanged count.
11689        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11690        assert_eq!(
11691            limiter.assess(&peer, 100, expired, 0),
11692            LimiterVerdict::Admit
11693        );
11694    }
11695
11696    #[test]
11697    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11698        // A window-deduped nomination must be DROPPED, not kept pending as
11699        // rate-deferred, even when the bucket is also empty: re-queuing a
11700        // suppressed rotation would hold a pending slot for two hours.
11701        let base = Instant::now();
11702        let mut limiter = FirstAuditLimiter::new(base);
11703        let peer = test_peer(9);
11704        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11705        limiter.commit_launch(peer, 10, base);
11706        let other = test_peer(10);
11707        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11708        limiter.commit_launch(other, 10, base);
11709        assert_eq!(
11710            limiter.assess(&peer, 10, base, 0),
11711            LimiterVerdict::WindowDeduped
11712        );
11713    }
11714
11715    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11716    /// is answerable now but would age out of the answerability window during
11717    /// the launch jitter, so scheduling state is only ever committed for a pin
11718    /// that can still be challenged when it actually sends.
11719    #[test]
11720    fn first_audit_horizon_prefilter_boundary() {
11721        let now = SystemTime::now();
11722        // C = the too-old cutoff; H = the worst-case send horizon.
11723        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11724        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11725        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11726        let boundary = now
11727            .checked_add(h)
11728            .and_then(|t| t.checked_sub(c))
11729            .expect("boundary time");
11730
11731        // In window at `now` (age = C - H < C)...
11732        assert!(quote_within_audit_window(boundary, now));
11733        // ...but the horizon prefilter rejects it (age == C at now + H).
11734        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11735
11736        // A hair newer stays answerable through the horizon; a hair older does
11737        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11738        // a nanosecond step would round to the same instant there.
11739        let newer = boundary
11740            .checked_add(Duration::from_micros(1))
11741            .expect("newer");
11742        let older = boundary
11743            .checked_sub(Duration::from_micros(1))
11744            .expect("older");
11745        assert!(quote_answerable_through_nominal_jitter(newer, now));
11746        assert!(!quote_answerable_through_nominal_jitter(older, now));
11747
11748        // A quote too far in the FUTURE is rejected at `now`, independent of the
11749        // horizon.
11750        let future = now
11751            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11752            .and_then(|t| t.checked_add(Duration::from_mins(1)))
11753            .expect("future");
11754        assert!(!quote_answerable_through_nominal_jitter(future, now));
11755    }
11756
11757    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11758    /// answerability check fails at promotion is fully state-neutral — it stamps
11759    /// no `first_audited`, no per-peer window, refunds its token, releases its
11760    /// in-flight slot, does not flip the lane, and does not count a launch — and
11761    /// a same-peer, same-count successor enqueued DURING the reservation is
11762    /// retained and becomes the next reservation after the cancel. This is the
11763    /// exact hole the reviewer flagged: suppression must never outlive a launch
11764    /// that did not send.
11765    /// A pending pin that has aged past the answerability horizon must not
11766    /// suppress a live lower-count nomination for the same peer: under token
11767    /// starvation no reserve scan ever collects the dead entry, so without the
11768    /// enqueue-time check the peer would stay unauditable through this path
11769    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11770    #[test]
11771    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11772        let obs = Arc::new(FirstAuditObservability::default());
11773        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11774        let peer = test_peer(1);
11775
11776        let dead_quote = SystemTime::now()
11777            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11778            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
11779            .expect("past wall time");
11780        let stale_high = MonetizedPinEvent {
11781            peer,
11782            pin: [1; 32],
11783            key_count: 400,
11784            quote_ts: dead_quote,
11785        };
11786        scheduler.enqueue(stale_high, &obs);
11787        assert_eq!(scheduler.pending_len(), 1);
11788
11789        // A fresh, lower-count nomination (a post-prune commitment).
11790        let fresh_lower = MonetizedPinEvent {
11791            peer,
11792            pin: [2; 32],
11793            key_count: 100,
11794            quote_ts: SystemTime::now(),
11795        };
11796        scheduler.enqueue(fresh_lower, &obs);
11797
11798        assert_eq!(scheduler.pending_len(), 1);
11799        assert_eq!(
11800            scheduler.pending.peek(&peer).map(|e| e.pin),
11801            Some([2; 32]),
11802            "the live nomination replaced the dead incumbent"
11803        );
11804        assert_eq!(
11805            obs.suppressed_lower.load(Ordering::Relaxed),
11806            0,
11807            "no self-erasure signal for displacing a dead pin"
11808        );
11809        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11810        assert_eq!(
11811            obs.outside_answerability_window.load(Ordering::Relaxed),
11812            1,
11813            "the dead incumbent is accounted as an expiry"
11814        );
11815    }
11816
11817    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11818    /// nomination still loses to an answerable higher-count pending pin.
11819    #[test]
11820    fn first_audit_live_incumbent_still_suppresses_lower_count() {
11821        let obs = Arc::new(FirstAuditObservability::default());
11822        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11823        let peer = test_peer(1);
11824
11825        let live_high = MonetizedPinEvent {
11826            peer,
11827            pin: [1; 32],
11828            key_count: 400,
11829            quote_ts: SystemTime::now(),
11830        };
11831        scheduler.enqueue(live_high, &obs);
11832        let cheaper = MonetizedPinEvent {
11833            peer,
11834            pin: [2; 32],
11835            key_count: 100,
11836            quote_ts: SystemTime::now(),
11837        };
11838        scheduler.enqueue(cheaper, &obs);
11839
11840        assert_eq!(scheduler.pending_len(), 1);
11841        assert_eq!(
11842            scheduler.pending.peek(&peer).map(|e| e.pin),
11843            Some([1; 32]),
11844            "the higher-count live pin is retained"
11845        );
11846        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11847        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11848    }
11849
11850    /// A fresh nomination for peer `b` (distinct pin per peer).
11851    fn live_nomination(b: u8) -> MonetizedPinEvent {
11852        MonetizedPinEvent {
11853            peer: test_peer(b),
11854            pin: [b; 32],
11855            key_count: 100,
11856            quote_ts: SystemTime::now(),
11857        }
11858    }
11859
11860    /// The pending admission cap must equal the number of usable launches the
11861    /// token budget can perform inside one answerability window, counted by
11862    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11863    /// tokens at age zero, one refill per launch interval), not by repeating
11864    /// the derivation formula. Any larger and admitted work is guaranteed to
11865    /// expire unlaunched; any smaller and the budget idles while nominations
11866    /// are displaced.
11867    #[test]
11868    fn first_audit_pending_cap_matches_strict_launch_horizon() {
11869        let quote_ts = SystemTime::now();
11870        // Burst launches fire at age zero and must pass the reserve predicate.
11871        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11872        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11873        let mut refill = 1u32;
11874        loop {
11875            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11876            let at = quote_ts + age;
11877            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11878                break;
11879            }
11880            usable += 1;
11881            refill += 1;
11882            assert!(refill < 10_000, "runaway horizon simulation");
11883        }
11884        assert_eq!(
11885            FIRST_AUDIT_PENDING_CAP, usable,
11886            "cap must match the simulated strict launch horizon"
11887        );
11888    }
11889
11890    /// The pending queue is sized to the launch budget while the dedup set
11891    /// keeps the commitment-cache bound: shrinking `first_audited` would
11892    /// forget audited pins and re-admit duplicates.
11893    #[test]
11894    fn first_audit_pending_cap_independent_of_dedup_cap() {
11895        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11896        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11897        assert_eq!(
11898            scheduler.first_audited.cap().get(),
11899            MAX_LAST_COMMITMENT_BY_PEER
11900        );
11901    }
11902
11903    /// Admission beyond the cap displaces exactly one incumbent per overflow
11904    /// and every displacement is accounted as `capacity_evicted` — the steady
11905    /// overload signal — never silent loss, and never an admission refusal.
11906    #[test]
11907    fn first_audit_admission_beyond_cap_displaces_and_counts() {
11908        let obs = Arc::new(FirstAuditObservability::default());
11909        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11910        let overflow: usize = 5;
11911        let total = FIRST_AUDIT_PENDING_CAP + overflow;
11912
11913        for i in 0..total {
11914            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11915            scheduler.enqueue(live_nomination(b), &obs);
11916        }
11917
11918        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11919        assert_eq!(
11920            obs.capacity_evicted.load(Ordering::Relaxed),
11921            u64::try_from(overflow).expect("overflow fits u64"),
11922            "each admission past the cap displaces exactly one entry"
11923        );
11924        assert_eq!(
11925            obs.queued.load(Ordering::Relaxed),
11926            u64::try_from(total).expect("total fits u64"),
11927            "displacement is not an admission refusal"
11928        );
11929        // Every arrival was admitted (the newest always enters the sample).
11930        let last = u8::try_from(total).expect("test peer count fits u8");
11931        assert!(
11932            scheduler.pending.peek(&test_peer(last)).is_some(),
11933            "the newest arrival always enters the sample"
11934        );
11935    }
11936
11937    /// The reviewer-demonstrated suppression route: a target followed by an
11938    /// ordered batch of distinct-peer nominations, all inside one ingress
11939    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11940    /// the token bucket EMPTY so no reservation can intervene. Under the old
11941    /// keep-newest LRU the target was evicted with certainty; under random
11942    /// displacement its per-overflow eviction probability is `1/cap`, so
11943    /// across repeated trials the target must survive some runs and be
11944    /// displaced in others — never deterministically flushed, and every
11945    /// displacement accounted.
11946    #[test]
11947    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11948        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11949        assert!(FIRST_AUDIT_PENDING_CAP < flood);
11950        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11951
11952        let trials = 100u64;
11953        let mut survived = 0u32;
11954        let mut evicted = 0u32;
11955        for trial in 0..trials {
11956            let obs = Arc::new(FirstAuditObservability::default());
11957            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11958            // Deterministic per-trial seed: the run is fully reproducible (no
11959            // flake budget at all) while still exercising 100 distinct
11960            // eviction sequences.
11961            scheduler.rng = StdRng::seed_from_u64(trial);
11962            // Drain the burst tokens so the pre-overflow reservation
11963            // opportunity cannot fire: this isolates pure retention.
11964            scheduler.limiter.reserve_token();
11965            scheduler.limiter.reserve_token();
11966
11967            let target = test_peer(200);
11968            scheduler.enqueue(live_nomination(200), &obs);
11969            for i in 0..flood {
11970                let b = u8::try_from(i + 1).expect("flood peer fits u8");
11971                scheduler.enqueue(live_nomination(b), &obs);
11972            }
11973
11974            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11975            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11976                .expect("overflow count fits u64");
11977            assert_eq!(
11978                obs.capacity_evicted.load(Ordering::Relaxed),
11979                overflows,
11980                "every overflow past the cap is accounted, none silent"
11981            );
11982            if scheduler.pending.peek(&target).is_some() {
11983                survived += 1;
11984            } else {
11985                evicted += 1;
11986            }
11987        }
11988        // With eviction probability 1/cap per overflow, P(target survives one
11989        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11990        // 100 seeded trials — and the seeds make the split exactly
11991        // reproducible rather than a (vanishingly small) flake budget.
11992        assert!(
11993            survived > 0,
11994            "target must survive some ordered floods — deterministic eviction \
11995             would mean keep-newest retention regressed"
11996        );
11997        assert!(
11998            evicted > 0,
11999            "target must also be displaceable — otherwise overflow is refusing \
12000             admissions instead of sampling"
12001        );
12002    }
12003
12004    /// With a token AVAILABLE, an overflowing arrival must first give pending
12005    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12006    /// one entry out of the queue, so admission proceeds without any eviction.
12007    #[test]
12008    fn first_audit_overflow_reserves_before_destructive_eviction() {
12009        let obs = Arc::new(FirstAuditObservability::default());
12010        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12011        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12012
12013        for i in 0..FIRST_AUDIT_PENDING_CAP {
12014            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12015            scheduler.enqueue(live_nomination(b), &obs);
12016        }
12017        let overflowing = live_nomination(250);
12018        assert!(scheduler.would_displace(&overflowing));
12019
12020        // The drainer's pre-overflow sequence: reserve, then enqueue.
12021        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12022        assert!(
12023            !scheduler.would_displace(&overflowing),
12024            "a successful reservation frees the slot"
12025        );
12026        scheduler.enqueue(overflowing, &obs);
12027
12028        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12029        assert_eq!(
12030            obs.capacity_evicted.load(Ordering::Relaxed),
12031            0,
12032            "no destructive eviction when a launch opportunity existed"
12033        );
12034    }
12035
12036    /// Displacement stamps no suppression state: a displaced peer's next
12037    /// nomination re-enters like any newcomer (it is NOT window-deduped or
12038    /// treated as a duplicate), so under overload every peer keeps an
12039    /// unpredictable chance of prompt first audit.
12040    #[test]
12041    fn first_audit_displaced_peer_may_be_renominated() {
12042        let obs = Arc::new(FirstAuditObservability::default());
12043        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12044        let total = FIRST_AUDIT_PENDING_CAP + 1;
12045
12046        for i in 0..total {
12047            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12048            scheduler.enqueue(live_nomination(b), &obs);
12049        }
12050        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12051        // Find whichever peer the random displacement removed.
12052        let displaced = (1..=total)
12053            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12054            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12055            .expect("exactly one admitted peer was displaced");
12056
12057        scheduler.enqueue(live_nomination(displaced), &obs);
12058
12059        assert!(
12060            scheduler.pending.peek(&test_peer(displaced)).is_some(),
12061            "the displaced peer re-enters the sample"
12062        );
12063        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12064        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12065        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12066        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12067    }
12068
12069    /// The periodic sweep collects expired pending entries even when the token
12070    /// bucket is empty — the reserve path returns at the budget gate and never
12071    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12072    /// honest under fleet-wide starvation.
12073    #[test]
12074    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12075        let obs = Arc::new(FirstAuditObservability::default());
12076        let mono = Instant::now();
12077        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12078
12079        let dead_quote = SystemTime::now()
12080            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12081            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12082            .expect("past wall time");
12083        scheduler.enqueue(
12084            MonetizedPinEvent {
12085                peer: test_peer(1),
12086                pin: [1; 32],
12087                key_count: 100,
12088                quote_ts: dead_quote,
12089            },
12090            &obs,
12091        );
12092        scheduler.enqueue(
12093            MonetizedPinEvent {
12094                peer: test_peer(2),
12095                pin: [2; 32],
12096                key_count: 100,
12097                quote_ts: SystemTime::now(),
12098            },
12099            &obs,
12100        );
12101        assert_eq!(scheduler.pending_len(), 2);
12102
12103        // Empty the bucket so the reserve path is budget-gated (fleet-wide
12104        // starvation) and cannot collect the dead entry itself.
12105        scheduler.limiter.tokens = 0;
12106        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12107        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12108        assert_eq!(
12109            scheduler.pending_len(),
12110            2,
12111            "budget-gated reserve scans nothing"
12112        );
12113
12114        let wall_now = SystemTime::now();
12115        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12116        assert_eq!(scheduler.pending_len(), 1);
12117        assert!(
12118            scheduler.pending.peek(&test_peer(2)).is_some(),
12119            "the live entry survives the sweep"
12120        );
12121        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12122        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12123        assert!(
12124            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12125            "the age gauge reflects only live work after the sweep"
12126        );
12127    }
12128
12129    #[test]
12130    #[allow(clippy::too_many_lines)]
12131    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12132        let obs = Arc::new(FirstAuditObservability::default());
12133        let mono = Instant::now();
12134        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12135
12136        // A pre-existing window sentinel for an UNRELATED peer must survive the
12137        // cancel byte-for-byte (cancel never touches `recent`).
12138        let sentinel_peer = test_peer(0xAA);
12139        scheduler.limiter.promote(sentinel_peer, 500, mono);
12140        let sentinel_before = scheduler
12141            .limiter
12142            .recent
12143            .peek(&sentinel_peer)
12144            .copied()
12145            .expect("sentinel present");
12146
12147        let peer = test_peer(1);
12148        let a = MonetizedPinEvent {
12149            peer,
12150            pin: [1; 32],
12151            key_count: 100,
12152            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12153        };
12154        scheduler.enqueue(a, &obs);
12155
12156        let tokens_before = scheduler.tokens();
12157        let lane_before = scheduler.oldest_first_lane;
12158        let launched_before = obs.launched.load(Ordering::Relaxed);
12159        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12160
12161        // Reserve A (jitter 0 so it is immediately due).
12162        let inflight0 = obs.inflight.load(Ordering::Relaxed);
12163        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12164        assert_eq!(scheduler.reserved_peer(), Some(peer));
12165        assert_eq!(
12166            scheduler.tokens(),
12167            tokens_before - 1,
12168            "reserve consumes a token"
12169        );
12170        assert_eq!(
12171            obs.inflight.load(Ordering::Relaxed),
12172            1,
12173            "reserve holds a slot"
12174        );
12175
12176        // A same-peer, same-count successor arrives DURING the reservation. It
12177        // must be retained (bypasses the window for the reserved peer) and must
12178        // NOT create a second reservation.
12179        let b = MonetizedPinEvent {
12180            peer,
12181            pin: [2; 32],
12182            key_count: 100,
12183            quote_ts: SystemTime::now(),
12184        };
12185        scheduler.enqueue(b, &obs);
12186        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12187        assert!(
12188            !scheduler.try_reserve(
12189                mono,
12190                obs.inflight.load(Ordering::Relaxed),
12191                Duration::ZERO,
12192                &cooldown,
12193                &obs
12194            ),
12195            "no second reservation while one is outstanding"
12196        );
12197
12198        // Resolve A with an injected wall time PAST A's answerability cutoff.
12199        let reservation = scheduler
12200            .take_due_reservation(mono)
12201            .expect("A is due at jitter 0");
12202        let wall_fail = a
12203            .quote_ts
12204            .checked_add(GOSSIP_ANSWERABILITY_TTL)
12205            .and_then(|t| t.checked_add(Duration::from_secs(1)))
12206            .expect("past-cutoff wall time");
12207        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12208        assert!(
12209            promoted.is_none(),
12210            "answerability lapsed -> cancelled, not promoted"
12211        );
12212
12213        // State-neutral cancel.
12214        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12215        assert!(
12216            scheduler.limiter.recent.peek(&peer).is_none(),
12217            "cancel stamps no per-peer window"
12218        );
12219        assert_eq!(
12220            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12221            Some(sentinel_before),
12222            "unrelated window sentinel untouched"
12223        );
12224        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12225        assert_eq!(
12226            scheduler.tokens(),
12227            tokens_before,
12228            "token refunded on cancel"
12229        );
12230        assert_eq!(
12231            obs.inflight.load(Ordering::Relaxed),
12232            0,
12233            "in-flight slot released"
12234        );
12235        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12236        assert_eq!(
12237            obs.launched.load(Ordering::Relaxed),
12238            launched_before,
12239            "no launch counted"
12240        );
12241        assert_eq!(
12242            obs.outside_answerability_window.load(Ordering::Relaxed),
12243            1,
12244            "the cancel reason is recorded"
12245        );
12246
12247        // The successor is still pending and is now fully schedulable: a fresh
12248        // reserve makes B the next reservation (proving eligibility, not merely
12249        // that the limiter would admit it).
12250        assert_eq!(
12251            scheduler.pending_len(),
12252            1,
12253            "successor still pending after cancel"
12254        );
12255        assert!(scheduler.reserved.is_none());
12256        assert!(scheduler.try_reserve(
12257            mono,
12258            obs.inflight.load(Ordering::Relaxed),
12259            Duration::ZERO,
12260            &cooldown,
12261            &obs
12262        ));
12263        assert_eq!(
12264            scheduler.reserved_peer(),
12265            Some(peer),
12266            "the retained successor becomes the next reservation"
12267        );
12268    }
12269
12270    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12271    /// race, the reserved event is requeued ONLY if no same-peer successor is
12272    /// already pending. A successor arrived after the reservation, so it is the
12273    /// newer nomination (e.g. a count jump) and must not be overwritten by the
12274    /// older reserved event.
12275    #[test]
12276    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12277        let obs = Arc::new(FirstAuditObservability::default());
12278        let mono = Instant::now();
12279        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12280        let peer = test_peer(1);
12281
12282        // Reserve A.
12283        let a = MonetizedPinEvent {
12284            peer,
12285            pin: [1; 32],
12286            key_count: 100,
12287            quote_ts: SystemTime::now(),
12288        };
12289        scheduler.enqueue(a, &obs);
12290        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12291        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12292
12293        // A newer same-peer successor B (a count jump) arrives during the
12294        // reservation and is retained.
12295        let b = MonetizedPinEvent {
12296            peer,
12297            pin: [2; 32],
12298            key_count: 400,
12299            quote_ts: SystemTime::now(),
12300        };
12301        scheduler.enqueue(b, &obs);
12302        assert_eq!(scheduler.pending_len(), 1);
12303
12304        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12305        // is already stamped for the peer, so promotion loses the race.
12306        let reservation = scheduler.take_due_reservation(mono).expect("due");
12307        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12308        cooldown.insert(peer, mono); // freshly on cooldown
12309        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12310        assert!(promoted.is_none(), "cooldown race -> not promoted");
12311
12312        // B (newer) is preserved; A did NOT overwrite it.
12313        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12314        assert_eq!(
12315            scheduler.pending.peek(&peer).map(|e| e.pin),
12316            Some([2; 32]),
12317            "the newer successor B is retained, not the older reserved A"
12318        );
12319        assert!(scheduler.first_audited.is_empty());
12320        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12321    }
12322
12323    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12324    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12325    /// and saturates to `0` for a future-dated quote (clock skew) without
12326    /// panicking. A climbing value is the pending-work-aging-out signal.
12327    #[test]
12328    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12329        let now = SystemTime::now();
12330        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12331        assert_eq!(
12332            scheduler.oldest_pending_quote_age_ms(now),
12333            0,
12334            "empty pending -> zero"
12335        );
12336
12337        // Two peers: quotes 10s and 2s old. The gauge must track the older.
12338        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12339            let _ = coalesce_first_audit_event(
12340                &mut scheduler.pending,
12341                MonetizedPinEvent {
12342                    peer: test_peer(peer_id),
12343                    pin,
12344                    key_count: 100,
12345                    quote_ts: now - Duration::from_secs(secs),
12346                },
12347                true,
12348                &mut scheduler.rng,
12349            );
12350        }
12351        assert_eq!(
12352            scheduler.oldest_pending_quote_age_ms(now),
12353            10_000,
12354            "tracks the oldest (10s), not the newest (2s)"
12355        );
12356
12357        // A future-dated quote (clock skew) saturates to zero, never panics.
12358        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12359        let _ = coalesce_first_audit_event(
12360            &mut skewed.pending,
12361            MonetizedPinEvent {
12362                peer: test_peer(3),
12363                pin: [3; 32],
12364                key_count: 100,
12365                quote_ts: now + Duration::from_secs(5),
12366            },
12367            true,
12368            &mut skewed.rng,
12369        );
12370        assert_eq!(
12371            skewed.oldest_pending_quote_age_ms(now),
12372            0,
12373            "future quote_ts saturates to zero"
12374        );
12375    }
12376
12377    /// A flood of strictly-lower-count same-peer nominations must neither
12378    /// displace the retained higher pin NOR disturb its recency position (each
12379    /// is suppressed via `peek`, no `push`), and each must be counted as
12380    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12381    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12382    /// (the documented `lru` contract that also drives the reserve scan's lane
12383    /// ordering), deliberately independent of the overflow policy: eviction is
12384    /// random-victim, so no assertion may require a particular peer to be
12385    /// displaced.
12386    #[test]
12387    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12388        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12389            LruCache::new(NonZeroUsize::new(2).unwrap());
12390        let mut rng = StdRng::seed_from_u64(11);
12391        let victim = test_peer(1);
12392        let other = test_peer(2);
12393        // Victim (high count) inserted first (older), then `other` (newer/MRU).
12394        let _ = coalesce_first_audit_event(
12395            &mut pending,
12396            MonetizedPinEvent {
12397                peer: victim,
12398                pin: [1; 32],
12399                key_count: 400,
12400                quote_ts: SystemTime::now(),
12401            },
12402            true,
12403            &mut rng,
12404        );
12405        let _ = coalesce_first_audit_event(
12406            &mut pending,
12407            MonetizedPinEvent {
12408                peer: other,
12409                pin: [9; 32],
12410                key_count: 100,
12411                quote_ts: SystemTime::now(),
12412            },
12413            true,
12414            &mut rng,
12415        );
12416        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12417        assert_eq!(
12418            order_before,
12419            vec![other, victim],
12420            "sanity: `other` is MRU, the victim is LRU"
12421        );
12422
12423        // Flood the victim with cheaper nominations.
12424        let mut suppressed = 0u64;
12425        for i in 0..8u8 {
12426            let out = coalesce_first_audit_event(
12427                &mut pending,
12428                MonetizedPinEvent {
12429                    peer: victim,
12430                    pin: [i; 32],
12431                    key_count: 50,
12432                    quote_ts: SystemTime::now(),
12433                },
12434                true,
12435                &mut rng,
12436            );
12437            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12438            suppressed += 1;
12439        }
12440        assert_eq!(suppressed, 8);
12441        // Victim pin/count unchanged.
12442        assert_eq!(
12443            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12444            Some(([1; 32], 400))
12445        );
12446        // Recency untouched: the iteration order (which the reserve lanes
12447        // consume) is byte-for-byte what it was before the flood.
12448        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12449        assert_eq!(
12450            order_after, order_before,
12451            "the suppressed-lower flood must not have changed any recency position"
12452        );
12453    }
12454
12455    /// The cooldown-race requeue counts a genuine different-peer capacity
12456    /// eviction (the ADR promises capacity loss is observable).
12457    #[test]
12458    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12459        let obs = Arc::new(FirstAuditObservability::default());
12460        let mono = Instant::now();
12461        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12462        // Pending capacity 1 so a requeue of a different peer must evict.
12463        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12464        let reserved_peer = test_peer(1);
12465        let other_peer = test_peer(2);
12466
12467        // Reserve peer 1.
12468        scheduler.enqueue(
12469            MonetizedPinEvent {
12470                peer: reserved_peer,
12471                pin: [1; 32],
12472                key_count: 100,
12473                quote_ts: SystemTime::now(),
12474            },
12475            &obs,
12476        );
12477        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12478        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12479
12480        // A DIFFERENT peer fills the single pending slot during the reservation.
12481        scheduler.enqueue(
12482            MonetizedPinEvent {
12483                peer: other_peer,
12484                pin: [2; 32],
12485                key_count: 100,
12486                quote_ts: SystemTime::now(),
12487            },
12488            &obs,
12489        );
12490        assert_eq!(scheduler.pending_len(), 1);
12491
12492        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12493        let reservation = scheduler.take_due_reservation(mono).expect("due");
12494        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12495        cooldown.insert(reserved_peer, mono);
12496        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12497        assert!(scheduler
12498            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12499            .is_none());
12500        assert_eq!(
12501            obs.capacity_evicted.load(Ordering::Relaxed),
12502            cap_before + 1,
12503            "the requeue eviction of a different peer is counted"
12504        );
12505        assert_eq!(
12506            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12507            Some([1; 32])
12508        );
12509    }
12510
12511    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12512    /// nomination arriving while an inflated pin is PENDING must not displace it.
12513    /// The inflated pin stays and is the one launched.
12514    #[test]
12515    fn first_audit_pending_lower_count_does_not_replace_higher() {
12516        let obs = Arc::new(FirstAuditObservability::default());
12517        let mono = Instant::now();
12518        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12519        let peer = test_peer(1);
12520
12521        // Inflated (high-count) sidecar pin lands in pending.
12522        scheduler.enqueue(
12523            MonetizedPinEvent {
12524                peer,
12525                pin: [1; 32],
12526                key_count: 400,
12527                quote_ts: SystemTime::now(),
12528            },
12529            &obs,
12530        );
12531        // A cheaper same-peer settlement arrives right after.
12532        scheduler.enqueue(
12533            MonetizedPinEvent {
12534                peer,
12535                pin: [2; 32],
12536                key_count: 100,
12537                quote_ts: SystemTime::now(),
12538            },
12539            &obs,
12540        );
12541
12542        assert_eq!(scheduler.pending_len(), 1);
12543        assert_eq!(
12544            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12545            Some(([1; 32], 400)),
12546            "the inflated pin must not be erased by the cheaper successor"
12547        );
12548        // The dropped cheaper nomination is counted through the enqueue path.
12549        assert_eq!(
12550            obs.suppressed_lower.load(Ordering::Relaxed),
12551            1,
12552            "the attempted cheaper-pin self-erasure is observable"
12553        );
12554
12555        // It reserves and promotes as the inflated pin/count.
12556        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12557        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12558        let reservation = scheduler.take_due_reservation(mono).expect("due");
12559        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12560        let (event, _slot) = scheduler
12561            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12562            .expect("promotes");
12563        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12564    }
12565
12566    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12567    /// loses the cooldown race must be requeued OVER a lower-count same-peer
12568    /// successor that arrived during its jitter, and must remain launchable once
12569    /// the shared cooldown expires — the cheaper successor cannot suppress it.
12570    #[test]
12571    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12572        let obs = Arc::new(FirstAuditObservability::default());
12573        let mono = Instant::now();
12574        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12575        let peer = test_peer(1);
12576
12577        // Reserve the inflated pin.
12578        scheduler.enqueue(
12579            MonetizedPinEvent {
12580                peer,
12581                pin: [1; 32],
12582                key_count: 400,
12583                quote_ts: SystemTime::now(),
12584            },
12585            &obs,
12586        );
12587        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12588        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12589
12590        // A cheaper successor arrives during the reservation (bypasses the
12591        // window as the reserved peer) and sits in pending.
12592        scheduler.enqueue(
12593            MonetizedPinEvent {
12594                peer,
12595                pin: [2; 32],
12596                key_count: 100,
12597                quote_ts: SystemTime::now(),
12598            },
12599            &obs,
12600        );
12601        assert_eq!(scheduler.pending_len(), 1);
12602
12603        // Resolve: answerability passes but the shared cooldown is already
12604        // stamped, so the reservation loses the race and requeues.
12605        let reservation = scheduler.take_due_reservation(mono).expect("due");
12606        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12607        cooldown.insert(peer, mono);
12608        assert!(scheduler
12609            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12610            .is_none());
12611
12612        // The inflated pin (400) replaced the cheaper successor (100).
12613        assert_eq!(scheduler.pending_len(), 1);
12614        assert_eq!(
12615            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12616            Some(([1; 32], 400)),
12617            "the inflated reserved pin must survive the requeue over the cheaper successor"
12618        );
12619        assert!(scheduler.first_audited.is_empty());
12620        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12621
12622        // Once the shared cooldown expires, the inflated pin reserves and
12623        // promotes with its intended pin/count.
12624        let later = mono
12625            .checked_add(Duration::from_secs(
12626                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12627            ))
12628            .expect("later");
12629        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12630        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12631        let reservation = scheduler.take_due_reservation(later).expect("due");
12632        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12633        let (event, _slot) = scheduler
12634            .resolve(
12635                reservation,
12636                SystemTime::now(),
12637                later,
12638                &mut cooldown_later,
12639                &obs,
12640            )
12641            .expect("promotes after cooldown");
12642        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12643    }
12644
12645    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12646    /// launch lane, driven through the real scheduler (reserve -> resolve ->
12647    /// promote), so a stream of fresh nominations cannot keep every launch on
12648    /// the newest lane and starve the oldest.
12649    #[test]
12650    fn first_audit_lane_alternates_across_promotions() {
12651        let obs = Arc::new(FirstAuditObservability::default());
12652        let mono = Instant::now();
12653        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12654        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12655
12656        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12657        let oldest_peer = test_peer(1);
12658        let newest_peer = test_peer(2);
12659        scheduler.enqueue(
12660            MonetizedPinEvent {
12661                peer: oldest_peer,
12662                pin: [1; 32],
12663                key_count: 100,
12664                quote_ts: SystemTime::now(),
12665            },
12666            &obs,
12667        );
12668        scheduler.enqueue(
12669            MonetizedPinEvent {
12670                peer: newest_peer,
12671                pin: [2; 32],
12672                key_count: 100,
12673                quote_ts: SystemTime::now(),
12674            },
12675            &obs,
12676        );
12677
12678        let mut launched_peers = Vec::new();
12679        for _ in 0..2 {
12680            assert!(scheduler.try_reserve(
12681                mono,
12682                obs.inflight.load(Ordering::Relaxed),
12683                Duration::ZERO,
12684                &cooldown,
12685                &obs
12686            ));
12687            let reservation = scheduler.take_due_reservation(mono).expect("due");
12688            // Answerable wall time == the quote's own time (age 0).
12689            let (event, _slot) = scheduler
12690                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12691                .expect("fresh in-window quote promotes");
12692            launched_peers.push(event.peer);
12693        }
12694
12695        // First launch takes the newest lane (lane starts false = newest), the
12696        // second takes the oldest lane: strict alternation.
12697        assert_eq!(
12698            launched_peers,
12699            vec![newest_peer, oldest_peer],
12700            "consecutive promotions alternate newest-then-oldest lane"
12701        );
12702    }
12703
12704    #[test]
12705    fn first_audit_count_jump_boundaries() {
12706        // Exactly 1.5x is NOT a jump; strictly above is.
12707        assert!(!first_audit_count_jump(100, 150));
12708        assert!(first_audit_count_jump(100, 151));
12709        // Anything beats an audited zero; zero never jumps.
12710        assert!(first_audit_count_jump(0, 1));
12711        assert!(!first_audit_count_jump(0, 0));
12712        // Equal max counts must not jump (and must not overflow).
12713        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12714    }
12715
12716    /// A verified payment's quote list includes the local node's own quote, so
12717    /// the verifier emits a monetized-pin event for the local peer on every
12718    /// payment it verifies. The node cannot network-audit itself, so the
12719    /// scheduler must drop such an event at ingress: never queued, and hence
12720    /// never launched nor marked first-audited.
12721    #[test]
12722    fn first_audit_queue_drops_self_targeting_events() {
12723        let obs = Arc::new(FirstAuditObservability::default());
12724        let self_peer = test_peer(1);
12725        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12726        let self_event = MonetizedPinEvent {
12727            peer: self_peer,
12728            pin: [7; 32],
12729            key_count: 1,
12730            quote_ts: SystemTime::now(),
12731        };
12732
12733        scheduler.enqueue(self_event, &obs);
12734        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12735        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12736        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12737
12738        // A remote peer's event still queues normally under the same filter.
12739        let remote_event = MonetizedPinEvent {
12740            peer: test_peer(2),
12741            pin: [8; 32],
12742            ..self_event
12743        };
12744        scheduler.enqueue(remote_event, &obs);
12745        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12746        assert_eq!(scheduler.pending_len(), 1);
12747        assert_eq!(
12748            obs.self_target_skipped.load(Ordering::Relaxed),
12749            1,
12750            "remote event must not count as a self-target skip"
12751        );
12752    }
12753
12754    #[test]
12755    fn fresh_offer_runs_store_admission_payment_checks() {
12756        let context = fresh_offer_payment_context();
12757        assert_eq!(context, VerificationContext::FreshReplication);
12758        // Fresh replication must keep verifying exactly like a direct client
12759        // PUT (store-strength cache, same live checks); the variant only
12760        // exists so price-floor telemetry can tell the two paths apart.
12761        assert!(context.is_store_admission());
12762    }
12763
12764    #[test]
12765    fn paid_notify_uses_paid_list_admission_payment_checks() {
12766        assert_eq!(
12767            paid_notify_payment_context(),
12768            VerificationContext::PaidListAdmission
12769        );
12770    }
12771
12772    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12773    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12774    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12775    #[test]
12776    fn monetized_quote_audit_window_fails_closed_both_ends() {
12777        let now = SystemTime::now();
12778        // Fresh (just quoted) and small future/past skew -> audited.
12779        assert!(quote_within_audit_window(now, now));
12780        assert!(quote_within_audit_window(now + Duration::from_mins(1), now));
12781        assert!(quote_within_audit_window(
12782            now - Duration::from_hours(1),
12783            now
12784        ));
12785        // Far future (badly-skewed / replayed) -> skipped.
12786        assert!(!quote_within_audit_window(
12787            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_mins(1),
12788            now
12789        ));
12790        // Older than the window -> skipped (pin may have aged out).
12791        assert!(!quote_within_audit_window(
12792            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12793            now
12794        ));
12795    }
12796
12797    #[tokio::test]
12798    async fn replication_branch_lagged_events_are_counted() {
12799        let before = audit_metrics::replication_event_lagged_total();
12800        let flow = handle_replication_event_recv_error(
12801            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12802        );
12803        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12804        let after = audit_metrics::replication_event_lagged_total();
12805        assert_eq!(after.saturating_sub(before), 3);
12806    }
12807
12808    #[tokio::test]
12809    async fn replication_branch_closed_events_stop_the_loop() {
12810        let flow =
12811            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12812        assert_eq!(flow, std::ops::ControlFlow::Break(()));
12813    }
12814
12815    #[tokio::test]
12816    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12817        let (sender, mut receiver) = mpsc::channel(1);
12818        let dropped_body =
12819            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12820                keys: Vec::new(),
12821                paid_list_check_indices: Vec::new(),
12822            });
12823        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12824        let first = InboundReplicationMessage {
12825            source: test_peer(0xC1),
12826            msg: ReplicationMessage {
12827                request_id: 1,
12828                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12829                    key: test_key(1),
12830                }),
12831            },
12832            rr_message_id: None,
12833            received_at: Instant::now(),
12834        };
12835        let second = InboundReplicationMessage {
12836            source: test_peer(0xC2),
12837            msg: ReplicationMessage {
12838                request_id: 2,
12839                body: dropped_body.clone(),
12840            },
12841            rr_message_id: None,
12842            received_at: Instant::now(),
12843        };
12844
12845        assert!(try_enqueue_serial_message(&sender, first).is_ok());
12846        let dropped = try_enqueue_serial_message(&sender, second)
12847            .expect_err("a full serial queue must refuse the second message");
12848        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12849        assert_eq!(dropped.message_class, "verification_request");
12850        assert_eq!(dropped.queue_depth, 1);
12851        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12852        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12853
12854        let queued = receiver
12855            .recv()
12856            .await
12857            .expect("first message should remain queued");
12858        assert_eq!(queued.msg.request_id, 1);
12859        assert!(receiver.try_recv().is_err());
12860    }
12861
12862    #[tokio::test]
12863    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12864        let peer = test_peer(0x44);
12865        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12866
12867        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12868        let mut digest_guards = Vec::new();
12869        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12870            let guard = admit_audit_responder(
12871                &semaphore,
12872                &digest_inflight,
12873                &peer,
12874                AuditResponderClass::Digest,
12875            )
12876            .await;
12877            assert!(guard.is_ok());
12878            digest_guards.push(guard);
12879        }
12880        assert!(
12881            admit_audit_responder(
12882                &semaphore,
12883                &digest_inflight,
12884                &peer,
12885                AuditResponderClass::Digest,
12886            )
12887            .await
12888            .is_err(),
12889            "digest class must stop at its documented per-source cap"
12890        );
12891        drop(digest_guards);
12892
12893        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12894        let mut subtree_guards = Vec::new();
12895        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12896            let guard = admit_audit_responder(
12897                &semaphore,
12898                &subtree_inflight,
12899                &peer,
12900                AuditResponderClass::Subtree,
12901            )
12902            .await;
12903            assert!(guard.is_ok());
12904            subtree_guards.push(guard);
12905        }
12906        assert!(
12907            admit_audit_responder(
12908                &semaphore,
12909                &subtree_inflight,
12910                &peer,
12911                AuditResponderClass::Subtree,
12912            )
12913            .await
12914            .is_err(),
12915            "subtree class must retain the deployed cap of two"
12916        );
12917        drop(subtree_guards);
12918    }
12919
12920    #[test]
12921    fn in_scope_audit_deadlines_share_one_formula() {
12922        let config = config::ReplicationConfig::default();
12923        for key_count in [1, 4, 16] {
12924            assert_eq!(
12925                audit::responsible_audit_response_timeout(&config, key_count),
12926                config.audit_response_timeout(key_count)
12927            );
12928            assert_eq!(
12929                pruning::prune_audit_response_timeout(&config, key_count),
12930                config.audit_response_timeout(key_count)
12931            );
12932        }
12933        assert_eq!(
12934            possession::possession_probe_response_timeout(&config),
12935            config.audit_response_timeout(1)
12936        );
12937    }
12938
12939    #[test]
12940    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12941        const EXISTING_SOURCE_ID: u8 = 1;
12942        const HINT_SENDER_ID: u8 = 2;
12943
12944        let existing_source = test_peer(EXISTING_SOURCE_ID);
12945        let hint_sender = test_peer(HINT_SENDER_ID);
12946        let mut sources = vec![existing_source];
12947
12948        let hint_sources = HashSet::from([hint_sender]);
12949        add_replica_hint_sources(&mut sources, &hint_sources);
12950        add_replica_hint_sources(&mut sources, &hint_sources);
12951
12952        // A paid-only advertiser leaves the claim set empty (see
12953        // `queue_admitted_hints`), so it contributes no fetch source.
12954        add_replica_hint_sources(&mut sources, &HashSet::new());
12955
12956        assert_eq!(sources, vec![existing_source, hint_sender]);
12957    }
12958
12959    #[test]
12960    fn audit_timeout_preserves_active_bootstrap_claim() {
12961        assert!(!audit_failure_clears_bootstrap_claim(
12962            &AuditFailureReason::Timeout
12963        ));
12964    }
12965
12966    fn strike_peer(b: u8) -> PeerId {
12967        let mut bytes = [0u8; 32];
12968        bytes[0] = b;
12969        PeerId::from_bytes(bytes)
12970    }
12971
12972    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12973    // cooldown must collapse a gossip flood into at most one audit per window.
12974
12975    #[test]
12976    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12977        let peer = strike_peer(1);
12978        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12979        let t0 = Instant::now();
12980        // First gossip in the window passes; a burst of further gossips at the
12981        // same instant are all suppressed.
12982        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12983        let mut passed = 1;
12984        for _ in 0..100 {
12985            if cooldown_allows_audit(&mut map, &peer, t0) {
12986                passed += 1;
12987            }
12988        }
12989        assert_eq!(
12990            passed, 1,
12991            "a flood at one instant must trigger exactly one audit"
12992        );
12993    }
12994
12995    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12996    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12997    // consumes the window. This is the property the isolated cooldown tests above
12998    // cannot see: they never sample the lottery, so a regression that reordered
12999    // the gates (sample probability first, only stamp the cooldown on a win)
13000    // would still pass them while breaking flood-resistance: a flood would then
13001    // re-roll the lottery on EVERY message until one won, multiplying audits.
13002    //
13003    // We model the exact production gate order (attempt-window, lottery,
13004    // shared cooldown) with a lottery driven by a fixed outcome instead of
13005    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13006    // messages all WIN. With the production order, the losing first ticket
13007    // burns the ATTEMPT window and every later winner in the same window is
13008    // blocked, so there are 0 audits this window. If the gates were flipped,
13009    // the second message's winning ticket would slip through. The window only
13010    // reopens after it elapses.
13011    //
13012    // FLIPS IF: the lottery is sampled before the attempt-window
13013    // check-and-stamp (a losing ticket no longer consumes the window),
13014    // re-enabling a flood-amplified audit storm.
13015    #[test]
13016    fn losing_lottery_still_consumes_attempt_window() {
13017        // Calls the SHIPPED `audit_launch_decision` (the same function
13018        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13019        // production fails this test — not a local reimplementation.
13020        let peer = strike_peer(3);
13021        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13022        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13023        let t0 = Instant::now();
13024
13025        // First flooded message at t0 LOSES the lottery, but the attempt window
13026        // is stamped BEFORE the lottery is consulted, so the window is consumed.
13027        assert!(
13028            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13029            "a losing ticket launches no audit"
13030        );
13031
13032        // 99 more flooded messages at the same instant would all WIN the lottery,
13033        // yet every one must be blocked by the attempt window the loser stamped.
13034        // (If production sampled the lottery FIRST, these would each get a fresh
13035        // roll and audits would multiply — this assertion catches that reorder.)
13036        let mut audits = 0;
13037        for _ in 0..99 {
13038            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13039                audits += 1;
13040            }
13041        }
13042        assert_eq!(
13043            audits, 0,
13044            "a losing first ticket must consume the attempt window so no later \
13045             flooded message in the same window can audit"
13046        );
13047
13048        // The window only reopens after it elapses; the next winning ticket
13049        // then launches exactly one audit and stamps the SHARED cooldown.
13050        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13051        assert!(
13052            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13053            "after the window a winning ticket audits again"
13054        );
13055        assert!(
13056            launched.contains_key(&peer),
13057            "a real launch stamps the shared cooldown"
13058        );
13059    }
13060
13061    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13062    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13063    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13064    /// first audit deferred until its answerability window expires.
13065    ///
13066    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13067    /// loss (the pre-split behavior, where both paths shared one map).
13068    #[test]
13069    fn losing_lottery_does_not_suppress_monetized_first_audit() {
13070        let peer = strike_peer(4);
13071        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13072        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13073        let t0 = Instant::now();
13074
13075        // A losing ticket consumes the gossip attempt window...
13076        assert!(!audit_launch_decision(
13077            &mut attempts,
13078            &mut launched,
13079            &peer,
13080            t0,
13081            false
13082        ));
13083        // ...but leaves the shared map untouched, so the first-audit reserve
13084        // gate (read-only) and the authoritative promotion check-and-stamp both
13085        // still allow the paid audit to launch immediately.
13086        assert!(
13087            cooldown_would_allow(&launched, &peer, t0),
13088            "reserve gate must not see a losing ticket as audit coverage"
13089        );
13090        assert!(
13091            cooldown_allows_audit(&mut launched, &peer, t0),
13092            "promotion must not be deferred by a losing ticket"
13093        );
13094
13095        // Conversely a WINNING ticket (real audit sent) does suppress the
13096        // first audit for the window, which is the intended shared semantics.
13097        let peer_won = strike_peer(5);
13098        assert!(audit_launch_decision(
13099            &mut attempts,
13100            &mut launched,
13101            &peer_won,
13102            t0,
13103            true
13104        ));
13105        assert!(
13106            !cooldown_would_allow(&launched, &peer_won, t0),
13107            "a real gossip audit still covers the peer for the window"
13108        );
13109    }
13110
13111    #[test]
13112    fn cooldown_lets_audit_through_after_the_window() {
13113        let peer = strike_peer(2);
13114        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13115        let t0 = Instant::now();
13116        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13117        // Within the window: suppressed.
13118        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13119        assert!(!cooldown_allows_audit(&mut map, &peer, within));
13120        // Past the window: allowed again.
13121        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13122        assert!(cooldown_allows_audit(&mut map, &peer, after));
13123    }
13124
13125    #[test]
13126    fn cooldown_is_per_peer_independent() {
13127        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13128        let t0 = Instant::now();
13129        // Different peers each get their own first-audit pass at the same instant.
13130        for i in 0..20u8 {
13131            assert!(
13132                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13133                "peer {i} should be auditable independently"
13134            );
13135        }
13136    }
13137
13138    #[test]
13139    fn audit_on_gossip_constants_match_adr() {
13140        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13141        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13142        // values above 5 would silently never be requested).
13143        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13144        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13145        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13146    }
13147
13148    // (d) A confirmed storage-integrity failure penalizes immediately and
13149    // revokes credit; it is not a timeout.
13150    #[test]
13151    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13152        assert!(audit_failure_clears_bootstrap_claim(
13153            &AuditFailureReason::DigestMismatch
13154        ));
13155        assert!(audit_failure_revokes_holder_credit(
13156            &AuditFailureReason::DigestMismatch
13157        ));
13158    }
13159
13160    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13161    /// uses: confirmed failures revoke credit, `Timeout` does not.
13162    #[test]
13163    fn confirmed_failures_revoke_credit_timeout_does_not() {
13164        for reason in [
13165            AuditFailureReason::MalformedResponse,
13166            AuditFailureReason::DigestMismatch,
13167            AuditFailureReason::KeyAbsent,
13168            AuditFailureReason::Rejected,
13169        ] {
13170            assert!(
13171                audit_failure_revokes_holder_credit(&reason),
13172                "confirmed failure {reason:?} must revoke holder credit"
13173            );
13174        }
13175        assert!(
13176            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13177            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13178        );
13179    }
13180
13181    /// Wiring test for the security fix: the helper the handler calls
13182    /// actually strips a credited peer on a confirmed failure
13183    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13184    /// Records genuine credit first so neither assertion is vacuous;
13185    /// this fails if `forget_peer` stops being called, or if the
13186    /// `Timeout` exclusion is dropped (both verified by mutation).
13187    #[test]
13188    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13189        let peer = test_peer(0xAB);
13190        let key = test_key(1);
13191        let hash = [0xCD; 32];
13192
13193        // Confirmed failure -> credit revoked.
13194        let mut provers = RecentProvers::new();
13195        provers.record_proof(key, peer, hash, Instant::now());
13196        assert!(
13197            provers.is_credited_holder(&key, &peer, &hash),
13198            "precondition: peer credited before failure"
13199        );
13200        apply_audit_failure_credit_revocation(
13201            &mut provers,
13202            &peer,
13203            &AuditFailureReason::DigestMismatch,
13204        );
13205        assert!(
13206            !provers.is_credited_holder(&key, &peer, &hash),
13207            "DigestMismatch must strip the peer's holder credit"
13208        );
13209
13210        // Timeout -> credit retained.
13211        let mut provers_timeout = RecentProvers::new();
13212        provers_timeout.record_proof(key, peer, hash, Instant::now());
13213        apply_audit_failure_credit_revocation(
13214            &mut provers_timeout,
13215            &peer,
13216            &AuditFailureReason::Timeout,
13217        );
13218        assert!(
13219            provers_timeout.is_credited_holder(&key, &peer, &hash),
13220            "Timeout must retain holder credit (deliberate liveness cushion)"
13221        );
13222    }
13223
13224    #[test]
13225    fn decoded_audit_failures_clear_active_bootstrap_claim() {
13226        for reason in [
13227            AuditFailureReason::MalformedResponse,
13228            AuditFailureReason::DigestMismatch,
13229            AuditFailureReason::KeyAbsent,
13230            AuditFailureReason::Rejected,
13231        ] {
13232            assert!(
13233                audit_failure_clears_bootstrap_claim(&reason),
13234                "decoded non-bootstrap failure {reason:?} should clear active claim"
13235            );
13236        }
13237    }
13238
13239    #[test]
13240    fn first_failed_key_label_truncates_to_16_hex_chars() {
13241        // The high-order 8 bytes of the XorName determine the label so an
13242        // operator can group audit-failures on the same chunk prefix.
13243        let mut key = [0u8; 32];
13244        key[0] = 0x18;
13245        key[7] = 0xff;
13246        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13247        // to verify they are NOT included in the label.
13248        for byte in &mut key[8..] {
13249            *byte = 0xAA;
13250        }
13251        let label = first_failed_key_label(&[key]);
13252        // Only the first 8 bytes are encoded, low-order bytes are dropped.
13253        assert_eq!(label, "0x18000000000000ff");
13254        assert_eq!(label.len(), "0x".len() + 16);
13255    }
13256
13257    #[test]
13258    fn first_failed_key_label_falls_back_when_empty() {
13259        // Should never happen in production (audit failure handling rejects
13260        // empty sets), but the formatter must still produce a valid label
13261        // so the log line doesn't contain a misleading default.
13262        assert_eq!(first_failed_key_label(&[]), "0x");
13263    }
13264
13265    #[test]
13266    fn first_failed_key_label_uses_first_key_only() {
13267        let first = [0x11u8; 32];
13268        let second = [0x22u8; 32];
13269        assert_eq!(
13270            first_failed_key_label(&[first, second]),
13271            format!("0x{}", hex::encode(&first[..8]))
13272        );
13273    }
13274
13275    // -- apply_fetch_result --------------------------------------------------
13276    //
13277    // The worker's disposition of a fetch outcome. Note there is no trust
13278    // handle in `apply_fetch_result`'s signature: the worker cannot report a
13279    // trust event for ANY outcome, and `execute_single_fetch` returns
13280    // `NoLongerResponsible` before its trust-reporting paths — the source did
13281    // nothing wrong when this node's own responsibility lapsed.
13282
13283    /// Route `key` through the real pipeline stages (pending → promoted →
13284    /// dequeued → in-flight) so it carries a verification retry-slot
13285    /// reservation, exactly as a worker-dequeued key does. Returns the
13286    /// in-flight source.
13287    fn drive_key_in_flight(
13288        q: &mut ReplicationQueues,
13289        key: XorName,
13290        sources: Vec<PeerId>,
13291    ) -> PeerId {
13292        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13293        let now = Instant::now();
13294        let entry = VerificationEntry {
13295            state: VerificationState::PendingVerify,
13296            verified_sources: Vec::new(),
13297            tried_sources: HashSet::new(),
13298            created_at: now,
13299            next_verify_at: now,
13300            hint_sources: HashSet::from([hinter]),
13301            replica_hint_sources: HashSet::from([hinter]),
13302            unresolved_retries: 0,
13303            no_holder_reported: false,
13304        };
13305        assert!(q.add_pending_verify(key, entry).admitted());
13306        assert!(q.promote_pending_to_fetch(key, key, sources));
13307        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13308        let source = *candidate.sources.first().expect("candidate has a source");
13309        q.start_dequeued_fetch(candidate, source);
13310        source
13311    }
13312
13313    #[test]
13314    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13315        const RETRY_AFTER: Duration = Duration::from_mins(1);
13316
13317        let mut q = ReplicationQueues::new();
13318        let key = test_key(0xAB);
13319        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13320        assert_eq!(q.retry_reserved_slot_count(), 1);
13321
13322        let follow_up =
13323            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13324
13325        assert_eq!(
13326            follow_up,
13327            FetchFollowUp::Terminal,
13328            "lapsed responsibility must run the caller's terminal bootstrap accounting"
13329        );
13330        assert!(
13331            !q.contains_key(&key),
13332            "the key must leave every pipeline stage — alternate sources included"
13333        );
13334        assert_eq!(
13335            q.pending_count(),
13336            0,
13337            "a lapsed-responsibility key must not be requeued for verification"
13338        );
13339        assert_eq!(
13340            q.retry_reserved_slot_count(),
13341            0,
13342            "terminal exit must release the verification retry-slot reservation"
13343        );
13344    }
13345
13346    #[test]
13347    fn no_longer_responsible_shares_the_stored_terminal_path() {
13348        const RETRY_AFTER: Duration = Duration::from_mins(1);
13349
13350        // Both variants must walk the identical terminal gate so the
13351        // battle-tested Stored accounting (retry-slot release + bootstrap
13352        // pending-set shrink in the caller) covers lapsed responsibility too.
13353        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13354            let mut q = ReplicationQueues::new();
13355            let key = test_key(0xCD);
13356            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13357
13358            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13359
13360            assert_eq!(follow_up, FetchFollowUp::Terminal);
13361            assert!(!q.contains_key(&key));
13362            assert_eq!(q.retry_reserved_slot_count(), 0);
13363        }
13364    }
13365
13366    #[test]
13367    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13368        const RETRY_AFTER: Duration = Duration::from_mins(1);
13369
13370        let mut q = ReplicationQueues::new();
13371        let key = test_key(0xEF);
13372        let first = test_peer(0x04);
13373        let second = test_peer(0x05);
13374        drive_key_in_flight(&mut q, key, vec![first, second]);
13375
13376        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13377        assert_eq!(
13378            follow_up,
13379            FetchFollowUp::RetryFrom(second),
13380            "a failed source must not abandon the remaining verified sources"
13381        );
13382        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13383
13384        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13385        assert_eq!(
13386            follow_up,
13387            FetchFollowUp::RequeuedForVerification,
13388            "exhausted sources must restore the reserved verification entry"
13389        );
13390        assert_eq!(q.pending_count(), 1);
13391        assert_eq!(
13392            q.retry_reserved_slot_count(),
13393            0,
13394            "the reservation converts back into the pending entry itself"
13395        );
13396    }
13397
13398    #[test]
13399    fn source_failure_without_retry_metadata_is_terminal() {
13400        const RETRY_AFTER: Duration = Duration::from_mins(1);
13401
13402        // Direct enqueue (no pending entry) models a fetch with no
13403        // verification retry reservation to restore.
13404        let mut q = ReplicationQueues::new();
13405        let key = test_key(0x1F);
13406        let source = test_peer(0x06);
13407        assert!(q.enqueue_fetch(key, key, vec![source]));
13408        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13409        q.start_dequeued_fetch(candidate, source);
13410
13411        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13412
13413        assert_eq!(follow_up, FetchFollowUp::Terminal);
13414        assert!(!q.contains_key(&key));
13415    }
13416
13417    #[test]
13418    fn already_held_key_leaves_the_pipeline_terminally() {
13419        const RETRY_AFTER: Duration = Duration::from_mins(1);
13420
13421        let mut q = ReplicationQueues::new();
13422        let key = test_key(0x4C);
13423        let source = test_peer(0x0B);
13424        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13425
13426        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13427
13428        assert_eq!(
13429            follow_up,
13430            FetchFollowUp::Terminal,
13431            "holding the key already discharges the duty, so the key must leave \
13432             the pipeline exactly as a completed fetch does — requeueing it \
13433             would re-verify a key that needs nothing"
13434        );
13435        assert!(!q.contains_key(&key));
13436        assert_eq!(
13437            q.retry_reserved_slot_count(),
13438            0,
13439            "the terminal path must release the retry-slot reservation, or the \
13440             owner's verification budget leaks"
13441        );
13442    }
13443
13444    #[test]
13445    fn local_write_failure_does_not_conscript_the_remaining_sources() {
13446        const RETRY_AFTER: Duration = Duration::from_mins(1);
13447
13448        let mut q = ReplicationQueues::new();
13449        let key = test_key(0x2A);
13450        let first = test_peer(0x07);
13451        let second = test_peer(0x08);
13452        let third = test_peer(0x09);
13453        drive_key_in_flight(&mut q, key, vec![first, second, third]);
13454
13455        let follow_up =
13456            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13457
13458        assert_eq!(
13459            follow_up,
13460            FetchFollowUp::RequeuedForVerification,
13461            "a local write failure must go straight back to verification: the two \
13462             untried sources would each re-upload the same chunk into the same \
13463             full disk, and neither of them did anything wrong"
13464        );
13465        assert_eq!(q.in_flight_count(), 0);
13466        assert_eq!(
13467            q.pending_count(),
13468            1,
13469            "the key must come back — capacity frees up, and a stranded key is \
13470             a replica this node silently stops owing"
13471        );
13472        assert_eq!(q.retry_reserved_slot_count(), 0);
13473    }
13474
13475    #[test]
13476    fn local_write_failure_without_retry_metadata_is_terminal() {
13477        const RETRY_AFTER: Duration = Duration::from_mins(1);
13478
13479        // No pending entry to restore, so the only way not to strand the key
13480        // in `in_flight_fetch` forever — which would also stall bootstrap
13481        // drain — is the terminal path.
13482        let mut q = ReplicationQueues::new();
13483        let key = test_key(0x3B);
13484        let source = test_peer(0x0A);
13485        assert!(q.enqueue_fetch(key, key, vec![source]));
13486        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13487        q.start_dequeued_fetch(candidate, source);
13488
13489        let follow_up =
13490            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13491
13492        assert_eq!(follow_up, FetchFollowUp::Terminal);
13493        assert!(!q.contains_key(&key));
13494        assert_eq!(q.retry_reserved_slot_count(), 0);
13495    }
13496}