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, ReplicationQueues};
95use crate::replication::types::{
96    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98    VerificationState,
99};
100use crate::storage::LmdbStorage;
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).map_or(true, |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_secs(3600))
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<LmdbStorage>,
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_secs(30 * 60);
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_secs(60);
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<LmdbStorage>,
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<LmdbStorage>,
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    /// Get a reference to the auditor's last-commitment-by-peer table.
1992    #[must_use]
1993    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1994        &self.last_commitment_by_peer
1995    }
1996
1997    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
1998    /// will be read by quorum / paid-list eligibility checks.
1999    #[must_use]
2000    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2001        &self.recent_provers
2002    }
2003
2004    /// Test-only: rebuild + rotate this node's storage commitment now over its
2005    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2006    /// just stored without waiting for the rotation cadence.
2007    ///
2008    /// # Errors
2009    ///
2010    /// Propagates any error from reading the local key set or building/signing
2011    /// the commitment.
2012    #[cfg(any(test, feature = "test-utils"))]
2013    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2014        rebuild_and_rotate_commitment(
2015            &self.storage,
2016            &self.identity,
2017            &self.commitment_state,
2018            &self.p2p_node,
2019            &self.config,
2020        )
2021        .await
2022    }
2023
2024    /// Test-only: directly seed this node's cached commitment for `peer`,
2025    /// simulating "we received `peer`'s gossiped commitment" without depending
2026    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2027    /// peer's commitment deterministically.
2028    #[cfg(any(feature = "test-utils", test))]
2029    pub async fn inject_peer_commitment_for_test(
2030        &self,
2031        peer: &PeerId,
2032        commitment: StorageCommitment,
2033    ) {
2034        let now = Instant::now();
2035        self.last_commitment_by_peer
2036            .write()
2037            .await
2038            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2039        self.ever_capable_peers.write().await.insert(*peer);
2040    }
2041
2042    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2043    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2044    /// window and clears any shared cooldown stamped by an earlier gossip
2045    /// launch. The locks follow the production gossip-audit lock order.
2046    #[cfg(any(test, feature = "test-utils"))]
2047    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2048        let now = Instant::now();
2049        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2050        let mut launched = self.audit_on_gossip_cooldown.write().await;
2051        lottery_attempts.insert(*peer, now);
2052        launched.remove(peer);
2053    }
2054
2055    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2056    /// commitment this node has cached for it (from gossip), over the live wire.
2057    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2058    /// in a real two-node setting without waiting for the gossip cadence.
2059    ///
2060    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2061    /// peer yet (gossip hasn't reached us). Gated to test builds.
2062    #[cfg(any(test, feature = "test-utils"))]
2063    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2064        let target = {
2065            let map = self.last_commitment_by_peer.read().await;
2066            map.get(peer)
2067                .and_then(PeerCommitmentRecord::last_commitment)
2068                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2069        };
2070        let Some((pin, key_count)) = target else {
2071            return audit::AuditTickResult::Idle;
2072        };
2073        let credit = storage_commitment_audit::AuditCredit {
2074            recent_provers: &self.recent_provers,
2075        };
2076        storage_commitment_audit::run_subtree_audit(
2077            &self.p2p_node,
2078            &self.config,
2079            peer,
2080            pin,
2081            key_count,
2082            Some(&credit),
2083        )
2084        .await
2085    }
2086
2087    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2088    /// tests assert what the live drainer decided for an injected
2089    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2090    #[cfg(any(test, feature = "test-utils"))]
2091    #[must_use]
2092    pub fn first_audit_stats(&self) -> FirstAuditStats {
2093        let o = &self.first_audit_observability;
2094        FirstAuditStats {
2095            received: o.received.load(Ordering::Relaxed),
2096            queued: o.queued.load(Ordering::Relaxed),
2097            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2098            launched: o.launched.load(Ordering::Relaxed),
2099            passed: o.passed.load(Ordering::Relaxed),
2100            timed_out: o.timed_out.load(Ordering::Relaxed),
2101            failed: o.failed.load(Ordering::Relaxed),
2102        }
2103    }
2104
2105    /// Test-only: run the possession check immediately for `key` against
2106    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2107    ///
2108    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2109    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2110    /// deterministically without waiting for the scheduled check.
2111    #[cfg(any(test, feature = "test-utils"))]
2112    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2113        possession::run_possession_check(
2114            key,
2115            peers,
2116            &self.p2p_node,
2117            &self.storage,
2118            &self.config,
2119            &self.sync_state,
2120            &self.audit_challenge_coordinator,
2121            &self.shutdown,
2122        )
2123        .await;
2124    }
2125
2126    /// Test-only: place `key` directly into the fetch queue as though a
2127    /// verification cycle had just promoted it, with `sources` as its
2128    /// verified holders. Returns whether the key was enqueued.
2129    ///
2130    /// Bypasses admission, verification, and the promotion-time
2131    /// responsibility pre-filter, modelling a promotion decision that has
2132    /// since gone stale (topology churn between promotion and download).
2133    /// The only guard left standing is the per-attempt recheck inside
2134    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2135    /// exercise.
2136    #[cfg(any(test, feature = "test-utils"))]
2137    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2138        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2139        self.queues
2140            .write()
2141            .await
2142            .enqueue_fetch(key, distance, sources)
2143    }
2144
2145    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2146    /// (pending verification, fetch queue, or in-flight fetch).
2147    #[cfg(any(test, feature = "test-utils"))]
2148    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2149        self.queues.read().await.contains_key(key)
2150    }
2151
2152    /// Start all background tasks.
2153    ///
2154    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2155    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2156    /// missed by the bootstrap-sync gate.
2157    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2158        if !self.task_handles.is_empty() {
2159            error!("ReplicationEngine::start() called while already running — ignoring");
2160            return;
2161        }
2162        info!("Starting replication engine");
2163
2164        self.start_message_handler();
2165        self.start_neighbor_sync_loop();
2166        self.start_self_lookup_loop();
2167        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2168        // chunks they SHOULD store (responsibility + prior hint).
2169        self.start_audit_loop();
2170        // Audit #1 (storage-commitment) is gossip-triggered in the message
2171        // handler when a peer's commitment is ingested, not on a periodic tick.
2172        self.start_commitment_rotation_loop();
2173        self.start_retention_persist_loop();
2174        self.start_fetch_worker();
2175        self.start_verification_worker();
2176        self.start_bootstrap_sync(dht_events);
2177        self.start_fresh_write_drainer();
2178        self.start_possession_check_scheduler();
2179        // ADR-0004: deterministic first audit of commitments that backed a
2180        // payment (surfaced by the verifier cross-check).
2181        self.start_first_audit_drainer();
2182        // V2-623: periodic cumulative per-variant traffic accounting.
2183        self.start_traffic_summary_loop();
2184        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2185        #[cfg(feature = "logging")]
2186        self.start_bootstrap_state_snapshot_loop();
2187        #[cfg(feature = "logging")]
2188        self.start_audit_responder_summary_loop();
2189
2190        info!(
2191            "Replication engine started with {} background tasks",
2192            self.task_handles.len()
2193        );
2194    }
2195
2196    /// Returns `true` if the node is still in the replication bootstrap phase.
2197    ///
2198    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2199    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2200    pub async fn is_bootstrapping(&self) -> bool {
2201        *self.is_bootstrapping.read().await
2202    }
2203
2204    /// Wait until the replication bootstrap phase completes.
2205    ///
2206    /// Returns immediately if bootstrap has already completed. Useful for
2207    /// readiness probes, health checks, and test harnesses that need the
2208    /// node to be fully operational before proceeding.
2209    ///
2210    /// Returns `true` if bootstrap completed within the timeout, `false`
2211    /// if the timeout elapsed first.
2212    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2213        // Register the notification future *before* checking the flag so that
2214        // a transition between the read and the await is not missed.
2215        let notified = self.bootstrap_complete_notify.notified();
2216        tokio::pin!(notified);
2217        notified.as_mut().enable();
2218
2219        if !*self.is_bootstrapping.read().await {
2220            return true;
2221        }
2222
2223        tokio::time::timeout(timeout, notified).await.is_ok()
2224    }
2225
2226    /// Cancel all background tasks and wait for them to terminate.
2227    ///
2228    /// This must be awaited before dropping the engine when the caller needs
2229    /// the `Arc<LmdbStorage>` references held by background tasks to be
2230    /// released (e.g. before reopening the same LMDB environment).
2231    ///
2232    /// When this returns, no engine-spawned task still holds
2233    /// `Arc<LmdbStorage>` or `Arc<PaidList>`, and no LMDB blocking operation
2234    /// (read or write, on either the chunk store or the paid-list
2235    /// environment) is still running.  Engine tasks race their work against
2236    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2237    /// LMDB transaction running detached, so this method additionally waits
2238    /// for both storage layers to go quiescent before returning.
2239    pub async fn shutdown(&mut self) {
2240        self.shutdown.cancel();
2241        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2242            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2243                Ok(Ok(())) => {}
2244                Ok(Err(e)) if e.is_cancelled() => {}
2245                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2246                Err(_) => {
2247                    warn!(
2248                        "Replication task {i} did not stop within {}s, aborting",
2249                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2250                    );
2251                    handle.abort();
2252                    // `abort` only requests cancellation. Await the handle so
2253                    // synchronous sections finish and the task drops every
2254                    // storage/P2P clone before we claim producer quiescence.
2255                    match handle.await {
2256                        Ok(()) => {}
2257                        Err(e) if e.is_cancelled() => {}
2258                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2259                    }
2260                }
2261            }
2262        }
2263
2264        // Close the responder worker pools. Detached tasks still queued for a
2265        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2266        // rather than waiting for a slot that will never free up — without
2267        // this, work admitted just before shutdown would queue behind the last
2268        // in-flight batch and hold the drain below open for its full duration.
2269        self.fresh_offer_worker_semaphore.close();
2270        self.paid_notify_worker_semaphore.close();
2271        self.fetch_responder_worker_semaphore.close();
2272        self.verification_responder_worker_semaphore.close();
2273        self.neighbor_sync_responder_worker_semaphore.close();
2274
2275        // All producers have stopped, so close and drain their detached work.
2276        // A started storage operation must run to completion: dropping an async
2277        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2278        // while an LMDB transaction still owns the environment.
2279        //
2280        // Deliberately unbounded: the LMDB contract requires every worker to
2281        // release its `Arc<LmdbStorage>` before the caller may reopen the
2282        // environment, and a timeout here could return with one still held.
2283        // What makes that safe is that every detached task is now guaranteed to
2284        // finish — the pools above are closed, stale work is shed at dequeue,
2285        // and the one genuinely unbounded await (payment verification) races
2286        // `self.shutdown` via `verify_payment_until_shutdown`.
2287        self.detached_task_tracker.close();
2288        self.detached_task_tracker.wait().await;
2289
2290        // Every producer is gone, but a select! racing the shutdown token may
2291        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2292        // (fetch `storage.put`, prune `storage.delete` /
2293        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2294        // detached blocking closure owns a cloned `Env`; wait for both
2295        // environments to go quiescent — bounded by one in-flight transaction
2296        // per op — so the caller may reopen them.
2297        self.storage.wait_idle().await;
2298        self.paid_list.wait_idle().await;
2299    }
2300
2301    /// Trigger an early neighbor sync round.
2302    ///
2303    /// Useful after topology changes (new nodes joining, network heal after
2304    /// partition) when the caller wants replication to converge faster than
2305    /// the regular 10-20 minute cadence.
2306    pub fn trigger_neighbor_sync(&self) {
2307        self.sync_trigger.notify_one();
2308    }
2309
2310    /// Execute fresh replication for a newly stored record, then schedule the
2311    /// delayed possession check for the responsible close-group peers
2312    /// (ADR-0003). The production PUT path schedules via the fresh-write
2313    /// drainer; this direct entry point schedules here so callers (and tests)
2314    /// that drive replication directly still get the possession check.
2315    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2316        let peers = fresh::replicate_fresh(
2317            key,
2318            data,
2319            proof_of_payment,
2320            &self.p2p_node,
2321            &self.paid_list,
2322            &self.config,
2323            &self.send_semaphore,
2324        )
2325        .await;
2326        if !peers.is_empty() {
2327            let _ = self
2328                .possession_check_tx
2329                .send(possession::PossessionCheckEvent { key: *key, peers });
2330        }
2331    }
2332
2333    // =======================================================================
2334    // Background task launchers
2335    // =======================================================================
2336
2337    /// Spawn a task that drains the fresh-write channel and triggers
2338    /// replication for each newly-stored chunk.
2339    fn start_fresh_write_drainer(&mut self) {
2340        let Some(mut rx) = self.fresh_write_rx.take() else {
2341            return;
2342        };
2343        let p2p = Arc::clone(&self.p2p_node);
2344        let paid_list = Arc::clone(&self.paid_list);
2345        let config = Arc::clone(&self.config);
2346        let send_semaphore = Arc::clone(&self.send_semaphore);
2347        let possession_tx = self.possession_check_tx.clone();
2348        let shutdown = self.shutdown.clone();
2349
2350        let handle = tokio::spawn(async move {
2351            loop {
2352                tokio::select! {
2353                    () = shutdown.cancelled() => break,
2354                    event = rx.recv() => {
2355                        let Some(event) = event else { break };
2356                        let peers = fresh::replicate_fresh(
2357                            &event.key,
2358                            &event.data,
2359                            &event.payment_proof,
2360                            &p2p,
2361                            &paid_list,
2362                            &config,
2363                            &send_semaphore,
2364                        )
2365                        .await;
2366                        // Schedule the delayed possession check (ADR-0003) for
2367                        // the responsible close-group peers. A closed receiver
2368                        // (engine shutting down) is ignored.
2369                        if !peers.is_empty() {
2370                            let _ = possession_tx.send(possession::PossessionCheckEvent {
2371                                key: event.key,
2372                                peers,
2373                            });
2374                        }
2375                    }
2376                }
2377            }
2378            debug!("Fresh-write drainer shut down");
2379        });
2380        self.task_handles.push(handle);
2381    }
2382
2383    /// Spawn the possession-check scheduler (ADR-0003).
2384    ///
2385    /// Drains scheduled possession-check events and, for each, waits a
2386    /// randomised 5-15 minute settle delay before probing every responsible
2387    /// peer for actual possession. A peer that fails to prove possession or does
2388    /// not answer is penalised at `AuditChallenge` severity.
2389    fn start_possession_check_scheduler(&mut self) {
2390        let Some(mut rx) = self.possession_check_rx.take() else {
2391            return;
2392        };
2393        let p2p = Arc::clone(&self.p2p_node);
2394        let storage = Arc::clone(&self.storage);
2395        let config = Arc::clone(&self.config);
2396        let sync_state = Arc::clone(&self.sync_state);
2397        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2398        let shutdown = self.shutdown.clone();
2399        let detached_task_tracker = self.detached_task_tracker.clone();
2400
2401        let handle = tokio::spawn(async move {
2402            loop {
2403                tokio::select! {
2404                    () = shutdown.cancelled() => break,
2405                    event = rx.recv() => {
2406                        let Some(event) = event else { break };
2407                        // Spawn a per-chunk delayed check so the drain loop
2408                        // keeps pace with the write rate. Each check sleeps the
2409                        // randomised settle delay, then probes every peer.
2410                        let p2p = Arc::clone(&p2p);
2411                        let storage = Arc::clone(&storage);
2412                        let config = Arc::clone(&config);
2413                        let sync_state = Arc::clone(&sync_state);
2414                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2415                        let shutdown = shutdown.clone();
2416                        let delay_min = config.possession_check_delay_min;
2417                        let delay_max = config.possession_check_delay_max;
2418                        detached_task_tracker.spawn(async move {
2419                            let delay = possession::random_delay(delay_min, delay_max);
2420                            // Race shutdown against the whole settle-then-probe
2421                            // sequence, not just the sleep. Once a check starts it
2422                            // may park on the per-target audit coordinator, which
2423                            // has no deadline of its own: with the settle delay
2424                            // inside the branch BODY the select is already resolved,
2425                            // so those waiters would drain only at the probe timeout
2426                            // (roughly `queued / per-target-limit` probes deep) while
2427                            // `detached_task_tracker.wait()` — deliberately unbounded
2428                            // for the LMDB contract — held shutdown open.
2429                            //
2430                            // Dropping this future mid-probe is safe and is the same
2431                            // shape the neighbor-sync round uses: a parked coordinator
2432                            // acquire releases its counted reference via
2433                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2434                            // covered by the storage-quiescence wait in `shutdown`.
2435                            tokio::select! {
2436                                () = shutdown.cancelled() => {}
2437                                () = async {
2438                                    tokio::time::sleep(delay).await;
2439                                    possession::run_possession_check(
2440                                        event.key,
2441                                        event.peers,
2442                                        &p2p,
2443                                        &storage,
2444                                        &config,
2445                                        &sync_state,
2446                                        &audit_challenge_coordinator,
2447                                        &shutdown,
2448                                    )
2449                                    .await;
2450                                } => {}
2451                            }
2452                        });
2453                    }
2454                }
2455            }
2456            debug!("Possession-check scheduler shut down");
2457        });
2458        self.task_handles.push(handle);
2459    }
2460
2461    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2462    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2463    /// as the gossip path, under the same per-peer cooldown and concurrency
2464    /// caps, but with the probability lottery BYPASSED (the lottery governs
2465    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2466    /// deterministic first audit; a peer minting fresh pins faster than the
2467    /// cooldown forfeits the older ones' coverage, never the newest's (the
2468    /// channel surfaces newest pins as they are monetized).
2469    #[allow(clippy::too_many_lines)]
2470    fn start_first_audit_drainer(&mut self) {
2471        let Some(mut rx) = self.monetized_pin_rx.take() else {
2472            return;
2473        };
2474        let gossip_audit = GossipAuditTrigger {
2475            p2p_node: Arc::clone(&self.p2p_node),
2476            config: Arc::clone(&self.config),
2477            recent_provers: Arc::clone(&self.recent_provers),
2478            sync_state: Arc::clone(&self.sync_state),
2479            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2480            detached_task_tracker: self.detached_task_tracker.clone(),
2481            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2482        };
2483        let shutdown = self.shutdown.clone();
2484        let observability = Arc::clone(&self.first_audit_observability);
2485        let self_peer = *self.p2p_node.peer_id();
2486
2487        let handle = tokio::spawn(async move {
2488            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2489            // scheduler. Payments only NOMINATE pins; the token bucket launches
2490            // them at a fixed per-node rate, and durable suppression is stamped
2491            // only at PROMOTION (after an authoritative post-jitter answerability
2492            // + cooldown check), so a cancelled reservation leaves nothing behind.
2493            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2494            // Periodic retry tick so budget/cooldown-deferred pins get retried
2495            // even when no new nomination arrives. `Skip` collapses a backlog.
2496            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2497            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2498            let mut last_summary = Instant::now();
2499            loop {
2500                // The reservation's jitter deadline is a wake source: if a
2501                // reservation is outstanding, sleep until it is due; otherwise
2502                // a far-future deadline effectively disables that arm and only
2503                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2504                // newly reserved (earlier) deadline is honoured next turn.
2505                let promotion_due = scheduler
2506                    .reserved_ready_at()
2507                    .unwrap_or_else(first_audit_far_future);
2508                tokio::select! {
2509                    () = shutdown.cancelled() => break,
2510                    event = rx.recv() => match event {
2511                        Some(e) => {
2512                            observability.received.fetch_add(1, Ordering::Relaxed);
2513                            // Pre-overflow reservation opportunity: before an
2514                            // arrival may displace a DIFFERENT peer, let the
2515                            // queue launch — a successful reservation frees the
2516                            // slot without eviction. One reservation can be
2517                            // outstanding at a time, so this consumes at most
2518                            // one slot per jitter window; arrivals beyond it
2519                            // fall through to random displacement (ADR-0004
2520                            // Amendment 4).
2521                            if scheduler.would_displace(&e) {
2522                                open_first_audit_reservation(
2523                                    &mut scheduler,
2524                                    &gossip_audit.cooldown,
2525                                    &observability,
2526                                )
2527                                .await;
2528                            }
2529                            scheduler.enqueue(e, &observability);
2530                            // Drain a bounded burst so a flood cannot starve the
2531                            // launch phase.
2532                            let mut drained = 1usize;
2533                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2534                                match rx.try_recv() {
2535                                    Ok(e) => {
2536                                        observability.received.fetch_add(1, Ordering::Relaxed);
2537                                        if scheduler.would_displace(&e) {
2538                                            open_first_audit_reservation(
2539                                                &mut scheduler,
2540                                                &gossip_audit.cooldown,
2541                                                &observability,
2542                                            )
2543                                            .await;
2544                                        }
2545                                        scheduler.enqueue(e, &observability);
2546                                        drained += 1;
2547                                    }
2548                                    Err(_) => break,
2549                                }
2550                            }
2551                        }
2552                        None => break,
2553                    },
2554                    _ = tick.tick() => {}
2555                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2556                }
2557
2558                // 1) Promote a due reservation. Resolved after EVERY wake (not
2559                //    only when the timer arm wins) so a continuously-ready `rx`
2560                //    cannot indefinitely delay a due promotion. The authoritative
2561                //    answerability + cooldown check-and-stamp happens here under
2562                //    the shared cooldown write lock, immediately before the send.
2563                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2564                    let promoted = {
2565                        let mut cooldown = gossip_audit.cooldown.write().await;
2566                        scheduler.resolve(
2567                            reservation,
2568                            SystemTime::now(),
2569                            Instant::now(),
2570                            &mut cooldown,
2571                            &observability,
2572                        )
2573                    };
2574                    if let Some((event, inflight_slot)) = promoted {
2575                        debug!(
2576                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2577                            event.peer, hex::encode(event.pin), event.key_count,
2578                            observability.inflight.load(Ordering::Relaxed)
2579                        );
2580                        let trigger = gossip_audit.clone();
2581                        let audit_observability = Arc::clone(&observability);
2582                        // Track the launch so `shutdown()`'s detached drain
2583                        // covers it. This task outlives the drainer loop that
2584                        // spawned it — the loop breaks on the shutdown token
2585                        // while the audit is still awaiting its response — so a
2586                        // bare spawn would let an in-flight subtree audit keep
2587                        // running, and keep its `Arc<P2PNode>`, past the point
2588                        // `shutdown()` claims every engine task has stopped.
2589                        let tracker = trigger.detached_task_tracker.clone();
2590                        tracker.spawn(async move {
2591                            // The jitter already elapsed as the reservation's
2592                            // timer; the slot is held for the audit's duration
2593                            // and released on drop (panic-safe).
2594                            let inflight_slot = inflight_slot;
2595                            let started = Instant::now();
2596                            let credit = storage_commitment_audit::AuditCredit {
2597                                recent_provers: &trigger.recent_provers,
2598                            };
2599                            let result = storage_commitment_audit::run_subtree_audit(
2600                                &trigger.p2p_node,
2601                                &trigger.config,
2602                                &event.peer,
2603                                event.pin,
2604                                event.key_count,
2605                                Some(&credit),
2606                            )
2607                            .await;
2608                            let outcome = first_audit_terminal_outcome(&result);
2609                            match outcome {
2610                                FirstAuditTerminalOutcome::Passed => {
2611                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2612                                }
2613                                FirstAuditTerminalOutcome::Timeout => {
2614                                    audit_observability
2615                                        .timed_out
2616                                        .fetch_add(1, Ordering::Relaxed);
2617                                }
2618                                FirstAuditTerminalOutcome::Failed => {
2619                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2620                                }
2621                                FirstAuditTerminalOutcome::BootstrapClaim => {
2622                                    audit_observability
2623                                        .bootstrap_claims
2624                                        .fetch_add(1, Ordering::Relaxed);
2625                                }
2626                                FirstAuditTerminalOutcome::Idle => {
2627                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2628                                }
2629                                FirstAuditTerminalOutcome::InsufficientKeys => {
2630                                    audit_observability
2631                                        .insufficient_keys
2632                                        .fetch_add(1, Ordering::Relaxed);
2633                                }
2634                            }
2635                            drop(inflight_slot);
2636                            debug!(
2637                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2638                                outcome.as_str(),
2639                                event.peer, hex::encode(event.pin), event.key_count,
2640                                started.elapsed().as_millis(),
2641                                audit_observability.inflight.load(Ordering::Relaxed)
2642                            );
2643                            handle_subtree_audit_result(
2644                                &result,
2645                                &trigger.p2p_node,
2646                                &trigger.sync_state,
2647                                &trigger.recent_provers,
2648                                &trigger.config,
2649                            )
2650                            .await;
2651                        });
2652                    }
2653                }
2654
2655                // 2) Open the single reservation from the pending queue if none
2656                //    is outstanding (read-only cooldown snapshot; the
2657                //    authoritative stamp is at promotion). Serializing
2658                //    reservations preserves per-launch lane alternation and keeps
2659                //    at most one jitter timer live.
2660                open_first_audit_reservation(
2661                    &mut scheduler,
2662                    &gossip_audit.cooldown,
2663                    &observability,
2664                )
2665                .await;
2666
2667                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2668                    // Token-independent hygiene: collect entries that aged past
2669                    // the answerability horizon while the budget gate kept the
2670                    // reserve scan from running, so the summary below reports
2671                    // only live work.
2672                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2673                    if swept > 0 {
2674                        debug!(
2675                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2676                            scheduler.pending_len()
2677                        );
2678                    }
2679                    info!(
2680                        "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={}",
2681                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2682                        observability.received.load(Ordering::Relaxed),
2683                        observability.queued.load(Ordering::Relaxed),
2684                        observability.coalesced.load(Ordering::Relaxed),
2685                        observability.suppressed_lower.load(Ordering::Relaxed),
2686                        observability.duplicates.load(Ordering::Relaxed),
2687                        observability.capacity_evicted.load(Ordering::Relaxed),
2688                        observability.self_target_skipped.load(Ordering::Relaxed),
2689                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2690                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2691                        observability.window_deduped.load(Ordering::Relaxed),
2692                        observability.launched.load(Ordering::Relaxed),
2693                        observability.passed.load(Ordering::Relaxed),
2694                        observability.timed_out.load(Ordering::Relaxed),
2695                        observability.failed.load(Ordering::Relaxed),
2696                        observability.bootstrap_claims.load(Ordering::Relaxed),
2697                        observability.idle.load(Ordering::Relaxed),
2698                        observability.insufficient_keys.load(Ordering::Relaxed),
2699                        observability.outside_answerability_window.load(Ordering::Relaxed),
2700                        scheduler.pending_len(),
2701                        FIRST_AUDIT_PENDING_CAP,
2702                        u8::from(scheduler.has_reservation()),
2703                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2704                        observability.inflight.load(Ordering::Relaxed),
2705                        scheduler.tokens(),
2706                    );
2707                    last_summary = Instant::now();
2708                }
2709            }
2710            debug!("First-audit drainer shut down");
2711        });
2712        self.task_handles.push(handle);
2713    }
2714
2715    #[allow(clippy::too_many_lines)]
2716    fn start_message_handler(&mut self) {
2717        let mut p2p_events = self.p2p_node.subscribe_events();
2718        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2719        let p2p = Arc::clone(&self.p2p_node);
2720        let storage = Arc::clone(&self.storage);
2721        let paid_list = Arc::clone(&self.paid_list);
2722        let payment_verifier = Arc::clone(&self.payment_verifier);
2723        let queues = Arc::clone(&self.queues);
2724        let config = Arc::clone(&self.config);
2725        let shutdown = self.shutdown.clone();
2726        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2727        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2728        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2729        let sync_history = Arc::clone(&self.sync_history);
2730        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2731        let repair_proofs = Arc::clone(&self.repair_proofs);
2732        let sync_trigger = Arc::clone(&self.sync_trigger);
2733        let my_commitment_state = Arc::clone(&self.commitment_state);
2734        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2735        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2736        let recent_provers = Arc::clone(&self.recent_provers);
2737        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2738        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2739        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2740        let sync_state = Arc::clone(&self.sync_state);
2741        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2742        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2743        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2744        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2745        let fetch_responder_admission_semaphore =
2746            Arc::clone(&self.fetch_responder_admission_semaphore);
2747        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2748        let verification_responder_worker_semaphore =
2749            Arc::clone(&self.verification_responder_worker_semaphore);
2750        let verification_responder_admission_semaphore =
2751            Arc::clone(&self.verification_responder_admission_semaphore);
2752        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2753        let neighbor_sync_responder_worker_semaphore =
2754            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2755        let neighbor_sync_responder_admission_semaphore =
2756            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2757        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2758        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2759        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2760        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2761        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2762        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2763        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2764        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2765        let detached_task_tracker = self.detached_task_tracker.clone();
2766        let subtree_round1 = self.subtree_round1.clone();
2767
2768        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2769        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2770        let gossip_audit = GossipAuditTrigger {
2771            p2p_node: Arc::clone(&p2p),
2772            config: Arc::clone(&config),
2773            recent_provers: Arc::clone(&recent_provers),
2774            sync_state: Arc::clone(&sync_state),
2775            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2776            detached_task_tracker: detached_task_tracker.clone(),
2777            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2778        };
2779
2780        let handler_context = ReplicationMessageHandlerContext {
2781            p2p_node: Arc::clone(&p2p),
2782            storage,
2783            paid_list,
2784            payment_verifier,
2785            queues,
2786            config: Arc::clone(&config),
2787            is_bootstrapping,
2788            bootstrap_state,
2789            sync_history,
2790            sync_cycle_epoch,
2791            repair_proofs: Arc::clone(&repair_proofs),
2792            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2793            ever_capable_peers,
2794            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2795            my_commitment_state,
2796            gossip_audit,
2797            audit_responder_semaphore,
2798            audit_responder_inflight,
2799            audit_responder_metrics,
2800            subtree_round1,
2801            fetch_responder_worker_semaphore,
2802            fetch_responder_admission_semaphore,
2803            fetch_responder_inflight,
2804            verification_responder_worker_semaphore,
2805            verification_responder_admission_semaphore,
2806            verification_responder_inflight,
2807            neighbor_sync_responder_worker_semaphore,
2808            neighbor_sync_responder_admission_semaphore,
2809            neighbor_sync_responder_inflight,
2810            fresh_offer_worker_semaphore,
2811            fresh_offer_admission_semaphore,
2812            fresh_offer_responder_inflight,
2813            fresh_offer_in_flight,
2814            paid_notify_worker_semaphore,
2815            paid_notify_admission_semaphore,
2816            paid_notify_responder_inflight,
2817            shutdown: shutdown.clone(),
2818            detached_task_tracker,
2819        };
2820
2821        let (replication_tx, mut replication_rx) =
2822            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2823        let serial_context = handler_context.clone();
2824        let serial_shutdown = shutdown.clone();
2825        let serial_handle = tokio::spawn(async move {
2826            loop {
2827                tokio::select! {
2828                    () = serial_shutdown.cancelled() => break,
2829                    inbound = replication_rx.recv() => {
2830                        let Some(inbound) = inbound else { break };
2831                        let source = inbound.source;
2832                        match handle_replication_message(
2833                            &source,
2834                            inbound.msg,
2835                            &serial_context,
2836                            inbound.received_at,
2837                            inbound.rr_message_id.as_deref(),
2838                        )
2839                        .await
2840                        {
2841                            Ok(()) => {}
2842                            Err(e) => {
2843                                debug!("Replication message from {source} error: {e}");
2844                            }
2845                        }
2846                    }
2847                }
2848            }
2849            debug!("Replication non-audit serial handler shut down");
2850        });
2851        self.task_handles.push(serial_handle);
2852
2853        let handle = tokio::spawn(async move {
2854            loop {
2855                tokio::select! {
2856                    () = shutdown.cancelled() => break,
2857                    event = p2p_events.recv() => {
2858                        let event = match event {
2859                            Ok(event) => event,
2860                            Err(error) => match handle_replication_event_recv_error(&error) {
2861                                ControlFlow::Continue(()) => continue,
2862                                ControlFlow::Break(()) => break,
2863                            },
2864                        };
2865                        let Some((source, payload, inbound_protocol, rr_message_id)) =
2866                            replication_payload_from_event(event)
2867                        else {
2868                            continue;
2869                        };
2870                        let received_at = Instant::now();
2871                        let msg = match ReplicationMessage::decode(&payload) {
2872                            Ok(msg) => msg,
2873                            Err(e) => {
2874                                debug!("Replication message from {source} decode error: {e}");
2875                                continue;
2876                            }
2877                        };
2878                        if !body_matches_protocol(&msg.body, inbound_protocol) {
2879                            debug!(
2880                                "Dropping replication body (variant {}) on protocol \
2881                                 {inbound_protocol}: wrong id for its family \
2882                                 (cross-version or misrouted)",
2883                                msg.body.variant_index()
2884                            );
2885                            continue;
2886                        }
2887                        if let Some(class) = audit_responder_class(&msg.body) {
2888                            handler_context
2889                                .audit_responder_metrics
2890                                .record_received(source, class);
2891                        }
2892                        let inbound = InboundReplicationMessage {
2893                            source,
2894                            msg,
2895                            rr_message_id,
2896                            received_at,
2897                        };
2898                        if matches!(
2899                            inbound.msg.body,
2900                            ReplicationMessageBody::AuditChallenge(_)
2901                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
2902                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
2903                        ) {
2904                            let source = inbound.source;
2905                            match handle_replication_message(
2906                                &source,
2907                                inbound.msg,
2908                                &handler_context,
2909                                inbound.received_at,
2910                                inbound.rr_message_id.as_deref(),
2911                            )
2912                            .await
2913                            {
2914                                Ok(()) => {}
2915                                Err(e) => {
2916                                    debug!("Replication message from {source} error: {e}");
2917                                }
2918                            }
2919                            continue;
2920                        }
2921                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2922                            if dropped.audit_responder_class.is_some() {
2923                                handler_context
2924                                    .audit_responder_metrics
2925                                    .record_serial_queue_drop(dropped.source);
2926                            }
2927                            // Every serial-lane class has protocol recovery: syncs rerun,
2928                            // fetches retry, verification re-asks, and a dropped fresh
2929                            // offer is refilled by neighbor sync (the possession check
2930                            // penalises the absence but never re-offers). Responses are
2931                            // covered by their requester's deadline/retry path. Never run
2932                            // a bulk handler here: event receipt must remain non-blocking.
2933                            warn!(
2934                                message_class = dropped.message_class,
2935                                source = %dropped.source,
2936                                queue_depth = dropped.queue_depth,
2937                                reason = dropped.reason.as_str(),
2938                                "Replication serial-queue message dropped"
2939                            );
2940                        }
2941                    }
2942                    // Gap 4: Topology churn handling (Section 13).
2943                    //
2944                    // The DHT routing table emits KClosestPeersChanged when the
2945                    // K-closest peer set actually changes, which is the precise
2946                    // signal for triggering neighbor sync. This replaces the
2947                    // previous approach of checking every PeerConnected /
2948                    // PeerDisconnected event against the close group.
2949                    dht_event = dht_events.recv() => {
2950                        let dht_event = match dht_event {
2951                            Ok(event) => event,
2952                            Err(RecvError::Lagged(missed)) => {
2953                                // Under heavy churn the broadcast buffer can overflow
2954                                // and drop routing-table events — the moment
2955                                // convergence matters most. A dropped
2956                                // KClosestPeersChanged means its entrants were never
2957                                // queued and its departures were never pruned, so
2958                                // draining priority_order cannot recover either.
2959                                // Resync from ground truth instead: snapshot the
2960                                // current close-peer set, prune pending peers that
2961                                // left it during the lost window (retain_sync_peers,
2962                                // as the normal topology-change path does), and queue
2963                                // every member. Dedup (queue_priority_peers) and
2964                                // per-peer cooldown (select_next_sync_peer) drop peers
2965                                // already queued or recently synced, so only genuine
2966                                // entrants surface.
2967                                warn!(
2968                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
2969                                );
2970                                let self_id = *p2p.peer_id();
2971                                let neighbors = neighbor_sync::snapshot_close_neighbors(
2972                                    &p2p,
2973                                    &self_id,
2974                                    config.neighbor_sync_scope,
2975                                )
2976                                .await;
2977                                let neighbor_set =
2978                                    neighbors.iter().copied().collect::<HashSet<_>>();
2979                                let (requeued, sync_removals) = {
2980                                    let mut state = sync_state.write().await;
2981                                    let sync_removals =
2982                                        state.retain_sync_peers(&neighbor_set);
2983                                    let requeued = state.queue_priority_peers(neighbors);
2984                                    (requeued, sync_removals)
2985                                };
2986                                if sync_removals > 0 {
2987                                    debug!(
2988                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
2989                                    );
2990                                }
2991                                if requeued > 0 {
2992                                    debug!(
2993                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
2994                                    );
2995                                    sync_trigger.notify_one();
2996                                }
2997                                continue;
2998                            }
2999                            Err(RecvError::Closed) => {
3000                                // A closed broadcast channel never yields again;
3001                                // continuing would spin the select! loop forever.
3002                                warn!(
3003                                    "DHT event stream closed on replication branch; stopping message handler"
3004                                );
3005                                break;
3006                            }
3007                        };
3008                        match dht_event {
3009                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3010                                let old_peers = old
3011                                    .iter()
3012                                    .take(config.neighbor_sync_scope)
3013                                    .copied()
3014                                    .collect::<HashSet<_>>();
3015                                let new_scoped = new
3016                                    .iter()
3017                                    .take(config.neighbor_sync_scope)
3018                                    .copied()
3019                                    .collect::<Vec<_>>();
3020                                let new_peers =
3021                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3022                                let entrants = new_scoped
3023                                    .iter()
3024                                    .copied()
3025                                    .filter(|peer| !old_peers.contains(peer))
3026                                    .collect::<Vec<_>>();
3027                                let entrant_count = entrants.len();
3028                                let (priority_insertions, sync_removals) = {
3029                                    let mut state = sync_state.write().await;
3030                                    let sync_removals = state.retain_sync_peers(&new_peers);
3031                                    let priority_insertions = state.queue_priority_peers(entrants);
3032                                    (priority_insertions, sync_removals)
3033                                };
3034                                if priority_insertions > 0 {
3035                                    debug!(
3036                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3037                                    );
3038                                } else {
3039                                    debug!(
3040                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3041                                    );
3042                                }
3043                                sync_trigger.notify_one();
3044                            }
3045                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3046                                sync_state.write().await.remove_peer(&peer_id);
3047                                repair_proofs.write().await.remove_peer(&peer_id);
3048                                update_bootstrap_after_peer_removed(
3049                                    &peer_id,
3050                                    &handler_context.bootstrap_state,
3051                                    &handler_context.queues,
3052                                    &handler_context.is_bootstrapping,
3053                                    &bootstrap_complete_notify,
3054                                )
3055                                .await;
3056                                // v12: drop the commitment bytes and the
3057                                // recent-prover credit so a churn / sybil
3058                                // attacker cannot leave behind one
3059                                // StorageCommitment per identity in
3060                                // `last_commitment_by_peer`. Also drop the
3061                                // sig-verify rate-limit timestamp.
3062                                last_commitment_by_peer.write().await.remove(&peer_id);
3063                                recent_provers.write().await.forget_peer(&peer_id);
3064                                sig_verify_attempts.write().await.remove(&peer_id);
3065                                // Same for the gossip-audit cooldown (ADR-0002)
3066                                // and the lottery-attempt window.
3067                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3068                                gossip_lottery_attempts.write().await.remove(&peer_id);
3069                                // The sticky `commitment_capable` flag is
3070                                // preserved orthogonally via
3071                                // `ever_capable_peers` — even after this
3072                                // removal, a re-joining peer continues to
3073                                // be treated as v12-capable rather than
3074                                // legacy (§3 shield).
3075                            }
3076                            _ => {}
3077                        }
3078                    }
3079                }
3080            }
3081            debug!("Replication message handler shut down");
3082        });
3083        self.task_handles.push(handle);
3084    }
3085
3086    fn start_neighbor_sync_loop(&mut self) {
3087        let p2p = Arc::clone(&self.p2p_node);
3088        let storage = Arc::clone(&self.storage);
3089        let paid_list = Arc::clone(&self.paid_list);
3090        let queues = Arc::clone(&self.queues);
3091        let config = Arc::clone(&self.config);
3092        let shutdown = self.shutdown.clone();
3093        let sync_state = Arc::clone(&self.sync_state);
3094        let sync_history = Arc::clone(&self.sync_history);
3095        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3096        let repair_proofs = Arc::clone(&self.repair_proofs);
3097        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3098        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3099        let sync_trigger = Arc::clone(&self.sync_trigger);
3100        let commitment_state = Arc::clone(&self.commitment_state);
3101        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3102        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3103        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3104        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3105        let detached_task_tracker = self.detached_task_tracker.clone();
3106        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3107        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3108        // here too so a peer that only ever answers — never initiates sync —
3109        // is still audited; otherwise it could fully evade auditing.
3110        let gossip_audit = GossipAuditTrigger {
3111            p2p_node: Arc::clone(&p2p),
3112            config: Arc::clone(&config),
3113            recent_provers: Arc::clone(&self.recent_provers),
3114            sync_state: Arc::clone(&sync_state),
3115            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3116            detached_task_tracker,
3117            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3118        };
3119
3120        let handle = tokio::spawn(async move {
3121            loop {
3122                // Park for the periodic tick or an explicit trigger ONLY when no
3123                // priority (topology-change) peers are queued. `sync_trigger` is a
3124                // coalescing `Notify`, so a churn burst that queues many entrants
3125                // produces a single wakeup; parking after draining one batch would
3126                // leave the rest waiting up to a full periodic tick. `priority_order`
3127                // is the durable record of pending work, so drain it back-to-back —
3128                // each round removes the peers it selects (`select_next_sync_peer`),
3129                // so the drain terminates once the queue empties.
3130                if !sync_state.read().await.has_priority_peers() {
3131                    let interval = config.random_neighbor_sync_interval();
3132                    tokio::select! {
3133                        () = shutdown.cancelled() => break,
3134                        () = tokio::time::sleep(interval) => {}
3135                        () = sync_trigger.notified() => {
3136                            debug!("Neighbor sync triggered by topology change");
3137                        }
3138                    }
3139                }
3140                // Wrap the sync round in a select so shutdown cancels
3141                // in-progress network operations rather than waiting for
3142                // the full round to complete.
3143                tokio::select! {
3144                    () = shutdown.cancelled() => break,
3145                    () = run_neighbor_sync_round(
3146                        &p2p,
3147                        &storage,
3148                        &paid_list,
3149                        &queues,
3150                        &config,
3151                        &sync_state,
3152                        &sync_history,
3153                        &sync_cycle_epoch,
3154                        &repair_proofs,
3155                        &is_bootstrapping,
3156                        &bootstrap_state,
3157                        &commitment_state,
3158                        &last_commitment_by_peer,
3159                        &ever_capable_peers,
3160                        &sig_verify_attempts,
3161                        &audit_challenge_coordinator,
3162                        &gossip_audit,
3163                    ) => {}
3164                }
3165            }
3166            debug!("Neighbor sync loop shut down");
3167        });
3168        self.task_handles.push(handle);
3169    }
3170
3171    fn start_self_lookup_loop(&mut self) {
3172        let p2p = Arc::clone(&self.p2p_node);
3173        let config = Arc::clone(&self.config);
3174        let shutdown = self.shutdown.clone();
3175
3176        let handle = tokio::spawn(async move {
3177            loop {
3178                let interval = config.random_self_lookup_interval();
3179                tokio::select! {
3180                    () = shutdown.cancelled() => break,
3181                    () = tokio::time::sleep(interval) => {
3182                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3183                            debug!("Self-lookup failed: {e}");
3184                        }
3185                    }
3186                }
3187            }
3188            debug!("Self-lookup loop shut down");
3189        });
3190        self.task_handles.push(handle);
3191    }
3192
3193    /// Periodic responsible-chunk audit loop (audit #2): every
3194    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3195    /// eligible close peer for the chunks it *should* be storing (by
3196    /// responsibility and prior repair hint), independent of the gossip-triggered
3197    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3198    /// immediately and periodically thereafter.
3199    fn start_audit_loop(&mut self) {
3200        let p2p = Arc::clone(&self.p2p_node);
3201        let storage = Arc::clone(&self.storage);
3202        let config = Arc::clone(&self.config);
3203        let shutdown = self.shutdown.clone();
3204        let sync_history = Arc::clone(&self.sync_history);
3205        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3206        let repair_proofs = Arc::clone(&self.repair_proofs);
3207        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3208        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3209        let sync_state = Arc::clone(&self.sync_state);
3210        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3211
3212        let handle = tokio::spawn(async move {
3213            // Invariant 19: wait for bootstrap to drain before starting audits.
3214            loop {
3215                tokio::select! {
3216                    () = shutdown.cancelled() => return,
3217                    () = tokio::time::sleep(
3218                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3219                    ) => {
3220                        if bootstrap_state.read().await.is_drained() {
3221                            break;
3222                        }
3223                    }
3224                }
3225            }
3226
3227            // Run one audit tick immediately after bootstrap drain.
3228            {
3229                let bootstrapping = *is_bootstrapping.read().await;
3230                let result = {
3231                    let history = sync_history.read().await;
3232                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3233                    audit::audit_tick_with_repair_proofs(
3234                        &p2p,
3235                        &storage,
3236                        &config,
3237                        &history,
3238                        &repair_proofs,
3239                        &audit_challenge_coordinator,
3240                        current_sync_epoch,
3241                        bootstrapping,
3242                    )
3243                    .await
3244                };
3245                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3246            }
3247
3248            // Then run periodically.
3249            loop {
3250                let interval = config.random_audit_tick_interval();
3251                tokio::select! {
3252                    () = shutdown.cancelled() => break,
3253                    () = tokio::time::sleep(interval) => {
3254                        let bootstrapping = *is_bootstrapping.read().await;
3255                        let result = {
3256                            let history = sync_history.read().await;
3257                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3258                            audit::audit_tick_with_repair_proofs(
3259                                &p2p,
3260                                &storage,
3261                                &config,
3262                                &history,
3263                                &repair_proofs,
3264                                &audit_challenge_coordinator,
3265                                current_sync_epoch,
3266                                bootstrapping,
3267                            )
3268                            .await
3269                        };
3270                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3271                    }
3272                }
3273            }
3274            debug!("Audit loop shut down");
3275        });
3276        self.task_handles.push(handle);
3277    }
3278
3279    /// Periodically rebuild + sign + rotate the responder's storage
3280    /// commitment.
3281    ///
3282    /// Phase 3 of the v12 storage-bound audit. Once per
3283    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3284    /// current LMDB key set, builds a Merkle tree (for content-addressed
3285    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3286    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3287    /// into `commitment_state`. Old `previous` slot is dropped by the
3288    /// rotate (per `ResponderCommitmentState::rotate`).
3289    ///
3290    /// Skips if the key set is empty (no commitment to make) — the
3291    /// auditor side falls back to the legacy plain-digest path for
3292    /// peers that have never gossiped a commitment.
3293    fn start_commitment_rotation_loop(&mut self) {
3294        let storage = Arc::clone(&self.storage);
3295        let identity = Arc::clone(&self.identity);
3296        let commitment_state = Arc::clone(&self.commitment_state);
3297        let shutdown = self.shutdown.clone();
3298        let p2p = Arc::clone(&self.p2p_node);
3299        let config = Arc::clone(&self.config);
3300        let sync_trigger = Arc::clone(&self.sync_trigger);
3301        let recent_provers = Arc::clone(&self.recent_provers);
3302
3303        let handle = tokio::spawn(async move {
3304            // Build the first commitment immediately on startup so a
3305            // restarted node can answer commitment-bound audits right
3306            // away — otherwise current() stays None for a full rotation
3307            // interval and audits silently fall back to legacy.
3308            //
3309            // After the first build, trigger an immediate neighbor-sync
3310            // round so the new commitment gossips out within seconds.
3311            // Without this, after a restart remote auditors keep pinning
3312            // the pre-restart (rotated-away) hash until their normal
3313            // sync cadence elapses — up to 1 h in the worst case,
3314            // during which time commitment-bound audits hit "unknown
3315            // commitment hash" -> Idle no-ops.
3316            // ML-DSA signatures are randomized so we cannot reproduce
3317            // the pre-restart hash; the only honest path to recovery
3318            // is fast re-gossip.
3319            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3320            // spawned), so this initial rebuild no-ops when the key set is
3321            // unchanged — preserving the reloaded current pin; otherwise the
3322            // reloaded roots stay answerable as retained slots until their gossip
3323            // TTL lapses. Persistence is handled by the retention-persist loop.
3324            if let Err(e) =
3325                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3326                    .await
3327            {
3328                warn!("Initial commitment build failed: {e}");
3329            } else {
3330                sync_trigger.notify_one();
3331            }
3332            loop {
3333                tokio::select! {
3334                    () = shutdown.cancelled() => break,
3335                    () = tokio::time::sleep(
3336                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3337                    ) => {
3338                        if let Err(e) = rebuild_and_rotate_commitment(
3339                            &storage,
3340                            &identity,
3341                            &commitment_state,
3342                            &p2p,
3343                            &config,
3344                        ).await {
3345                            warn!("Commitment rotation failed: {e}");
3346                        }
3347                        // Piggyback a sweep of expired recent_provers
3348                        // entries on the rotation tick (same cadence,
3349                        // 1 h). is_credited_holder already honours the
3350                        // TTL on read, but the sweep reclaims memory
3351                        // for entries we'll never re-read.
3352                        let dropped = recent_provers.write().await.sweep_expired(
3353                            std::time::Instant::now()
3354                        );
3355                        if dropped > 0 {
3356                            debug!("recent_provers: swept {dropped} expired entries");
3357                        }
3358                    }
3359                }
3360            }
3361            debug!("Commitment rotation loop shut down");
3362        });
3363        self.task_handles.push(handle);
3364    }
3365
3366    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3367    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3368    /// rotations — survives a restart. Flushes once immediately, then every
3369    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3370    fn start_retention_persist_loop(&mut self) {
3371        let commitment_state = Arc::clone(&self.commitment_state);
3372        let retention_path = self.retention_path.clone();
3373        let shutdown = self.shutdown.clone();
3374        let handle = tokio::spawn(async move {
3375            let mut last: Option<Vec<u8>> = None;
3376            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3377            loop {
3378                tokio::select! {
3379                    () = shutdown.cancelled() => {
3380                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3381                            .await;
3382                        break;
3383                    }
3384                    () = tokio::time::sleep(std::time::Duration::from_secs(
3385                        RETENTION_PERSIST_INTERVAL_SECS,
3386                    )) => {
3387                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3388                            .await;
3389                    }
3390                }
3391            }
3392            debug!("Commitment retention persist loop shut down");
3393        });
3394        self.task_handles.push(handle);
3395    }
3396
3397    /// Periodically emit the cumulative replication traffic summaries: the
3398    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3399    /// (V2-684). Both read process-global counter tables maintained by the
3400    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3401    /// state.
3402    fn start_traffic_summary_loop(&mut self) {
3403        let shutdown = self.shutdown.clone();
3404        let handle = tokio::spawn(async move {
3405            loop {
3406                tokio::select! {
3407                    () = shutdown.cancelled() => break,
3408                    () = tokio::time::sleep(std::time::Duration::from_secs(
3409                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3410                    )) => {
3411                        protocol::log_traffic_summary();
3412                        protocol::log_served_peers_summary();
3413                        protocol::log_audit_outcome_summary();
3414                        audit_metrics::log_responder_admission_summary();
3415                    }
3416                }
3417            }
3418            debug!("Replication traffic summary loop shut down");
3419        });
3420        self.task_handles.push(handle);
3421    }
3422
3423    /// Periodically expose the state that gates bootstrap completion and prune
3424    /// admission. The state counts are copied before reading `is_bootstrapping`
3425    /// so this diagnostic path never nests async locks.
3426    #[cfg(feature = "logging")]
3427    fn start_bootstrap_state_snapshot_loop(&mut self) {
3428        let shutdown = self.shutdown.clone();
3429        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3430        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3431        let started_at = Instant::now();
3432        let handle = tokio::spawn(async move {
3433            loop {
3434                tokio::select! {
3435                    () = shutdown.cancelled() => break,
3436                    () = tokio::time::sleep(Duration::from_secs(
3437                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3438                    )) => {
3439                        let (
3440                            drained,
3441                            pending_peer_requests,
3442                            pending_keys,
3443                            capacity_rejected_sources,
3444                        ) = {
3445                            let state = bootstrap_state.read().await;
3446                            (
3447                                state.drained,
3448                                state.pending_peer_requests,
3449                                state.pending_keys.len(),
3450                                state.capacity_rejected_sources.len(),
3451                            )
3452                        };
3453                        let bootstrapping = *is_bootstrapping.read().await;
3454                        let snapshot_state = if drained && !bootstrapping {
3455                            "healthy"
3456                        } else if drained {
3457                            "drained_waiting_for_bootstrap_flag"
3458                        } else {
3459                            "pending"
3460                        };
3461                        info!(
3462                            drained,
3463                            pending_peer_requests,
3464                            pending_keys,
3465                            capacity_rejected_sources,
3466                            is_bootstrapping = bootstrapping,
3467                            snapshot_state,
3468                            uptime_secs = started_at.elapsed().as_secs(),
3469                            "Replication bootstrap state snapshot"
3470                        );
3471                        if drained && !bootstrapping {
3472                            info!(
3473                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3474                            );
3475                            break;
3476                        }
3477                    }
3478                }
3479            }
3480            debug!("Bootstrap state snapshot loop shut down");
3481        });
3482        self.task_handles.push(handle);
3483    }
3484
3485    /// Periodically rank remote peers using the shared audit responder pool and
3486    /// report handler-only versus end-to-end latency. Windowed values make a
3487    /// burst visible even after a long-running node has accumulated traffic.
3488    #[cfg(feature = "logging")]
3489    fn start_audit_responder_summary_loop(&mut self) {
3490        let shutdown = self.shutdown.clone();
3491        let metrics = Arc::clone(&self.audit_responder_metrics);
3492        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3493        let handle = tokio::spawn(async move {
3494            let mut window_started = Instant::now();
3495            loop {
3496                tokio::select! {
3497                    () = shutdown.cancelled() => {
3498                        log_audit_responder_summary(
3499                            &metrics,
3500                            &semaphore,
3501                            window_started.elapsed(),
3502                        );
3503                        break;
3504                    }
3505                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3506                        log_audit_responder_summary(
3507                            &metrics,
3508                            &semaphore,
3509                            window_started.elapsed(),
3510                        );
3511                        window_started = Instant::now();
3512                    }
3513                }
3514            }
3515            debug!("Audit responder summary loop shut down");
3516        });
3517        self.task_handles.push(handle);
3518    }
3519
3520    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3521    fn start_fetch_worker(&mut self) {
3522        let p2p = Arc::clone(&self.p2p_node);
3523        let storage = Arc::clone(&self.storage);
3524        let queues = Arc::clone(&self.queues);
3525        let config = Arc::clone(&self.config);
3526        let shutdown = self.shutdown.clone();
3527        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3528        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3529        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3530        let detached_task_tracker = self.detached_task_tracker.clone();
3531        let concurrency = max_parallel_fetch();
3532
3533        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3534
3535        let handle = tokio::spawn(async move {
3536            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3537            // always recover the key — even if the inner task panics.
3538            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3539
3540            loop {
3541                // Fill up to `concurrency` slots from the queue.
3542                {
3543                    let mut q = queues.write().await;
3544                    while in_flight.len() < concurrency {
3545                        let Some(candidate) = q.dequeue_fetch() else {
3546                            break;
3547                        };
3548                        let fetch_key = candidate.key;
3549                        let Some(&source) = candidate.sources.first() else {
3550                            warn!(
3551                                "Fetch candidate {} has no sources; requeueing for verification",
3552                                hex::encode(fetch_key)
3553                            );
3554                            let _ = q.requeue_candidate_for_verification(
3555                                candidate,
3556                                config.verification_request_timeout,
3557                            );
3558                            continue;
3559                        };
3560                        q.start_dequeued_fetch(candidate, source);
3561
3562                        let p2p = Arc::clone(&p2p);
3563                        let storage = Arc::clone(&storage);
3564                        let config = Arc::clone(&config);
3565                        let token = shutdown.clone();
3566                        let tracker = detached_task_tracker.clone();
3567                        in_flight.push(Box::pin(async move {
3568                            // Tracked so shutdown() still awaits the task if
3569                            // this awaiter is dropped (e.g. the worker is
3570                            // aborted): it holds Arc<LmdbStorage> and must
3571                            // not outlive the engine.
3572                            let handle = tracker.spawn(async move {
3573                                // Cancel-aware: abort when the engine shuts down.
3574                                tokio::select! {
3575                                    () = token.cancelled() => FetchOutcome {
3576                                        key: fetch_key,
3577                                        result: FetchResult::SourceFailed,
3578                                    },
3579                                    outcome = execute_single_fetch(
3580                                        p2p, storage, config, fetch_key, source,
3581                                    ) => outcome,
3582                                }
3583                            });
3584                            match handle.await {
3585                                Ok(outcome) => (outcome.key, Some(outcome)),
3586                                Err(e) => {
3587                                    error!(
3588                                        "Fetch task for {} panicked: {e}",
3589                                        hex::encode(fetch_key)
3590                                    );
3591                                    (fetch_key, None)
3592                                }
3593                            }
3594                        }));
3595                    }
3596                } // release queues write lock
3597
3598                if in_flight.is_empty() {
3599                    // No work — wait for new items or shutdown.
3600                    tokio::select! {
3601                        () = shutdown.cancelled() => break,
3602                        () = tokio::time::sleep(
3603                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3604                        ) => continue,
3605                    }
3606                }
3607
3608                // Wait for the next fetch to complete and process the result.
3609                tokio::select! {
3610                    () = shutdown.cancelled() => break,
3611                    Some((key, maybe_outcome)) = in_flight.next() => {
3612                        let mut q = queues.write().await;
3613                        let terminal = if let Some(outcome) = maybe_outcome {
3614                            match apply_fetch_result(
3615                                &mut q,
3616                                &key,
3617                                &outcome.result,
3618                                config.verification_request_timeout,
3619                            ) {
3620                                FetchFollowUp::Terminal => true,
3621                                FetchFollowUp::RequeuedForVerification => false,
3622                                FetchFollowUp::RetryFrom(next_peer) => {
3623                                    // Spawn a new fetch task for the next source.
3624                                    let p2p = Arc::clone(&p2p);
3625                                    let storage = Arc::clone(&storage);
3626                                    let config = Arc::clone(&config);
3627                                    let token = shutdown.clone();
3628                                    let tracker = detached_task_tracker.clone();
3629                                    let fetch_key = key;
3630                                    in_flight.push(Box::pin(async move {
3631                                        // Tracked for the same reason as the
3632                                        // initial fetch spawn above.
3633                                        let handle = tracker.spawn(async move {
3634                                            tokio::select! {
3635                                                () = token.cancelled() => FetchOutcome {
3636                                                    key: fetch_key,
3637                                                    result: FetchResult::SourceFailed,
3638                                                },
3639                                                outcome = execute_single_fetch(
3640                                                    p2p, storage, config, fetch_key, next_peer,
3641                                                ) => outcome,
3642                                            }
3643                                        });
3644                                        match handle.await {
3645                                            Ok(outcome) => (outcome.key, Some(outcome)),
3646                                            Err(e) => {
3647                                                error!(
3648                                                    "Fetch task for {} panicked: {e}",
3649                                                    hex::encode(fetch_key)
3650                                                );
3651                                                (fetch_key, None)
3652                                            }
3653                                        }
3654                                    }));
3655                                    false
3656                                }
3657                            }
3658                        } else {
3659                            // Task panicked — retry verification when this was
3660                            // a verified repair, otherwise reclaim the slot.
3661                            !q.requeue_fetch_for_verification(
3662                                &key,
3663                                config.verification_request_timeout,
3664                            )
3665                        };
3666
3667                        // Shrink bootstrap pending set on terminal exit.
3668                        if terminal {
3669                            drop(q); // release queues lock before acquiring bootstrap_state
3670                            if !bootstrap_state.read().await.is_drained() {
3671                                bootstrap_state.write().await.remove_key(&key);
3672                                let q = queues.read().await;
3673                                if bootstrap::check_bootstrap_drained(
3674                                    &bootstrap_state,
3675                                    &q,
3676                                )
3677                                .await
3678                                {
3679                                    complete_bootstrap(
3680                                        &is_bootstrapping,
3681                                        &bootstrap_complete_notify,
3682                                    ).await;
3683                                }
3684                            }
3685                        }
3686                    }
3687                }
3688            }
3689
3690            // Cancel and drain remaining in-flight fetches on shutdown.
3691            // The CancellationToken is already cancelled by this point, so
3692            // spawned tasks will see cancellation via their select! branches.
3693            while in_flight.next().await.is_some() {}
3694            debug!("Fetch worker shut down");
3695        });
3696        self.task_handles.push(handle);
3697    }
3698
3699    fn start_verification_worker(&mut self) {
3700        let p2p = Arc::clone(&self.p2p_node);
3701        let storage = Arc::clone(&self.storage);
3702        let queues = Arc::clone(&self.queues);
3703        let paid_list = Arc::clone(&self.paid_list);
3704        let config = Arc::clone(&self.config);
3705        let shutdown = self.shutdown.clone();
3706        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3707        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3708        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3709        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3710        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3711        let recent_provers = Arc::clone(&self.recent_provers);
3712
3713        let handle = tokio::spawn(async move {
3714            loop {
3715                tokio::select! {
3716                    () = shutdown.cancelled() => break,
3717                    () = tokio::time::sleep(
3718                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3719                    ) => {
3720                        let ctx = VerificationCycleContext {
3721                            p2p_node: &p2p,
3722                            paid_list: &paid_list,
3723                            storage: &storage,
3724                            queues: &queues,
3725                            config: &config,
3726                            bootstrap_state: &bootstrap_state,
3727                            is_bootstrapping: &is_bootstrapping,
3728                            bootstrap_complete_notify: &bootstrap_complete_notify,
3729                            last_commitment_by_peer: &last_commitment_by_peer,
3730                            ever_capable_peers: &ever_capable_peers,
3731                            recent_provers: &recent_provers,
3732                        };
3733                        run_verification_cycle(ctx).await;
3734                    }
3735                }
3736            }
3737            debug!("Verification worker shut down");
3738        });
3739        self.task_handles.push(handle);
3740    }
3741
3742    /// Gap 3: Run a one-shot bootstrap sync on startup.
3743    ///
3744    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3745    /// (indicating the routing table is populated) before snapshotting
3746    /// close neighbors. Falls back after a timeout so bootstrap nodes
3747    /// (which have no peers and therefore never receive the event) still
3748    /// proceed.
3749    ///
3750    /// After the gate, finds close neighbors, syncs with each in
3751    /// round-robin batches, admits returned hints into the verification
3752    /// pipeline, and tracks discovered keys for bootstrap drain detection.
3753    #[allow(clippy::too_many_lines)]
3754    fn start_bootstrap_sync(
3755        &mut self,
3756        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3757    ) {
3758        let p2p = Arc::clone(&self.p2p_node);
3759        let storage = Arc::clone(&self.storage);
3760        let paid_list = Arc::clone(&self.paid_list);
3761        let queues = Arc::clone(&self.queues);
3762        let config = Arc::clone(&self.config);
3763        let shutdown = self.shutdown.clone();
3764        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3765        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3766        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3767        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3768        let repair_proofs = Arc::clone(&self.repair_proofs);
3769        let my_commitment_state = Arc::clone(&self.commitment_state);
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 sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3773
3774        let handle = tokio::spawn(async move {
3775            // Wait for DHT bootstrap to complete before snapshotting
3776            // neighbors. The routing table is empty until saorsa-core
3777            // finishes its FIND_NODE rounds and bucket refreshes.
3778            let gate = bootstrap::wait_for_bootstrap_complete(
3779                dht_events,
3780                config.bootstrap_complete_timeout_secs,
3781                &shutdown,
3782            )
3783            .await;
3784
3785            if gate == bootstrap::BootstrapGateResult::Shutdown {
3786                return;
3787            }
3788
3789            let self_id = *p2p.peer_id();
3790            let neighbors =
3791                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3792                    .await;
3793
3794            if neighbors.is_empty() {
3795                info!("Bootstrap sync: no close neighbors found, marking drained");
3796                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3797                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3798                return;
3799            }
3800
3801            let neighbor_count = neighbors.len();
3802            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3803
3804            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3805            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3806                if shutdown.is_cancelled() {
3807                    break;
3808                }
3809
3810                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3811                    batch,
3812                    &storage,
3813                    &paid_list,
3814                    &p2p,
3815                    config.close_group_size,
3816                    config.paid_list_close_group_size,
3817                )
3818                .await;
3819
3820                // Keep the batch outstanding until every response has been
3821                // admitted and bootstrap accounting is updated. The verification
3822                // worker uses this counter as a batch barrier, so it cannot race
3823                // the source aggregation below.
3824                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3825                let bootstrapping = *is_bootstrapping.read().await;
3826
3827                let sync_futures = batch.iter().map(|peer| {
3828                    let peer = *peer;
3829                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3830                    // Atomically snapshot + mark-gossiped for each emitted
3831                    // bootstrap request so we remain answerable for it.
3832                    let commitment = my_commitment_state
3833                        .current_for_gossip()
3834                        .map(|binding| binding.commitment().clone());
3835                    let p2p = &p2p;
3836                    let config = &config;
3837                    async move {
3838                        let outcome = neighbor_sync::sync_with_peer_with_hints(
3839                            &peer,
3840                            p2p,
3841                            config,
3842                            bootstrapping,
3843                            hints,
3844                            commitment,
3845                        )
3846                        .await;
3847                        (peer, outcome)
3848                    }
3849                });
3850                let completed = join_all(sync_futures).await;
3851
3852                // Process response metadata before exposing any of this batch's
3853                // hints to verification.
3854                for (peer, outcome) in &completed {
3855                    if let Some(outcome) = outcome {
3856                        // Ingest the peer's piggybacked commitment from the
3857                        // response (same verification as the request path).
3858                        // Bootstrap is the FIRST gossip we receive from most
3859                        // peers, so this populates last_commitment_by_peer.
3860                        //
3861                        // We intentionally do NOT trigger a gossip-audit here:
3862                        // during bootstrap this node may itself still be
3863                        // bootstrapping (audits are gated on that), and the
3864                        // close-group/RT view is not yet stable. The peer is
3865                        // audited on the first STEADY-STATE neighbor-sync round
3866                        // after bootstrap drains (request + response paths both
3867                        // trigger), which is within one sync cycle — so caching
3868                        // the commitment here is sufficient and there is no
3869                        // coverage gap (ADR-0002).
3870                        ingest_peer_commitment(
3871                            peer,
3872                            outcome.response.commitment.as_ref(),
3873                            &p2p,
3874                            &last_commitment_by_peer,
3875                            &ever_capable_peers,
3876                            &sig_verify_attempts,
3877                        )
3878                        .await; // sig_verify_attempts in scope from line ~1080
3879
3880                        if !outcome.response.bootstrapping {
3881                            record_sent_replica_hints(
3882                                peer,
3883                                &outcome.sent_replica_hints,
3884                                &repair_proofs,
3885                                &sync_cycle_epoch,
3886                            )
3887                            .await;
3888                        }
3889                    }
3890                }
3891
3892                let pending_keys: HashSet<XorName> = {
3893                    let q = queues.read().await;
3894                    q.pending_keys().into_iter().collect()
3895                };
3896                let admission_futures = completed.iter().map(|(_, outcome)| async {
3897                    match outcome {
3898                        Some(outcome) if !outcome.response.bootstrapping => Some(
3899                            admission::admit_hints(
3900                                &self_id,
3901                                &outcome.response.replica_hints,
3902                                &outcome.response.paid_hints,
3903                                &p2p,
3904                                &config,
3905                                &storage,
3906                                &paid_list,
3907                                &pending_keys,
3908                            )
3909                            .await,
3910                        ),
3911                        _ => None,
3912                    }
3913                });
3914                let admitted = join_all(admission_futures).await;
3915
3916                // Queue every peer's admitted hints under one write lock. Once
3917                // released, source-count ordering sees the complete batch.
3918                let (batch_outcomes, batch_discovered) = {
3919                    let mut q = queues.write().await;
3920                    let outcomes = completed
3921                        .iter()
3922                        .zip(admitted)
3923                        .filter_map(|((peer, _), admitted)| {
3924                            admitted.map(|admitted| {
3925                                (
3926                                    *peer,
3927                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
3928                                )
3929                            })
3930                        })
3931                        .collect::<Vec<_>>();
3932                    let live_discovered = outcomes
3933                        .iter()
3934                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3935                        .filter(|key| q.contains_key(key))
3936                        .collect::<HashSet<_>>();
3937                    (outcomes, live_discovered)
3938                };
3939
3940                publish_bootstrap_admission_outcomes(
3941                    &bootstrap_state,
3942                    &batch_outcomes,
3943                    &batch_discovered,
3944                )
3945                .await;
3946
3947                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3948            }
3949
3950            // Check drain condition.
3951            {
3952                let q = queues.read().await;
3953                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3954                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3955                }
3956            }
3957
3958            info!("Bootstrap sync completed");
3959        });
3960        self.task_handles.push(handle);
3961    }
3962}
3963
3964// ===========================================================================
3965// Free functions for background tasks
3966// ===========================================================================
3967
3968#[cfg(feature = "logging")]
3969fn log_audit_responder_summary(
3970    metrics: &AuditResponderMetrics,
3971    semaphore: &Semaphore,
3972    window: Duration,
3973) {
3974    let snapshot = metrics.take_snapshot();
3975    if snapshot.origins.is_empty() {
3976        return;
3977    }
3978
3979    let total = snapshot.total;
3980    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3981        total.received_by_class;
3982    let global_inflight =
3983        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
3984    info!(
3985        target: "ant_node::replication::audit_responder",
3986        window_ms = window.as_millis(),
3987        source_count = snapshot.origins.len(),
3988        received = total.received(),
3989        digest_received,
3990        subtree_received,
3991        byte_received,
3992        commitment_pin_received,
3993        admitted = total.admitted,
3994        global_pool_drops = total.global_pool_drops,
3995        per_peer_cap_drops = total.per_peer_cap_drops,
3996        serial_queue_drops = total.serial_queue_drops,
3997        completed = total.completed,
3998        send_failures = total.send_failures,
3999        processing_avg_ms = total.processing_avg_ms(),
4000        processing_max_ms = total.processing_max_ms,
4001        total_avg_ms = total.total_avg_ms(),
4002        total_max_ms = total.total_max_ms,
4003        global_inflight,
4004        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4005        peak_global_inflight = total.peak_global_inflight,
4006        "Audit responder summary"
4007    );
4008
4009    for (index, origin) in snapshot
4010        .origins
4011        .iter()
4012        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4013        .enumerate()
4014    {
4015        let Some(source) = origin.source else {
4016            continue;
4017        };
4018        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4019            origin.received_by_class;
4020        info!(
4021            target: "ant_node::replication::audit_responder",
4022            rank = index + 1,
4023            source = %source,
4024            received = origin.received(),
4025            digest_received,
4026            subtree_received,
4027            byte_received,
4028            commitment_pin_received,
4029            admitted = origin.admitted,
4030            global_pool_drops = origin.global_pool_drops,
4031            per_peer_cap_drops = origin.per_peer_cap_drops,
4032            serial_queue_drops = origin.serial_queue_drops,
4033            completed = origin.completed,
4034            send_failures = origin.send_failures,
4035            processing_avg_ms = origin.processing_avg_ms(),
4036            processing_max_ms = origin.processing_max_ms,
4037            total_avg_ms = origin.total_avg_ms(),
4038            total_max_ms = origin.total_max_ms,
4039            peak_global_inflight = origin.peak_global_inflight,
4040            peak_peer_inflight = origin.peak_peer_inflight,
4041            "Audit responder top origin"
4042        );
4043    }
4044}
4045
4046/// Which ceiling rejected an audit-responder admission attempt.
4047///
4048/// Stable, machine-readable so a production log-scrape can bucket drops by
4049/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4050/// single opaque "capacity reached" line; this splits the two distinct causes
4051/// so the next such investigation can tell a global-pool exhaustion (the whole
4052/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4053/// without re-instrumenting.
4054///
4055/// This branch runs a SINGLE shared audit-responder pool for all challenge
4056/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4057/// pool to distinguish here — the `kind=` log field already separates the
4058/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4059/// dedicated slow pool is later split out, add its variants here.
4060#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4061enum ResponderRejectReason {
4062    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4063    /// free; the per-peer cap was not the binding constraint.
4064    GlobalPoolFull,
4065    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4066    /// share, so the global permit was never attempted.
4067    PerPeerCapFull,
4068}
4069
4070impl ResponderRejectReason {
4071    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4072    /// frozen — production log tooling greps for them.
4073    fn as_str(self) -> &'static str {
4074        match self {
4075            Self::GlobalPoolFull => "global_pool_full",
4076            Self::PerPeerCapFull => "per_peer_cap_full",
4077        }
4078    }
4079}
4080
4081impl From<ResponderRejectReason> for AuditResponderDropReason {
4082    fn from(reason: ResponderRejectReason) -> Self {
4083        match reason {
4084            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4085            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4086        }
4087    }
4088}
4089
4090impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4091    fn from(reason: ResponderRejectReason) -> Self {
4092        match reason {
4093            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4094            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4095        }
4096    }
4097}
4098
4099/// Cumulative fresh-offer admission refusals in this process.
4100///
4101/// **Expected value in healthy operation is zero.** A node that refuses a
4102/// legitimate fresh offer does not merely shed load: the sender transmits
4103/// offers one-way and never reads the refusal, so the chunk's absence
4104/// resurfaces at the sender's delayed possession check and is charged to the
4105/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4106/// means the node is either under-provisioned for its offered load or its
4107/// admission share is mis-sized — and is accruing unearned trust damage either
4108/// way. Operators should alarm on any sustained non-zero rate.
4109///
4110/// Process-global rather than per-engine, which is exactly right in production
4111/// (one node per process) and adequate in multi-node test harnesses, where the
4112/// useful assertion is that *no* node in the fleet refused.
4113#[must_use]
4114pub fn fresh_offer_admission_refusals() -> u64 {
4115    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4116}
4117
4118/// Cumulative paid-list notification admission refusals in this process.
4119///
4120/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4121/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4122/// paid-list evidence outright rather than pushing work back onto a requester.
4123#[must_use]
4124pub fn paid_notify_admission_refusals() -> u64 {
4125    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4126}
4127
4128/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4129///
4130/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4131/// different things: this one says the node was saturated across all sources
4132/// and is genuinely under-provisioned for its offered load.
4133#[must_use]
4134pub fn fresh_offer_refusals_global_pool() -> u64 {
4135    audit_metrics::responder_admission_drops_by_ceiling(
4136        ReplicationResponderClass::FreshOffer,
4137        ResponderAdmissionCeiling::GlobalPool,
4138    )
4139}
4140
4141/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4142///
4143/// For fresh offers this usually indicts the *share's size* rather than the
4144/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4145/// node handling a client's PUT and fanning it out — so a share sized for
4146/// request/response traffic will refuse ordinary uploads.
4147#[must_use]
4148pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4149    audit_metrics::responder_admission_drops_by_ceiling(
4150        ReplicationResponderClass::FreshOffer,
4151        ResponderAdmissionCeiling::PerPeerShare,
4152    )
4153}
4154
4155/// Why an audit-responder admission attempt failed, with the decision-time
4156/// capacity counters that let a drop be logged with full context.
4157///
4158/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4159/// decision was made (the two ceilings are read under different locks, so they
4160/// are not a single atomic view), but they are exact enough to tell a saturated
4161/// node from a single self-throttling flooder.
4162#[derive(Debug, Clone, Copy)]
4163struct ResponderAdmissionFailure {
4164    reason: ResponderRejectReason,
4165    /// Global permits in use across the whole engine at decision time.
4166    global_inflight: usize,
4167    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4168    global_limit: usize,
4169    /// In-flight audit responders already held for `source` at decision time.
4170    peer_inflight: u32,
4171    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4172    peer_limit: u32,
4173}
4174
4175impl fmt::Display for ResponderAdmissionFailure {
4176    /// Renders the stable `reason=... global_inflight=... global_limit=...
4177    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4179        write!(
4180            f,
4181            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4182            self.reason.as_str(),
4183            self.global_inflight,
4184            self.global_limit,
4185            self.peer_inflight,
4186            self.peer_limit,
4187        )
4188    }
4189}
4190
4191/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4192/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4193/// spawned task ties both bounds to the task's exact lifetime — no manual
4194/// decrement to forget on an early return or panic.
4195struct ResponderGuard {
4196    _permit: tokio::sync::OwnedSemaphorePermit,
4197    _peer_slot: PeerResponderSlot,
4198    global_inflight: usize,
4199    peer_inflight: u32,
4200}
4201
4202type AuditResponderGuard = ResponderGuard;
4203type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4204
4205/// Provisional or admitted per-peer responder slot.
4206///
4207/// The slot is claimed before the global permit is attempted. Keeping that
4208/// claim under RAII means cancellation while rolling a failed admission back
4209/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4210/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4211struct PeerResponderSlot {
4212    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4213    peer: PeerId,
4214}
4215
4216#[derive(Clone)]
4217struct ReplicationMessageHandlerContext {
4218    p2p_node: Arc<P2PNode>,
4219    storage: Arc<LmdbStorage>,
4220    paid_list: Arc<PaidList>,
4221    payment_verifier: Arc<PaymentVerifier>,
4222    queues: Arc<RwLock<ReplicationQueues>>,
4223    config: Arc<ReplicationConfig>,
4224    is_bootstrapping: Arc<RwLock<bool>>,
4225    bootstrap_state: Arc<RwLock<BootstrapState>>,
4226    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4227    sync_cycle_epoch: Arc<RwLock<u64>>,
4228    repair_proofs: Arc<RwLock<RepairProofs>>,
4229    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4230    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4231    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4232    my_commitment_state: Arc<ResponderCommitmentState>,
4233    gossip_audit: GossipAuditTrigger,
4234    audit_responder_semaphore: Arc<Semaphore>,
4235    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4236    audit_responder_metrics: Arc<AuditResponderMetrics>,
4237    subtree_round1: SubtreeRound1Limiter,
4238    fetch_responder_worker_semaphore: Arc<Semaphore>,
4239    fetch_responder_admission_semaphore: Arc<Semaphore>,
4240    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4241    verification_responder_worker_semaphore: Arc<Semaphore>,
4242    verification_responder_admission_semaphore: Arc<Semaphore>,
4243    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4244    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4245    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4246    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4247    fresh_offer_worker_semaphore: Arc<Semaphore>,
4248    fresh_offer_admission_semaphore: Arc<Semaphore>,
4249    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4250    fresh_offer_in_flight: FreshOfferInFlight,
4251    paid_notify_worker_semaphore: Arc<Semaphore>,
4252    paid_notify_admission_semaphore: Arc<Semaphore>,
4253    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4254    /// The engine's shutdown token, for detached responder work.
4255    ///
4256    /// Workers on [`Self::detached_task_tracker`] race this around their
4257    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4258    /// where dropping the awaiter would detach a live transaction. This is
4259    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4260    /// terminate: the wait stays safe because it is now guaranteed finite.
4261    shutdown: CancellationToken,
4262    /// Shared tracker for detached work so `shutdown()` can await release of
4263    /// storage and P2P resources after all producer tasks have stopped.
4264    detached_task_tracker: TaskTracker,
4265}
4266
4267struct InboundReplicationMessage {
4268    source: PeerId,
4269    msg: ReplicationMessage,
4270    rr_message_id: Option<String>,
4271    received_at: Instant,
4272}
4273
4274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4275enum SerialQueueDropReason {
4276    Full,
4277    Closed,
4278}
4279
4280#[cfg(feature = "logging")]
4281impl SerialQueueDropReason {
4282    const fn as_str(self) -> &'static str {
4283        match self {
4284            Self::Full => "full",
4285            Self::Closed => "closed",
4286        }
4287    }
4288}
4289
4290#[derive(Debug, Clone, Copy)]
4291#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4292struct SerialQueueDrop {
4293    source: PeerId,
4294    message_class: &'static str,
4295    audit_responder_class: Option<AuditResponderClass>,
4296    queue_depth: usize,
4297    reason: SerialQueueDropReason,
4298}
4299
4300fn try_enqueue_serial_message(
4301    sender: &mpsc::Sender<InboundReplicationMessage>,
4302    inbound: InboundReplicationMessage,
4303) -> std::result::Result<(), SerialQueueDrop> {
4304    let source = inbound.source;
4305    let message_class = replication_message_class(&inbound.msg.body);
4306    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4307    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4308    sender.try_send(inbound).map_err(|error| {
4309        let (reason, dropped) = match error {
4310            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4311            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4312        };
4313        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4314        SerialQueueDrop {
4315            source,
4316            message_class,
4317            audit_responder_class,
4318            queue_depth,
4319            reason,
4320        }
4321    })
4322}
4323
4324const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4325    match body {
4326        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4327        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4328        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4329        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4330        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4331        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4332        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4333        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4334        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4335        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4336        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4337        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4338        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4339        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4340        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4341        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4342        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4343    }
4344}
4345
4346const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4347    match body {
4348        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4349        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4350        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4351        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4352        _ => None,
4353    }
4354}
4355
4356impl AuditResponderClass {
4357    const fn per_peer_limit(self) -> u32 {
4358        match self {
4359            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4360            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4361        }
4362    }
4363}
4364
4365fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4366    match error {
4367        RecvError::Lagged(missed) => {
4368            audit_metrics::record_replication_event_lagged(*missed);
4369            warn!(
4370                "Missed {missed} P2P events on replication branch (broadcast lag); \
4371                 replication messages may have been dropped before dispatch"
4372            );
4373            ControlFlow::Continue(())
4374        }
4375        RecvError::Closed => {
4376            // A closed broadcast channel never yields again, so the branch
4377            // would otherwise be immediately ready on every select! iteration.
4378            warn!("P2P event stream closed on replication branch; stopping message handler");
4379            ControlFlow::Break(())
4380        }
4381    }
4382}
4383
4384fn replication_payload_from_event(
4385    event: P2PEvent,
4386) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4387    let P2PEvent::Message {
4388        topic,
4389        source: Some(source),
4390        data,
4391        ..
4392    } = event
4393    else {
4394        return None;
4395    };
4396
4397    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4398    if !is_rr {
4399        return Some((source, data, matched_id, None));
4400    }
4401    if is_rr {
4402        return P2PNode::parse_request_envelope(&data)
4403            .filter(|(_, is_resp, _)| !is_resp)
4404            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4405    }
4406    None
4407}
4408
4409impl Drop for PeerResponderSlot {
4410    fn drop(&mut self) {
4411        // Decrement (and prune to keep the map bounded) without blocking the
4412        // async runtime: a short lock on a tiny map.
4413        //
4414        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4415        // with no spawn. Otherwise defer to a task — but only if a runtime is
4416        // actually current, so `Drop` during shutdown (no runtime) can never
4417        // panic. A missed decrement at shutdown is harmless: the whole map is
4418        // being dropped with the engine.
4419        let peer = self.peer;
4420        if let Ok(mut map) = self.inflight.try_write() {
4421            if let Some(n) = map.get_mut(&peer) {
4422                *n = n.saturating_sub(1);
4423                if *n == 0 {
4424                    map.remove(&peer);
4425                }
4426            }
4427            return;
4428        }
4429        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4430            let inflight = Arc::clone(&self.inflight);
4431            handle.spawn(async move {
4432                let mut map = inflight.write().await;
4433                if let Some(n) = map.get_mut(&peer) {
4434                    *n = n.saturating_sub(1);
4435                    if *n == 0 {
4436                        map.remove(&peer);
4437                    }
4438                }
4439            });
4440        }
4441    }
4442}
4443
4444/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4445/// and then a global permit. The limits are parameters so independent responder
4446/// classes can reuse the same flood-fair admission and cancellation semantics.
4447async fn admit_bounded_responder(
4448    semaphore: &Arc<Semaphore>,
4449    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4450    source: &PeerId,
4451    global_limit: usize,
4452    peer_limit: u32,
4453) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4454    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4455
4456    let admitted_peer_inflight = {
4457        let mut map = inflight.write().await;
4458        let entry = map.entry(*source).or_insert(0);
4459        if *entry >= peer_limit {
4460            let peer_inflight = *entry;
4461            drop(map);
4462            return Err(ResponderAdmissionFailure {
4463                reason: ResponderRejectReason::PerPeerCapFull,
4464                global_inflight: global_inflight(semaphore),
4465                global_limit,
4466                peer_inflight,
4467                peer_limit,
4468            });
4469        }
4470        *entry += 1;
4471        *entry
4472    };
4473
4474    let peer_slot = PeerResponderSlot {
4475        inflight: Arc::clone(inflight),
4476        peer: *source,
4477    };
4478    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4479        return Err(ResponderAdmissionFailure {
4480            reason: ResponderRejectReason::GlobalPoolFull,
4481            global_inflight: global_inflight(semaphore),
4482            global_limit,
4483            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4484            peer_limit,
4485        });
4486    };
4487
4488    Ok(ResponderGuard {
4489        _permit: permit,
4490        _peer_slot: peer_slot,
4491        global_inflight: global_inflight(semaphore),
4492        peer_inflight: admitted_peer_inflight,
4493    })
4494}
4495
4496/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4497struct SubtreeSession {
4498    commitment_hash: [u8; 32],
4499    nonce: [u8; 32],
4500    inserted: Instant,
4501}
4502
4503/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4504/// read and hash, refilled continuously at
4505/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4506/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4507///
4508/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4509/// identity may ask, so it is refilled by acquiring more identities; this is
4510/// charged for work done regardless of who asked, so it is not.
4511///
4512/// Charged after the fact, with the bytes the proof actually covered: the cost
4513/// of a request is not known until the pinned commitment has been resolved and
4514/// its subtree selected, both of which happen inside the handler. Admission
4515/// therefore asks only whether the balance is positive, and a proof that costs
4516/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4517/// Carrying the debt is what makes the bound real: without it a maximal proof
4518/// would cost the same as a trivial one, since either way the next request only
4519/// has to wait for the balance to climb back above zero. With it, sustained
4520/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4521/// admitted proportionally less often.
4522struct Round1WorkBudget {
4523    /// Signed, so an over-large proof leaves debt to work off.
4524    balance: i64,
4525    last_refill: Instant,
4526}
4527
4528impl Round1WorkBudget {
4529    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4530    /// for longer than the burst takes to refill.
4531    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4532    /// Nanoseconds per second, for the sub-second part of a refill.
4533    const NANOS_PER_SEC: i64 = 1_000_000_000;
4534
4535    fn new() -> Self {
4536        Self {
4537            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4538            last_refill: Instant::now(),
4539        }
4540    }
4541
4542    /// Add the tokens accrued since the last touch, capped at the burst size.
4543    fn refill(&mut self, now: Instant) {
4544        let elapsed = now.saturating_duration_since(self.last_refill);
4545        self.last_refill = now;
4546        let whole_secs = i64::try_from(elapsed.as_secs())
4547            .unwrap_or(i64::MAX)
4548            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4549        let sub_sec = i64::from(elapsed.subsec_nanos())
4550            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4551            / Self::NANOS_PER_SEC;
4552        self.balance = self
4553            .balance
4554            .saturating_add(whole_secs.saturating_add(sub_sec))
4555            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4556    }
4557
4558    /// Whether budget remains for a new round-1 proof.
4559    fn has_budget(&mut self, now: Instant) -> bool {
4560        self.refill(now);
4561        self.balance > 0
4562    }
4563
4564    /// Charge `bytes` of completed proof work, carrying debt down to
4565    /// [`Self::MAX_DEBT`].
4566    fn charge(&mut self, bytes: i64, now: Instant) {
4567        self.refill(now);
4568        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4569    }
4570}
4571
4572/// Resource controls for the HEAVY subtree-audit round 1: a tight
4573/// admission pool separate from the light responsible/slice audits, a per-peer
4574/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4575/// challenge is only served after a matching round 1.
4576///
4577/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4578/// bounds not keyed by peer identity, and so the only one that bounds sustained
4579/// work rather than concurrency or per-identity frequency.
4580#[derive(Clone)]
4581struct SubtreeRound1Limiter {
4582    semaphore: Arc<Semaphore>,
4583    /// Global ceiling on concurrent round-1 proofs (config-driven;
4584    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4585    /// semaphore because the per-peer admission helper needs the same number.
4586    max_concurrent: usize,
4587    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4588    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4589    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4590    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4591    cooldown_interval: Duration,
4592    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4593    /// Identity-independent ceiling on sustained round-1 work.
4594    work: Arc<RwLock<Round1WorkBudget>>,
4595}
4596
4597impl SubtreeRound1Limiter {
4598    /// `max_concurrent` of 0 would wedge the responder into refusing every
4599    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4600    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4601    /// rather than to off.
4602    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4603        let max_concurrent = max_concurrent.max(1);
4604        Self {
4605            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4606            max_concurrent,
4607            inflight: Arc::new(RwLock::new(HashMap::new())),
4608            cooldown: Arc::new(RwLock::new(HashMap::new())),
4609            cooldown_interval,
4610            sessions: Arc::new(RwLock::new(HashMap::new())),
4611            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4612        }
4613    }
4614
4615    /// Charge completed round-1 proof work against the responder-wide budget.
4616    async fn charge_work(&self, content_bytes: i64) {
4617        self.work
4618            .write()
4619            .await
4620            .charge(content_bytes, Instant::now());
4621    }
4622
4623    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4624    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4625    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4626    /// drops the challenge (the remote auditor applies its own graced-timeout
4627    /// policy).
4628    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4629        let guard = admit_bounded_responder(
4630            &self.semaphore,
4631            &self.inflight,
4632            source,
4633            self.max_concurrent,
4634            MAX_SUBTREE_ROUND1_PER_PEER,
4635        )
4636        .await
4637        .ok()?;
4638        // Checked before the per-peer cooldown is stamped, so a peer refused for
4639        // want of budget is not also charged its next allowance.
4640        if !self.work.write().await.has_budget(Instant::now()) {
4641            return None; // guard drops here, releasing the permit + slot
4642        }
4643        let now = Instant::now();
4644        let mut cooldown = self.cooldown.write().await;
4645        if let Some(&last) = cooldown.get(source) {
4646            if now.duration_since(last) < self.cooldown_interval {
4647                return None; // guard drops here, releasing the permit + slot
4648            }
4649        }
4650        // Evict lapsed entries (their cooldown has expired, so they no longer
4651        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4652        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4653        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4654            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4655                cooldown.remove(&oldest);
4656            }
4657        }
4658        cooldown.insert(*source, now);
4659        Some(guard)
4660    }
4661
4662    /// Record a single-use session once a round-1 proof is built and about to be
4663    /// sent, so the matching round 2 is admitted exactly once.
4664    async fn open_session(
4665        &self,
4666        source: PeerId,
4667        challenge_id: u64,
4668        commitment_hash: [u8; 32],
4669        nonce: [u8; 32],
4670    ) {
4671        let now = Instant::now();
4672        let mut sessions = self.sessions.write().await;
4673        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4674        if sessions.len() >= MAX_SUBTREE_SESSIONS {
4675            if let Some(oldest) = sessions
4676                .iter()
4677                .min_by_key(|(_, e)| e.inserted)
4678                .map(|(k, _)| *k)
4679            {
4680                sessions.remove(&oldest);
4681            }
4682        }
4683        sessions.insert(
4684            (source, challenge_id),
4685            SubtreeSession {
4686                commitment_hash,
4687                nonce,
4688                inserted: now,
4689            },
4690        );
4691    }
4692
4693    /// Atomically consume the round-2 session for this exchange. `true` iff a
4694    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4695    /// existed (and is now removed); a miss silently drops round 2 to the graced
4696    /// timeout lane (sessions are ephemeral and can be lost across a restart).
4697    async fn consume_session(
4698        &self,
4699        source: &PeerId,
4700        challenge_id: u64,
4701        commitment_hash: &[u8; 32],
4702        nonce: &[u8; 32],
4703    ) -> bool {
4704        let mut sessions = self.sessions.write().await;
4705        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4706            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4707                && &e.commitment_hash == commitment_hash
4708                && &e.nonce == nonce
4709        });
4710        if matches {
4711            sessions.remove(&(*source, challenge_id));
4712        }
4713        matches
4714    }
4715}
4716
4717/// Outcome of admitting a round-2 slice challenge.
4718enum SliceAdmission {
4719    /// Admitted: the guard holds the global permit and the per-peer slot, and
4720    /// the single-use round-1 session has been consumed.
4721    Admitted(AuditResponderGuard),
4722    /// Refused at a responder ceiling. The round-1 session is left INTACT.
4723    Capacity(AuditResponderAdmissionFailure),
4724    /// No live round-1 session matched this challenge.
4725    NoSession,
4726}
4727
4728/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4729/// the single-use round-1 session.
4730///
4731/// The order is the point: a single-use token must not be spent on work that is
4732/// then refused. Consuming first and testing admission second leaves the session
4733/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4734/// even in principle.
4735///
4736/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4737/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4738/// auditor does not currently re-send round 2 within an audit. The preserved
4739/// session is therefore not yet *recovering* an audit — it keeps a refusal
4740/// truthful (temporary means temporary) and keeps the invariant available for a
4741/// retry, rather than baking "capacity drop is permanent" into the state
4742/// machine. If an application-level retry is ruled out for good, this ordering
4743/// still costs nothing over the alternative.
4744///
4745/// Cost of the ordering: the permit and per-peer slot are held across the
4746/// session probe, which is one in-memory map lookup and no chunk work. The
4747/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4748/// share it could already occupy with well-formed ones, so the admission
4749/// surface is unchanged.
4750async fn admit_slice_challenge(
4751    semaphore: &Arc<Semaphore>,
4752    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4753    round1: &SubtreeRound1Limiter,
4754    source: &PeerId,
4755    challenge: &protocol::SubtreeSliceChallenge,
4756) -> SliceAdmission {
4757    let guard =
4758        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4759            Ok(guard) => guard,
4760            Err(failure) => return SliceAdmission::Capacity(failure),
4761        };
4762    if !round1
4763        .consume_session(
4764            source,
4765            challenge.challenge_id,
4766            &challenge.expected_commitment_hash,
4767            &challenge.nonce,
4768        )
4769        .await
4770    {
4771        // Release the permit and per-peer slot before the caller replies: no
4772        // chunk work follows, so holding them would shrink the pool for nothing.
4773        drop(guard);
4774        return SliceAdmission::NoSession;
4775    }
4776    SliceAdmission::Admitted(guard)
4777}
4778
4779/// Try to admit one audit-responder task for `source`: take a global permit AND
4780/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4781/// its decision-time counters (caller drops the challenge, leaving the remote
4782/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4783/// so one flooder can neither exhaust the global pool's effect on others nor
4784/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4785/// log exactly WHY the drop happened rather than a single opaque "capacity
4786/// reached".
4787async fn admit_audit_responder(
4788    semaphore: &Arc<Semaphore>,
4789    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4790    source: &PeerId,
4791    class: AuditResponderClass,
4792) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4793    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4794    let peer_limit = class.per_peer_limit();
4795    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4796}
4797
4798/// Handle an incoming replication protocol message.
4799///
4800/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4801/// request-response path and the response must be sent via `send_response`
4802/// so saorsa-core can route it back to the waiting `send_request` caller.
4803#[allow(clippy::too_many_lines)]
4804async fn handle_replication_message(
4805    source: &PeerId,
4806    msg: ReplicationMessage,
4807    ctx: &ReplicationMessageHandlerContext,
4808    received_at: Instant,
4809    rr_message_id: Option<&str>,
4810) -> Result<()> {
4811    match msg.body {
4812        ReplicationMessageBody::FreshReplicationOffer(offer) => {
4813            dispatch_fresh_offer(
4814                *source,
4815                offer,
4816                ctx,
4817                msg.request_id,
4818                received_at,
4819                rr_message_id,
4820            )
4821            .await
4822        }
4823        ReplicationMessageBody::PaidNotify(notify) => {
4824            dispatch_paid_notify(*source, notify, ctx, received_at).await
4825        }
4826        ReplicationMessageBody::NeighborSyncRequest(request) => {
4827            let bootstrapping = *ctx.is_bootstrapping.read().await;
4828            // Phase-3 storage-bound audit: store the sender's
4829            // commitment for use as `expected_commitment_hash` in
4830            // future audits. Verify signature before storing so a peer
4831            // cannot inject a forged commitment for someone else.
4832            if let Some(target) = ingest_peer_commitment(
4833                source,
4834                request.commitment.as_ref(),
4835                &ctx.p2p_node,
4836                &ctx.last_commitment_by_peer,
4837                &ctx.ever_capable_peers,
4838                &ctx.sig_verify_attempts,
4839            )
4840            .await
4841            {
4842                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4843            }
4844            dispatch_neighbor_sync_request(
4845                *source,
4846                request,
4847                ctx,
4848                bootstrapping,
4849                // Atomically snapshot + mark-gossiped: emitted in the sync
4850                // response, so we must stay answerable for it (ADR-0002).
4851                ctx.my_commitment_state
4852                    .current_for_gossip()
4853                    .map(|b| b.commitment().clone()),
4854                msg.request_id,
4855                received_at,
4856                rr_message_id,
4857            )
4858            .await
4859        }
4860        ReplicationMessageBody::VerificationRequest(request) => {
4861            dispatch_verification_request(
4862                *source,
4863                request,
4864                ctx,
4865                msg.request_id,
4866                received_at,
4867                rr_message_id,
4868            )
4869            .await
4870        }
4871        ReplicationMessageBody::FetchRequest(request) => {
4872            dispatch_fetch_request(
4873                *source,
4874                request,
4875                ctx,
4876                msg.request_id,
4877                received_at,
4878                rr_message_id,
4879            )
4880            .await
4881        }
4882        ReplicationMessageBody::AuditChallenge(challenge) => {
4883            // Responsible-chunk audit (audit #2) responder: answer with per-key
4884            // possession digests. This same handler also answers the
4885            // prune-confirmation audit, which sends the same `AuditChallenge`
4886            // wire message.
4887            //
4888            // Answering digests the stored bytes of every challenged key, so —
4889            // like the subtree/byte audits below — run it on a detached task off
4890            // this serial message loop. Handling it inline lets one challenge
4891            // block all other replication traffic until its digests complete
4892            // (head-of-line blocking). The same flood-fair admission applies: a
4893            // global ceiling AND a per-peer cap, dropping the challenge if either
4894            // is hit. A dropped challenge reads as a penalised timeout to the
4895            // auditor, so the caps must remain high enough for honest audit load;
4896            // the per-peer share still prevents one flooder from starving others.
4897            let class = AuditResponderClass::Digest;
4898            let guard = match admit_audit_responder(
4899                &ctx.audit_responder_semaphore,
4900                &ctx.audit_responder_inflight,
4901                source,
4902                class,
4903            )
4904            .await
4905            {
4906                Ok(guard) => guard,
4907                Err(failure) => {
4908                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4909                    audit_metrics::record_admission_drop(class);
4910                    ctx.audit_responder_metrics
4911                        .record_drop(*source, failure.reason.into());
4912                    warn!(
4913                        target: "ant_node::replication::audit_responder",
4914                        event = "admission_dropped",
4915                        kind = "responsible",
4916                        responder_class = class.as_str(),
4917                        source = %source,
4918                        challenge_id = challenge.challenge_id,
4919                        key_count = challenge.keys.len(),
4920                        request_response = rr_message_id.is_some(),
4921                        dispatch_ms = received_at.elapsed().as_millis(),
4922                        reason = failure.reason.as_str(),
4923                        global_inflight = failure.global_inflight,
4924                        global_limit = failure.global_limit,
4925                        peer_inflight = failure.peer_inflight,
4926                        peer_limit = failure.peer_limit,
4927                        "Audit responder admission dropped"
4928                    );
4929                    return Ok(());
4930                }
4931            };
4932            let admission_global_inflight = guard.global_inflight;
4933            let admission_peer_inflight = guard.peer_inflight;
4934            ctx.audit_responder_metrics.record_admitted(
4935                *source,
4936                admission_global_inflight,
4937                admission_peer_inflight,
4938            );
4939            info!(
4940                target: "ant_node::replication::audit_responder",
4941                event = "admitted",
4942                kind = "responsible",
4943                responder_class = class.as_str(),
4944                source = %source,
4945                challenge_id = challenge.challenge_id,
4946                key_count = challenge.keys.len(),
4947                request_response = rr_message_id.is_some(),
4948                dispatch_ms = received_at.elapsed().as_millis(),
4949                global_inflight = admission_global_inflight,
4950                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4951                peer_inflight = admission_peer_inflight,
4952                peer_limit = class.per_peer_limit(),
4953                "Audit responder request admitted"
4954            );
4955            let bootstrapping = *ctx.is_bootstrapping.read().await;
4956            let dispatch_latency = received_at.elapsed();
4957            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4958            debug!(
4959                audit_type = "digest_responder",
4960                dispatch_latency_ms = dispatch_latency.as_millis(),
4961                source = %source,
4962                "Audit challenge dispatch latency measured"
4963            );
4964            let storage = Arc::clone(&ctx.storage);
4965            let p2p_node = Arc::clone(&ctx.p2p_node);
4966            let source = *source;
4967            let request_id = msg.request_id;
4968            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
4969            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
4970            ctx.detached_task_tracker.spawn(async move {
4971                let _guard = guard; // global permit + per-peer slot, held until done
4972                let worker_started = Instant::now();
4973                match handle_audit_challenge_msg(
4974                    &source,
4975                    &challenge,
4976                    &storage,
4977                    &p2p_node,
4978                    bootstrapping,
4979                    ReplyRoute {
4980                        request_id,
4981                        rr_message_id: rr_message_id.as_deref(),
4982                        protocol: REPLICATION_PROTOCOL_ID,
4983                    },
4984                )
4985                .await
4986                {
4987                    Ok(completion) => log_audit_responder_completion(
4988                        &responder_metrics,
4989                        source,
4990                        class,
4991                        "responsible",
4992                        challenge.challenge_id,
4993                        challenge.keys.len(),
4994                        completion.response_kind,
4995                        completion.sent,
4996                        received_at,
4997                        worker_started,
4998                        completion.processing,
4999                        completion.response_send,
5000                    ),
5001                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5002                }
5003            });
5004            Ok(())
5005        }
5006        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5007            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5008            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5009            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5010            // detached task so this serial message loop is never blocked on disk
5011            // I/O — otherwise one audit stalls all replication traffic (§5).
5012            //
5013            // A bounded, flood-fair admission restores backpressure (codex#1 +
5014            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5015            // we drop this challenge. Subtree auditors grace timeout
5016            // non-responses, so capacity drops throttle flooders without turning
5017            // into trust penalties (and one source cannot starve other peers,
5018            // since its share is capped per-peer).
5019            let class = AuditResponderClass::Subtree;
5020            info!(
5021                "Audit challenge received: kind=subtree source={source} request_response={}",
5022                rr_message_id.is_some(),
5023            );
5024            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5025            // so it uses its own tight admission pool + per-peer rate cooldown,
5026            // separate from the light responsible/slice audits, and a miss silently
5027            // drops (subtree auditors grace timeouts).
5028            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5029                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5030                warn!(
5031                    target: "ant_node::replication::audit_responder",
5032                    event = "admission_dropped",
5033                    kind = "subtree",
5034                    responder_class = class.as_str(),
5035                    source = %source,
5036                    challenge_id = challenge.challenge_id,
5037                    request_response = rr_message_id.is_some(),
5038                    dispatch_ms = received_at.elapsed().as_millis(),
5039                    reason = "heavy_pool_cooldown_or_work_budget",
5040                    "Audit responder admission dropped"
5041                );
5042                return Ok(());
5043            };
5044            let admission_global_inflight = guard.global_inflight;
5045            let admission_peer_inflight = guard.peer_inflight;
5046            ctx.audit_responder_metrics.record_admitted(
5047                *source,
5048                admission_global_inflight,
5049                admission_peer_inflight,
5050            );
5051            info!(
5052                target: "ant_node::replication::audit_responder",
5053                event = "admitted",
5054                kind = "subtree",
5055                responder_class = class.as_str(),
5056                source = %source,
5057                challenge_id = challenge.challenge_id,
5058                request_response = rr_message_id.is_some(),
5059                dispatch_ms = received_at.elapsed().as_millis(),
5060                global_inflight = admission_global_inflight,
5061                global_limit = ctx.subtree_round1.max_concurrent,
5062                peer_inflight = admission_peer_inflight,
5063                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5064                "Audit responder request admitted"
5065            );
5066            let bootstrapping = *ctx.is_bootstrapping.read().await;
5067            let storage = Arc::clone(&ctx.storage);
5068            let p2p_node = Arc::clone(&ctx.p2p_node);
5069            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5070            let source = *source;
5071            let request_id = msg.request_id;
5072            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5073            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5074            let subtree_round1 = ctx.subtree_round1.clone();
5075            ctx.detached_task_tracker.spawn(async move {
5076                let _guard = guard; // global permit + per-peer slot, held until done
5077                let worker_started = Instant::now();
5078                let processing_started = Instant::now();
5079                let storage_commitment_audit::Round1Work {
5080                    response,
5081                    content_bytes,
5082                } = storage_commitment_audit::handle_subtree_challenge_measured(
5083                    &challenge,
5084                    &storage,
5085                    p2p_node.peer_id(),
5086                    bootstrapping,
5087                    Some(&my_commitment_state),
5088                )
5089                .await;
5090                let processing = processing_started.elapsed();
5091                // Charge the work actually done, on EVERY outcome.
5092                //
5093                // This used to charge only the `Proof` arm, reasoning that the
5094                // rejecting paths either read nothing or reflected this node's
5095                // own broken storage. The second half of that was wrong: a
5096                // retained commitment containing one unreadable key still costs
5097                // a full run of reads and keyed-BLAKE3 passes over every leaf
5098                // before it, and then rejects. An attacker who finds such a
5099                // commitment could replay subtrees over it indefinitely for
5100                // free. The per-peer cooldown does not catch that either, since
5101                // it is escapable by rotating identity — the responder-wide
5102                // budget is the only bound that applies, so it has to see the
5103                // work. A zero charge is a no-op, so the untouched paths are
5104                // unaffected.
5105                subtree_round1.charge_work(content_bytes).await;
5106                // A round-1 proof authorizes exactly one matching round 2: open a
5107                // single-use session so a slice challenge cannot be served without
5108                // a live round-1 exchange.
5109                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5110                {
5111                    subtree_round1
5112                        .open_session(
5113                            source,
5114                            challenge.challenge_id,
5115                            challenge.expected_commitment_hash,
5116                            challenge.nonce,
5117                        )
5118                        .await;
5119                }
5120                let response_kind = subtree_audit_response_kind(&response);
5121                let work_items = subtree_audit_response_work_items(&response);
5122                let response_send_started = Instant::now();
5123                let sent = send_replication_response_checked(
5124                    &source,
5125                    &p2p_node,
5126                    request_id,
5127                    ReplicationMessageBody::SubtreeAuditResponse(response),
5128                    rr_message_id.as_deref(),
5129                    None,
5130                )
5131                .await;
5132                let response_send = response_send_started.elapsed();
5133                log_audit_responder_completion(
5134                    &responder_metrics,
5135                    source,
5136                    class,
5137                    "subtree",
5138                    challenge.challenge_id,
5139                    work_items,
5140                    response_kind,
5141                    sent,
5142                    received_at,
5143                    worker_started,
5144                    processing,
5145                    response_send,
5146                );
5147            });
5148            Ok(())
5149        }
5150        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5151            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5152            // block of each auditor-selected spot-check key with a Bao verified
5153            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5154            // build the proofs, so it runs off the serial loop under the light
5155            // audit pool's global and per-peer ceilings.
5156            let class = AuditResponderClass::Byte;
5157            info!(
5158                "Audit challenge received: kind=slice source={source} request_response={}",
5159                rr_message_id.is_some(),
5160            );
5161            let guard = match admit_slice_challenge(
5162                &ctx.audit_responder_semaphore,
5163                &ctx.audit_responder_inflight,
5164                &ctx.subtree_round1,
5165                source,
5166                &challenge,
5167            )
5168            .await
5169            {
5170                SliceAdmission::Admitted(guard) => guard,
5171                SliceAdmission::Capacity(failure) => {
5172                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5173                    audit_metrics::record_admission_drop(class);
5174                    ctx.audit_responder_metrics
5175                        .record_drop(*source, failure.reason.into());
5176                    warn!(
5177                        target: "ant_node::replication::audit_responder",
5178                        event = "admission_dropped",
5179                        kind = "byte",
5180                        responder_class = class.as_str(),
5181                        source = %source,
5182                        challenge_id = challenge.challenge_id,
5183                        key_count = challenge.openings.len(),
5184                        request_response = rr_message_id.is_some(),
5185                        dispatch_ms = received_at.elapsed().as_millis(),
5186                        reason = failure.reason.as_str(),
5187                        global_inflight = failure.global_inflight,
5188                        global_limit = failure.global_limit,
5189                        peer_inflight = failure.peer_inflight,
5190                        peer_limit = failure.peer_limit,
5191                        "Audit responder admission dropped"
5192                    );
5193                    return Ok(());
5194                }
5195                // No live round-1 session: reply with a cheap `Transient` rejection
5196                // rather than dropping silently. Sessions are ephemeral (an honest
5197                // responder that restarts between rounds loses its session), and an
5198                // unanswered `send_request` would make saorsa-core record a
5199                // transport trust failure against that honest responder — an
5200                // ongoing effect, not just a rollout-window one. A `Transient`
5201                // reply routes the auditor to the graced timeout lane (no trust
5202                // penalty; the responder re-earns pinned credit on the next audit)
5203                // and does no chunk work, so it is not a DoS lever.
5204                SliceAdmission::NoSession => {
5205                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5206                    debug!(
5207                        "Slice challenge without a live round-1 session source={source} \
5208                         challenge_id={} → Transient reject",
5209                        challenge.challenge_id
5210                    );
5211                    send_replication_response_checked(
5212                        source,
5213                        &ctx.p2p_node,
5214                        msg.request_id,
5215                        ReplicationMessageBody::SubtreeSliceResponse(
5216                            protocol::SubtreeSliceResponse::Rejected {
5217                                challenge_id: challenge.challenge_id,
5218                                kind: protocol::RejectKind::Transient,
5219                                reason: "no live round-1 session".to_string(),
5220                            },
5221                        ),
5222                        rr_message_id,
5223                        None,
5224                    )
5225                    .await;
5226                    return Ok(());
5227                }
5228            };
5229            let admission_global_inflight = guard.global_inflight;
5230            let admission_peer_inflight = guard.peer_inflight;
5231            ctx.audit_responder_metrics.record_admitted(
5232                *source,
5233                admission_global_inflight,
5234                admission_peer_inflight,
5235            );
5236            info!(
5237                target: "ant_node::replication::audit_responder",
5238                event = "admitted",
5239                kind = "byte",
5240                responder_class = class.as_str(),
5241                source = %source,
5242                challenge_id = challenge.challenge_id,
5243                key_count = challenge.openings.len(),
5244                request_response = rr_message_id.is_some(),
5245                dispatch_ms = received_at.elapsed().as_millis(),
5246                global_inflight = admission_global_inflight,
5247                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5248                peer_inflight = admission_peer_inflight,
5249                peer_limit = class.per_peer_limit(),
5250                "Audit responder request admitted"
5251            );
5252            let bootstrapping = *ctx.is_bootstrapping.read().await;
5253            let storage = Arc::clone(&ctx.storage);
5254            let p2p_node = Arc::clone(&ctx.p2p_node);
5255            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5256            let source = *source;
5257            let request_id = msg.request_id;
5258            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5259            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5260            ctx.detached_task_tracker.spawn(async move {
5261                let _guard = guard; // global permit + per-peer slot, held until done
5262                let worker_started = Instant::now();
5263                let processing_started = Instant::now();
5264                let response = storage_commitment_audit::handle_subtree_slice_challenge(
5265                    &challenge,
5266                    &storage,
5267                    p2p_node.peer_id(),
5268                    bootstrapping,
5269                    Some(&my_commitment_state),
5270                )
5271                .await;
5272                let processing = processing_started.elapsed();
5273                let response_kind = subtree_slice_response_kind(&response);
5274                let response_send_started = Instant::now();
5275                let sent = send_replication_response_checked(
5276                    &source,
5277                    &p2p_node,
5278                    request_id,
5279                    ReplicationMessageBody::SubtreeSliceResponse(response),
5280                    rr_message_id.as_deref(),
5281                    None,
5282                )
5283                .await;
5284                let response_send = response_send_started.elapsed();
5285                log_audit_responder_completion(
5286                    &responder_metrics,
5287                    source,
5288                    class,
5289                    "byte",
5290                    challenge.challenge_id,
5291                    challenge.openings.len(),
5292                    response_kind,
5293                    sent,
5294                    received_at,
5295                    worker_started,
5296                    processing,
5297                    response_send,
5298                );
5299            });
5300            Ok(())
5301        }
5302        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5303            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5304            // only. `lookup_by_hash` is an allocation-light read over the
5305            // bounded slot set; it returns the live current commitment or any
5306            // still-answerable recently-gossiped/quoted one. A miss is reported
5307            // as `NotRetained` (graced, never confirmed) rather than an error,
5308            // so an aged-out pin can never brand an honest node.
5309            //
5310            // Reuse the audit-responder admission guard (global ceiling + per-peer
5311            // cap) so a flood of fetches cannot drive unbounded commitment
5312            // clone/encode/send work; over-limit is dropped, which the fetching
5313            // peer graces exactly like a missed audit response.
5314            let class = AuditResponderClass::CommitmentPin;
5315            let guard = match admit_audit_responder(
5316                &ctx.audit_responder_semaphore,
5317                &ctx.audit_responder_inflight,
5318                source,
5319                class,
5320            )
5321            .await
5322            {
5323                Ok(guard) => guard,
5324                Err(failure) => {
5325                    audit_metrics::record_admission_drop(class);
5326                    ctx.audit_responder_metrics
5327                        .record_drop(*source, failure.reason.into());
5328                    warn!(
5329                        target: "ant_node::replication::audit_responder",
5330                        event = "admission_dropped",
5331                        kind = "commitment_pin",
5332                        responder_class = class.as_str(),
5333                        source = %source,
5334                        challenge_id = msg.request_id,
5335                        request_response = rr_message_id.is_some(),
5336                        dispatch_ms = received_at.elapsed().as_millis(),
5337                        reason = failure.reason.as_str(),
5338                        global_inflight = failure.global_inflight,
5339                        global_limit = failure.global_limit,
5340                        peer_inflight = failure.peer_inflight,
5341                        peer_limit = failure.peer_limit,
5342                        "Audit responder admission dropped"
5343                    );
5344                    return Ok(());
5345                }
5346            };
5347            ctx.audit_responder_metrics.record_admitted(
5348                *source,
5349                guard.global_inflight,
5350                guard.peer_inflight,
5351            );
5352            info!(
5353                target: "ant_node::replication::audit_responder",
5354                event = "admitted",
5355                kind = "commitment_pin",
5356                responder_class = class.as_str(),
5357                source = %source,
5358                challenge_id = msg.request_id,
5359                request_response = rr_message_id.is_some(),
5360                dispatch_ms = received_at.elapsed().as_millis(),
5361                global_inflight = guard.global_inflight,
5362                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5363                peer_inflight = guard.peer_inflight,
5364                peer_limit = class.per_peer_limit(),
5365                "Audit responder request admitted"
5366            );
5367            let worker_started = Instant::now();
5368            let processing_started = Instant::now();
5369            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5370                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5371                |built| protocol::GetCommitmentByPinResponse::Found {
5372                    commitment: built.commitment().clone(),
5373                },
5374            );
5375            let processing = processing_started.elapsed();
5376            let response_kind = commitment_pin_response_kind(&response);
5377            let response_send_started = Instant::now();
5378            let sent = send_replication_response_checked(
5379                source,
5380                &ctx.p2p_node,
5381                msg.request_id,
5382                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5383                rr_message_id,
5384                None,
5385            )
5386            .await;
5387            let response_send = response_send_started.elapsed();
5388            log_audit_responder_completion(
5389                &ctx.audit_responder_metrics,
5390                *source,
5391                class,
5392                "commitment_pin",
5393                msg.request_id,
5394                1,
5395                response_kind,
5396                sent,
5397                received_at,
5398                worker_started,
5399                processing,
5400                response_send,
5401            );
5402            drop(guard);
5403            Ok(())
5404        }
5405        // Response messages are handled by their respective request initiators.
5406        ReplicationMessageBody::FreshReplicationResponse(_)
5407        | ReplicationMessageBody::NeighborSyncResponse(_)
5408        | ReplicationMessageBody::VerificationResponse(_)
5409        | ReplicationMessageBody::FetchResponse(_)
5410        | ReplicationMessageBody::AuditResponse(_)
5411        | ReplicationMessageBody::SubtreeAuditResponse(_)
5412        | ReplicationMessageBody::SubtreeSliceResponse(_)
5413        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5414    }
5415}
5416
5417// ---------------------------------------------------------------------------
5418// Per-message-type handlers
5419// ---------------------------------------------------------------------------
5420
5421/// Verify a payment proof, yielding early if the engine is shutting down.
5422///
5423/// Returns `None` when shutdown won the race, meaning no verdict was reached
5424/// and the caller must abandon the message without storing or penalising.
5425///
5426/// Payment verification is pure network I/O — an EVM round trip and, on the
5427/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5428/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5429/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5430/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5431/// is guaranteed to end.
5432///
5433/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5434/// dropping its awaiter would detach a live LMDB transaction and break the
5435/// very contract the unbounded wait exists to uphold.
5436async fn verify_payment_until_shutdown(
5437    payment_verifier: &Arc<PaymentVerifier>,
5438    key: &XorName,
5439    proof_of_payment: &[u8],
5440    context: VerificationContext,
5441    shutdown: &CancellationToken,
5442) -> Option<Result<crate::payment::PaymentStatus>> {
5443    tokio::select! {
5444        () = shutdown.cancelled() => None,
5445        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5446            Some(result)
5447        }
5448    }
5449}
5450
5451/// A fresh offer rejected on payload shape alone.
5452struct FreshOfferRejection {
5453    /// Wire-visible reason returned to the sender.
5454    reason: String,
5455    /// Whether the sender is charged for it. Reserved for offers no honest
5456    /// node would construct, so an ordinary capacity refusal stays free.
5457    penalise: bool,
5458}
5459
5460/// Reject a fresh offer on payload shape, or return `None` to admit it.
5461///
5462/// Pure and non-blocking by construction: these are the checks answerable from
5463/// the payload alone, run on the serial message loop *before* the in-flight
5464/// claim and the admission permit, so a malformed offer can neither lock an
5465/// honest offer out of its key nor occupy one of the scarce
5466/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5467/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5468/// verification — stays on the worker.
5469///
5470/// The content-address hash is deliberately included despite costing real CPU
5471/// on the loop: it is what makes the entry below *earned* rather than merely
5472/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5473/// arrive at link speed, so a flooder can never make this loop hash faster than
5474/// it can deliver the bytes, and delivering them already cost it more than the
5475/// hash costs us. The receive path has in any case already deserialised the
5476/// same buffer.
5477///
5478/// Every rejection here is penalised. These are the conditions no honest sender
5479/// can produce — an absent, undersized, oversized, or non-matching payload — as
5480/// distinct from a capacity refusal, which is this node's own state and stays
5481/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5482/// proof that fails to verify may simply have been read against a lagging chain
5483/// view, and penalising that would charge honest senders in correlated bursts.
5484fn fresh_offer_structural_rejection(
5485    key: &XorName,
5486    data: &[u8],
5487    proof_of_payment: &[u8],
5488) -> Option<FreshOfferRejection> {
5489    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5490    // and an absent proof is the cheapest possible slot-filler, so this is the
5491    // first thing checked.
5492    if proof_of_payment.is_empty() {
5493        return Some(FreshOfferRejection {
5494            reason: "Missing proof of payment".to_string(),
5495            penalise: true,
5496        });
5497    }
5498
5499    // Bound the proof before it can be queued. The verifier applies the same
5500    // limits, but only once the offer reaches a worker — too late here, because
5501    // an entry retains a proof per queued sender, and a proof is capped on the
5502    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5503    // a byte of data and a 10 MiB "proof" would be admitted, and
5504    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5505    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5506    // admission bound exists to enforce.
5507    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5508        return Some(FreshOfferRejection {
5509            reason: format!(
5510                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5511                proof_of_payment.len(),
5512            ),
5513            penalise: true,
5514        });
5515    }
5516    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5517        return Some(FreshOfferRejection {
5518            reason: format!(
5519                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5520                proof_of_payment.len(),
5521            ),
5522            penalise: true,
5523        });
5524    }
5525
5526    // Enforce chunk size invariant: the normal PUT path rejects data larger
5527    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5528    // prevent peers from pushing oversized records through replication.
5529    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5530        return Some(FreshOfferRejection {
5531            reason: format!(
5532                "Data size {} exceeds maximum chunk size {}",
5533                data.len(),
5534                crate::ant_protocol::MAX_CHUNK_SIZE,
5535            ),
5536            penalise: true,
5537        });
5538    }
5539
5540    // Mirror the normal PUT path: the advertised key must be the content
5541    // address of the supplied bytes. Ordered last so an oversized payload is
5542    // refused without being hashed.
5543    //
5544    // This is the check that makes the entry safe to open, and safe for later
5545    // offers to be folded into. Until it passes, the sender has only *asserted*
5546    // an association between the key and the bytes. Opening an entry on an
5547    // assertion would let any peer that knows a key — every recipient of its
5548    // `PaidNotify`, not just the close group — seize it with junk; folding a
5549    // later offer into an entry on an assertion would be worse still, since the
5550    // handler tries each queued proof against the *opener's* bytes and would be
5551    // storing bytes nobody offered for that proof.
5552    let computed_key = crate::client::compute_address(data);
5553    if computed_key != *key {
5554        return Some(FreshOfferRejection {
5555            reason: format!(
5556                "Content address mismatch: expected {}, computed {}",
5557                hex::encode(key),
5558                hex::encode(computed_key),
5559            ),
5560            penalise: true,
5561        });
5562    }
5563
5564    None
5565}
5566
5567/// Tell `source` its offer for `key` was not taken.
5568///
5569/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5570/// one-way `send_message`, so the refusal is observed only as a later absence by
5571/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5572async fn refuse_fresh_offer(
5573    source: &PeerId,
5574    key: XorName,
5575    reason: String,
5576    ctx: &ReplicationMessageHandlerContext,
5577    request_id: u64,
5578    rr_message_id: Option<&str>,
5579) {
5580    send_replication_response(
5581        source,
5582        &ctx.p2p_node,
5583        request_id,
5584        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5585            key,
5586            reason,
5587        }),
5588        rr_message_id,
5589    )
5590    .await;
5591}
5592
5593/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5594/// the sender when the defect is one no honest node could produce.
5595///
5596/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5597/// two say opposite things: this is the sender's fault, that one is ours.
5598async fn refuse_malformed_fresh_offer(
5599    source: &PeerId,
5600    key: XorName,
5601    rejection: FreshOfferRejection,
5602    ctx: &ReplicationMessageHandlerContext,
5603    request_id: u64,
5604    rr_message_id: Option<&str>,
5605) {
5606    if rejection.penalise {
5607        warn!(
5608            "Rejecting fresh offer for key {} from {source}: {}",
5609            hex::encode(key),
5610            rejection.reason
5611        );
5612        ctx.p2p_node
5613            .report_trust_event(
5614                source,
5615                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5616            )
5617            .await;
5618    } else {
5619        debug!(
5620            "Fresh offer for {} from {source} refused before admission: {}",
5621            hex::encode(key),
5622            rejection.reason
5623        );
5624    }
5625    refuse_fresh_offer(
5626        source,
5627        key,
5628        rejection.reason,
5629        ctx,
5630        request_id,
5631        rr_message_id,
5632    )
5633    .await;
5634}
5635
5636/// Tell senders whose proofs joined an entry that was torn down before a handler
5637/// ever ran for it.
5638///
5639/// Only reachable in the window between opening an entry and failing to take an
5640/// admission permit. Their proofs are answered rather than dropped with the
5641/// entry, so the refusal count reflects what actually happened.
5642async fn refuse_stranded_fresh_offers(
5643    key: XorName,
5644    stranded: Vec<FreshOfferAttempt>,
5645    ctx: &ReplicationMessageHandlerContext,
5646) {
5647    for attempt in stranded {
5648        refuse_fresh_offer(
5649            &attempt.source,
5650            key,
5651            "Receiver at fresh-offer capacity".to_string(),
5652            ctx,
5653            attempt.request_id,
5654            attempt.rr_message_id.as_deref(),
5655        )
5656        .await;
5657    }
5658}
5659
5660/// Admit a fresh offer for handling on a worker, or refuse it.
5661///
5662/// This runs on the serial non-audit message loop, so it must stay cheap: every
5663/// path here is a set insert, a permit try, or a small response send. The offer
5664/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5665/// runs on a tracked worker task, never inline, because stalling this loop backs
5666/// up the inbound queue and ultimately drops replication messages wholesale.
5667///
5668/// Admission is bounded **per source** as well as globally
5669/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5670/// hold every slot, and since a refusal is later read as absence by the
5671/// sender's delayed possession check, the resulting refusals land as
5672/// audit-severity penalties on this node rather than on the flooder.
5673///
5674/// The structurally-invalid checks run **before** the entry is opened and before
5675/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5676/// the duration of a payment verification.
5677///
5678/// Only the offer that *opens* an entry costs a permit and a worker. Later
5679/// offers for the same key contribute their proof and are answered by whatever
5680/// the opener's handler concludes, which is what keeps the routine
5681/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5682/// one verification per key.
5683async fn dispatch_fresh_offer(
5684    source: PeerId,
5685    offer: protocol::FreshReplicationOffer,
5686    ctx: &ReplicationMessageHandlerContext,
5687    request_id: u64,
5688    received_at: Instant,
5689    rr_message_id: Option<&str>,
5690) -> Result<()> {
5691    if let Some(rejection) =
5692        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5693    {
5694        refuse_malformed_fresh_offer(
5695            &source,
5696            offer.key,
5697            rejection,
5698            ctx,
5699            request_id,
5700            rr_message_id,
5701        )
5702        .await;
5703        return Ok(());
5704    }
5705
5706    // Join the work already in flight for this key before taking an admission
5707    // permit, so the duplicates a single client PUT produces cost one permit
5708    // between them rather than one each.
5709    //
5710    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5711    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5712    // already held for the key. That is what lets its payload be dropped here
5713    // and only its proof retained: the handler will try that proof against the
5714    // bytes it already has.
5715    let key = offer.key;
5716    let admission_outcome = FreshOfferEntryGuard::admit(
5717        &ctx.fresh_offer_in_flight,
5718        offer,
5719        source,
5720        request_id,
5721        rr_message_id.map(ToOwned::to_owned),
5722        received_at,
5723    );
5724    let mut entry = match admission_outcome {
5725        FreshOfferAdmission::Opened(entry) => entry,
5726        FreshOfferAdmission::Joined => {
5727            // No response yet: this proof has not been judged. The handler that
5728            // owns the key answers every queued sender once it settles.
5729            debug!(
5730                "Fresh offer for {} from {source} queued behind the handler already \
5731                 holding the key",
5732                hex::encode(key)
5733            );
5734            return Ok(());
5735        }
5736        // Surplus, not suspect: the proofs already queued are enough to place
5737        // the record, so neither case is charged as misbehaviour.
5738        surplus => {
5739            debug!(
5740                "Fresh offer for {} from {source} refused: {}",
5741                hex::encode(key),
5742                surplus.surplus_reason()
5743            );
5744            refuse_fresh_offer(
5745                &source,
5746                key,
5747                "Duplicate offer already in flight".to_string(),
5748                ctx,
5749                request_id,
5750                rr_message_id,
5751            )
5752            .await;
5753            return Ok(());
5754        }
5755    };
5756
5757    let admission = match admit_bounded_responder(
5758        &ctx.fresh_offer_admission_semaphore,
5759        &ctx.fresh_offer_responder_inflight,
5760        &source,
5761        FRESH_OFFER_MAX_OUTSTANDING,
5762        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5763    )
5764    .await
5765    {
5766        Ok(guard) => guard,
5767        Err(failure) => {
5768            audit_metrics::record_responder_admission_drop(
5769                ReplicationResponderClass::FreshOffer,
5770                failure.reason.into(),
5771            );
5772            // WARN, not DEBUG: a healthy node should never refuse a legitimate
5773            // fresh offer. The sender does not read this refusal, so it
5774            // resurfaces as a missing key at the delayed possession check and
5775            // is charged to US at audit severity. Log the binding ceiling
5776            // locally; the wire reason stays generic so a probing peer cannot
5777            // map out this node's live occupancy.
5778            warn!(
5779                responder_class = "fresh_offer",
5780                source = %source,
5781                key = %hex::encode(key),
5782                "Fresh offer refused at admission — this node will be penalised                  for the resulting absence: {failure}"
5783            );
5784            // Release the key explicitly rather than on drop, so the next offer
5785            // opens a fresh entry rather than queueing behind a handler that was
5786            // never spawned — and so any proof that joined in the window between
5787            // opening the entry and failing here is answered rather than
5788            // discarded with it.
5789            let stranded = entry.release();
5790            refuse_fresh_offer(
5791                &source,
5792                key,
5793                "Receiver at fresh-offer capacity".to_string(),
5794                ctx,
5795                request_id,
5796                rr_message_id,
5797            )
5798            .await;
5799            refuse_stranded_fresh_offers(key, stranded, ctx).await;
5800            return Ok(());
5801        }
5802    };
5803
5804    let ctx = ctx.clone();
5805    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5806    // an `Arc<LmdbStorage>` while writing, and the shutdown contract requires
5807    // those references be released before the caller reopens the environment.
5808    ctx.detached_task_tracker
5809        .clone()
5810        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5811    Ok(())
5812}
5813
5814/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5815///
5816/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5817/// A started handler is never cancelled: `storage.put()` awaits
5818/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5819/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5820/// and from `handle_fresh_offer` racing the token around payment verification.
5821///
5822/// Works down the key's queued proofs rather than judging the key on the first
5823/// one. A proof that fails to establish payment disqualifies its *sender*, not
5824/// the record: the bytes are content-addressed and identical across every offer,
5825/// so the next sender's proof is tried against the copy already in hand — no
5826/// second payload, no second permit, no refetch. Only when a failure is about
5827/// the key itself (not responsible, no capacity, shutting down) does rotating
5828/// become pointless, because every remaining proof would meet the same wall.
5829async fn run_fresh_offer_worker(
5830    key: XorName,
5831    mut entry: Box<FreshOfferEntryGuard>,
5832    ctx: ReplicationMessageHandlerContext,
5833    admission: ResponderGuard,
5834) {
5835    // The admission permit is released on completion, freeing the payload's
5836    // memory budget and the opening source's per-peer share. The entry releases
5837    // the key itself, either as the queue empties or on drop.
5838    let _admission = admission;
5839    let received_at = entry.received_at();
5840    // Wait for a worker slot here rather than in the caller. The worker bound
5841    // caps concurrent EVM and storage pressure; making the message loop wait on
5842    // it is what put that pressure back on the loop.
5843    //
5844    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5845    // path for offers still queued behind a worker when the engine stops — not
5846    // dead code.
5847    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5848        .acquire_owned()
5849        .await
5850    else {
5851        debug!(
5852            "Fresh offer for {} dropped: worker pool shut down",
5853            hex::encode(key)
5854        );
5855        return;
5856    };
5857    // Fresh offers are fire-and-forget (`send_message`), so there is no
5858    // requester deadline to honour and a late store is still genuinely useful.
5859    // The threshold is the point past which the offer has already cost us what
5860    // it was going to cost: the possession check (ADR-0003) has run by then and
5861    // charged the absence to this node, and it does not re-offer the key —
5862    // repair comes later from neighbor sync. Shedding here trades a copy that
5863    // would have arrived after the penalty for the multi-MiB payload it is
5864    // holding, and keeps a backlog from outliving its own admission bound.
5865    //
5866    // Note this is a memory-pressure decision, not a redundancy one: the copy
5867    // is late, not useless, so on a node with headroom finishing it would still
5868    // beat waiting for neighbor sync.
5869    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5870        debug!(
5871            responder_class = "fresh_offer",
5872            key = %hex::encode(key),
5873            request_age_ms = received_at.elapsed().as_millis(),
5874            "Superseded fresh offer shed at dequeue"
5875        );
5876        return;
5877    }
5878
5879    let mut verdict = FreshOfferOutcome::Abandoned;
5880    while let Some(attempt) = entry.next_attempt() {
5881        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5882            Ok(outcome) => {
5883                verdict = outcome;
5884                match outcome {
5885                    // Settled: the record is down and every remaining sender
5886                    // wanted exactly that. Abandoned: the key cannot be placed
5887                    // by anyone right now, so the proofs behind this one would
5888                    // fail identically. Either way there is nothing left to try.
5889                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5890                    // This sender's claim to have paid did not hold up. Say so
5891                    // to that sender alone and try the next proof.
5892                    FreshOfferOutcome::ProofRejected => {}
5893                }
5894            }
5895            Err(e) => {
5896                debug!(
5897                    "Fresh replication offer for {} from {} error: {e}",
5898                    hex::encode(key),
5899                    attempt.source
5900                );
5901                verdict = FreshOfferOutcome::Abandoned;
5902                break;
5903            }
5904        }
5905    }
5906
5907    // Answer the senders whose proofs were never reached. A stored record is
5908    // what they were asking for, so it is an acceptance even though their own
5909    // proof went untested.
5910    let unreached = entry.release();
5911    if unreached.is_empty() {
5912        return;
5913    }
5914    let response = match verdict {
5915        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5916        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5917            FreshReplicationResponse::Rejected {
5918                key,
5919                reason: "Record could not be stored from any offered proof".to_string(),
5920            }
5921        }
5922    };
5923    for attempt in unreached {
5924        send_replication_response(
5925            &attempt.source,
5926            &ctx.p2p_node,
5927            attempt.request_id,
5928            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5929            attempt.rr_message_id.as_deref(),
5930        )
5931        .await;
5932    }
5933}
5934
5935/// What one proof concluded, and whether another proof for the same key is worth
5936/// trying.
5937///
5938/// The distinction the worker acts on is *what the failure was about*. A
5939/// rejected proof is a statement about its sender; anything else is a statement
5940/// about the key or this node, which no other sender's proof can change.
5941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5942enum FreshOfferOutcome {
5943    /// The record is stored. The key is done.
5944    Settled,
5945    /// This proof did not establish payment. A different sender's proof for the
5946    /// same bytes may still succeed.
5947    ProofRejected,
5948    /// Nothing about this key can succeed right now — not responsible, no disk,
5949    /// shutting down, or a write that failed. Rotating repeats the failure.
5950    Abandoned,
5951}
5952
5953// A linear sequence of protocol steps — structural recheck, responsibility,
5954// capacity, payment, write — each with its own refusal response. Splitting it
5955// would scatter one decision across several functions.
5956#[allow(clippy::too_many_lines)]
5957async fn handle_fresh_offer(
5958    key: &XorName,
5959    data: &[u8],
5960    attempt: &FreshOfferAttempt,
5961    ctx: &ReplicationMessageHandlerContext,
5962) -> Result<FreshOfferOutcome> {
5963    let source = &attempt.source;
5964    let request_id = attempt.request_id;
5965    let rr_message_id = attempt.rr_message_id.as_deref();
5966    let p2p_node = &ctx.p2p_node;
5967    let config = &ctx.config;
5968    let self_id = *p2p_node.peer_id();
5969
5970    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
5971    // proof, bad proof size, oversized payload, content-address mismatch —
5972    // before opening the entry or taking an admission permit, so nothing
5973    // reaching a worker should trip them. Kept so the handler is correct in
5974    // isolation. Note this re-checks the *pairing* actually being used: these
5975    // bytes against this attempt's proof.
5976    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
5977    {
5978        if rejection.penalise {
5979            warn!(
5980                "Rejecting fresh offer for key {}: {}",
5981                hex::encode(key),
5982                rejection.reason
5983            );
5984            p2p_node
5985                .report_trust_event(
5986                    source,
5987                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5988                )
5989                .await;
5990        }
5991        send_replication_response(
5992            source,
5993            p2p_node,
5994            request_id,
5995            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5996                key: *key,
5997                reason: rejection.reason,
5998            }),
5999            rr_message_id,
6000        )
6001        .await;
6002        // Structurally invalid is a fact about this attempt, not the key.
6003        return Ok(FreshOfferOutcome::ProofRejected);
6004    }
6005
6006    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6007    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6008    // the same width client PUTs use), not just the close group plus a small
6009    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6010    // table may still list closer full nodes it hasn't evicted yet, ranking it
6011    // outside the narrow window in its own view; the wider accept window absorbs
6012    // that transient skew so the chunk still lands. Retention (pruning) stays at
6013    // `storage_admission_width`, so steady-state replication is unchanged.
6014    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6015    {
6016        send_replication_response(
6017            source,
6018            p2p_node,
6019            request_id,
6020            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6021                key: *key,
6022                reason: "Not in storage-admission range for this key".to_string(),
6023            }),
6024            rr_message_id,
6025        )
6026        .await;
6027        // About the key and this node's place in the routing table, not about
6028        // the sender: every queued proof would be refused identically.
6029        return Ok(FreshOfferOutcome::Abandoned);
6030    }
6031
6032    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6033    // never store this record, so reject it before the expensive payment
6034    // verification (EVM on-chain query / merkle pool work) rather than verifying
6035    // and only then failing at `storage.put` below. Reuses the cached capacity
6036    // check (passing results only, so freed space is detected promptly), and the
6037    // store path keeps its own check as defence-in-depth.
6038    if let Err(e) = ctx.storage.check_capacity() {
6039        info!(
6040            target: "ant_node::storage::disk_precheck",
6041            key = %hex::encode(key),
6042            "Rejecting fresh replication offer before payment verification: {e}"
6043        );
6044        send_replication_response(
6045            source,
6046            p2p_node,
6047            request_id,
6048            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6049                key: *key,
6050                reason: e.to_string(),
6051            }),
6052            rr_message_id,
6053        )
6054        .await;
6055        // A full disk is this node's condition, not the sender's.
6056        return Ok(FreshOfferOutcome::Abandoned);
6057    }
6058
6059    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6060    // part of the immediate write fan-out: this receiver is about to store the
6061    // record as if the client had PUT it here directly. Storage admission
6062    // was checked above before proof work. FreshReplication verification is
6063    // identical to ClientPut — store-strength cache semantics, paid-quote
6064    // issuer K-closeness checks for single-node proofs, merkle candidate
6065    // closeness for merkle proofs, and the same price-floor policy — the
6066    // distinct context only labels price-floor telemetry.
6067    let Some(verification) = verify_payment_until_shutdown(
6068        &ctx.payment_verifier,
6069        key,
6070        &attempt.proof_of_payment,
6071        fresh_offer_payment_context(),
6072        &ctx.shutdown,
6073    )
6074    .await
6075    else {
6076        debug!(
6077            "Fresh offer for {} from {source} abandoned: engine shutting down \
6078             during payment verification",
6079            hex::encode(key)
6080        );
6081        return Ok(FreshOfferOutcome::Abandoned);
6082    };
6083    match verification {
6084        Ok(status) if status.can_store() => {
6085            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6086        }
6087        // The chain has no record of this payment. That is a statement about
6088        // *this sender's* proof, so the key rotates to the next one rather than
6089        // being written off — the whole point of queueing them.
6090        //
6091        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6092        // not "definitively unpaid", so a lagging or reorganising chain view
6093        // renders honest senders indistinguishable from forgers, and penalising
6094        // would land on the entire close group at once. The structural checks in
6095        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6096        // because those cannot be produced by an honest sender at all.
6097        Ok(_) => {
6098            debug!(
6099                "Fresh offer for {} from {source}: no payment found for this proof",
6100                hex::encode(key)
6101            );
6102            send_replication_response(
6103                source,
6104                p2p_node,
6105                request_id,
6106                ReplicationMessageBody::FreshReplicationResponse(
6107                    FreshReplicationResponse::Rejected {
6108                        key: *key,
6109                        reason: "Payment verification failed: payment required".to_string(),
6110                    },
6111                ),
6112                rr_message_id,
6113            )
6114            .await;
6115            return Ok(FreshOfferOutcome::ProofRejected);
6116        }
6117        // A verification *error* is usually ours — an unreachable or failing EVM
6118        // endpoint — so it is neither penalised nor treated as this sender's
6119        // fault. Another proof still gets its turn, since the next call may well
6120        // succeed against a recovered endpoint.
6121        Err(e) => {
6122            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6123            send_replication_response(
6124                source,
6125                p2p_node,
6126                request_id,
6127                ReplicationMessageBody::FreshReplicationResponse(
6128                    FreshReplicationResponse::Rejected {
6129                        key: *key,
6130                        reason: format!("Payment verification error: {e}"),
6131                    },
6132                ),
6133                rr_message_id,
6134            )
6135            .await;
6136            return Ok(FreshOfferOutcome::ProofRejected);
6137        }
6138    }
6139
6140    // Rule 6: add to PaidForList.
6141    if let Err(e) = ctx.paid_list.insert(key).await {
6142        warn!("Failed to add key to PaidForList: {e}");
6143    }
6144
6145    // Store the record.
6146    match ctx.storage.put(key, data).await {
6147        Ok(_) => {
6148            send_replication_response(
6149                source,
6150                p2p_node,
6151                request_id,
6152                ReplicationMessageBody::FreshReplicationResponse(
6153                    FreshReplicationResponse::Accepted { key: *key },
6154                ),
6155                rr_message_id,
6156            )
6157            .await;
6158            Ok(FreshOfferOutcome::Settled)
6159        }
6160        Err(e) => {
6161            send_replication_response(
6162                source,
6163                p2p_node,
6164                request_id,
6165                ReplicationMessageBody::FreshReplicationResponse(
6166                    FreshReplicationResponse::Rejected {
6167                        key: *key,
6168                        reason: e.to_string(),
6169                    },
6170                ),
6171                rr_message_id,
6172            )
6173            .await;
6174            // The payment was good and the write still failed, so this is local
6175            // storage trouble that another proof cannot get around.
6176            Ok(FreshOfferOutcome::Abandoned)
6177        }
6178    }
6179}
6180
6181/// Admit a paid-list notification for handling on a worker, or drop it.
6182///
6183/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6184/// meant one message could park every other non-audit message behind a full
6185/// payment verification. That verification is not a bounded local computation:
6186/// on the merkle path it performs an iterative Kademlia lookup capped only by
6187/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6188/// the loop for minutes while the bounded inbound queue behind it overflowed
6189/// and dropped unrelated replication traffic wholesale.
6190///
6191/// It now follows the same detached-responder pattern as neighbor sync and
6192/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6193/// when stale, and run on a tracked worker.
6194///
6195/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6196/// refused notify is simply dropped. The sender's own paid-list convergence
6197/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6198/// the recovery path, exactly as for a notify lost in transit.
6199async fn dispatch_paid_notify(
6200    source: PeerId,
6201    notify: protocol::PaidNotify,
6202    ctx: &ReplicationMessageHandlerContext,
6203    received_at: Instant,
6204) -> Result<()> {
6205    let admission = match admit_bounded_responder(
6206        &ctx.paid_notify_admission_semaphore,
6207        &ctx.paid_notify_responder_inflight,
6208        &source,
6209        PAID_NOTIFY_MAX_OUTSTANDING,
6210        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6211    )
6212    .await
6213    {
6214        Ok(guard) => guard,
6215        Err(failure) => {
6216            audit_metrics::record_responder_admission_drop(
6217                ReplicationResponderClass::PaidNotify,
6218                failure.reason.into(),
6219            );
6220            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6221            // so a refusal discards durable paid-list evidence outright rather
6222            // than pushing work back onto a requester.
6223            warn!(
6224                responder_class = "paid_notify",
6225                source = %source,
6226                key = %hex::encode(notify.key),
6227                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6228            );
6229            return Ok(());
6230        }
6231    };
6232
6233    let ctx = ctx.clone();
6234    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6235    // Deliberately NOT the verification request deadline used by the
6236    // request/response responders. Nobody is waiting on a notify, and shedding
6237    // one discards durable paid-list evidence rather than a reply a requester
6238    // has already given up on. The threshold is instead the point at which the
6239    // pull path would have learned the same fact anyway: one slow-cadence
6240    // neighbor-sync interval, after which the verification cycle's paid-list
6241    // quorum makes this notify genuinely redundant.
6242    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6243    ctx.detached_task_tracker.clone().spawn(async move {
6244        let _admission = admission;
6245        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6246        // still queued behind a worker when the engine stops.
6247        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6248            debug!("Paid notify from {source} dropped: worker pool shut down");
6249            return;
6250        };
6251        if request_is_stale(received_at, queue_max_age) {
6252            debug!(
6253                responder_class = "paid_notify",
6254                source = %source,
6255                request_age_ms = received_at.elapsed().as_millis(),
6256                "Redundant paid notify shed at dequeue"
6257            );
6258            return;
6259        }
6260        if let Err(e) = handle_paid_notify(
6261            &source,
6262            &notify,
6263            &ctx.paid_list,
6264            &ctx.payment_verifier,
6265            &ctx.p2p_node,
6266            &ctx.config,
6267            &ctx.shutdown,
6268        )
6269        .await
6270        {
6271            debug!("Paid notify from {source} error: {e}");
6272        }
6273    });
6274
6275    Ok(())
6276}
6277
6278async fn handle_paid_notify(
6279    _source: &PeerId,
6280    notify: &protocol::PaidNotify,
6281    paid_list: &Arc<PaidList>,
6282    payment_verifier: &Arc<PaymentVerifier>,
6283    p2p_node: &Arc<P2PNode>,
6284    config: &ReplicationConfig,
6285    shutdown: &CancellationToken,
6286) -> Result<()> {
6287    let self_id = *p2p_node.peer_id();
6288
6289    // Rule 3: validate PoP presence before adding.
6290    if notify.proof_of_payment.is_empty() {
6291        return Ok(());
6292    }
6293
6294    // Check if we're in PaidCloseGroup for this key.
6295    if !admission::is_in_paid_close_group(
6296        &self_id,
6297        &notify.key,
6298        p2p_node,
6299        config.paid_list_close_group_size,
6300    )
6301    .await
6302    {
6303        return Ok(());
6304    }
6305
6306    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6307    // paid-list metadata, so local paid-list close-group membership was checked
6308    // above before proof work. The verifier then runs the same payment proof
6309    // checks as ClientPut while writing a paid-list-strength cache entry.
6310    let Some(verification) = verify_payment_until_shutdown(
6311        payment_verifier,
6312        &notify.key,
6313        &notify.proof_of_payment,
6314        paid_notify_payment_context(),
6315        shutdown,
6316    )
6317    .await
6318    else {
6319        debug!(
6320            "Paid notify for {} abandoned: engine shutting down during payment \
6321             verification",
6322            hex::encode(notify.key)
6323        );
6324        return Ok(());
6325    };
6326    match verification {
6327        Ok(status) if status.can_store() => {
6328            debug!(
6329                "PoP validated for paid notify key {}",
6330                hex::encode(notify.key)
6331            );
6332        }
6333        Ok(_) => {
6334            warn!(
6335                "Paid notify rejected: payment required for key {}",
6336                hex::encode(notify.key)
6337            );
6338            return Ok(());
6339        }
6340        Err(e) => {
6341            warn!(
6342                "PoP verification error for paid notify key {}: {e}",
6343                hex::encode(notify.key)
6344            );
6345            return Ok(());
6346        }
6347    }
6348
6349    if let Err(e) = paid_list.insert(&notify.key).await {
6350        warn!("Failed to add paid notify key to PaidForList: {e}");
6351    }
6352
6353    Ok(())
6354}
6355
6356#[allow(clippy::too_many_arguments)]
6357async fn dispatch_neighbor_sync_request(
6358    source: PeerId,
6359    request: protocol::NeighborSyncRequest,
6360    ctx: &ReplicationMessageHandlerContext,
6361    is_bootstrapping: bool,
6362    my_commitment: Option<StorageCommitment>,
6363    request_id: u64,
6364    received_at: Instant,
6365    rr_message_id: Option<&str>,
6366) -> Result<()> {
6367    let guard = match admit_bounded_responder(
6368        &ctx.neighbor_sync_responder_admission_semaphore,
6369        &ctx.neighbor_sync_responder_inflight,
6370        &source,
6371        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6372        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6373    )
6374    .await
6375    {
6376        Ok(guard) => guard,
6377        Err(failure) => {
6378            audit_metrics::record_responder_admission_drop(
6379                ReplicationResponderClass::NeighborSync,
6380                failure.reason.into(),
6381            );
6382            warn!(
6383                responder_class = "neighbor_sync",
6384                source = %source,
6385                "Neighbor-sync response dropped at admission: {failure}"
6386            );
6387            return Ok(());
6388        }
6389    };
6390
6391    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6392    let p2p_node = Arc::clone(&ctx.p2p_node);
6393    let storage = Arc::clone(&ctx.storage);
6394    let paid_list = Arc::clone(&ctx.paid_list);
6395    let queues = Arc::clone(&ctx.queues);
6396    let config = Arc::clone(&ctx.config);
6397    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6398    let sync_history = Arc::clone(&ctx.sync_history);
6399    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6400    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6401    let request_timeout = ctx.config.verification_request_timeout;
6402    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6403    ctx.detached_task_tracker.spawn(async move {
6404        let _guard = guard;
6405        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6406            debug!(
6407                responder_class = "neighbor_sync",
6408                source = %source,
6409                "Neighbor-sync responder worker pool closed before dequeue"
6410            );
6411            return;
6412        };
6413        if request_is_stale(received_at, request_timeout) {
6414            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6415            debug!(
6416                responder_class = "neighbor_sync",
6417                source = %source,
6418                request_age_ms = received_at.elapsed().as_millis(),
6419                "Stale neighbor-sync request shed at dequeue"
6420            );
6421            return;
6422        }
6423        if let Err(e) = handle_neighbor_sync_request(
6424            &source,
6425            &request,
6426            &p2p_node,
6427            &storage,
6428            &paid_list,
6429            &queues,
6430            &config,
6431            is_bootstrapping,
6432            &bootstrap_state,
6433            &sync_history,
6434            &sync_cycle_epoch,
6435            &repair_proofs,
6436            my_commitment,
6437            request_id,
6438            rr_message_id.as_deref(),
6439        )
6440        .await
6441        {
6442            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6443        }
6444    });
6445
6446    Ok(())
6447}
6448
6449#[allow(clippy::too_many_arguments)]
6450async fn handle_neighbor_sync_request(
6451    source: &PeerId,
6452    request: &protocol::NeighborSyncRequest,
6453    p2p_node: &Arc<P2PNode>,
6454    storage: &Arc<LmdbStorage>,
6455    paid_list: &Arc<PaidList>,
6456    queues: &Arc<RwLock<ReplicationQueues>>,
6457    config: &ReplicationConfig,
6458    is_bootstrapping: bool,
6459    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6460    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6461    sync_cycle_epoch: &Arc<RwLock<u64>>,
6462    repair_proofs: &Arc<RwLock<RepairProofs>>,
6463    my_commitment: Option<StorageCommitment>,
6464    request_id: u64,
6465    rr_message_id: Option<&str>,
6466) -> Result<()> {
6467    let self_id = *p2p_node.peer_id();
6468
6469    // No per-request hint count limit: the wire message size limit
6470    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6471    // challenges, sync hints don't drive expensive computation — they just
6472    // enter the verification queue. A per-request limit here would break
6473    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6474
6475    // Build response (outbound hints).
6476    let (response, sent_replica_hints, sender_in_rt) =
6477        neighbor_sync::handle_sync_request_with_proofs(
6478            source,
6479            request,
6480            p2p_node,
6481            storage,
6482            paid_list,
6483            config,
6484            is_bootstrapping,
6485            my_commitment.clone(),
6486        )
6487        .await;
6488
6489    // Send response.
6490    let response_sent = send_replication_response_checked(
6491        source,
6492        p2p_node,
6493        request_id,
6494        ReplicationMessageBody::NeighborSyncResponse(response),
6495        rr_message_id,
6496        None,
6497    )
6498    .await;
6499
6500    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6501    if !sender_in_rt {
6502        return Ok(());
6503    }
6504
6505    // Update sync history for this peer before recording repair proofs so a
6506    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6507    {
6508        let mut history = sync_history.write().await;
6509        let record = history.entry(*source).or_insert(PeerSyncRecord {
6510            last_sync: None,
6511            cycles_since_sync: 0,
6512        });
6513        record.last_sync = Some(Instant::now());
6514        record.cycles_since_sync = 0;
6515    }
6516
6517    if response_sent && !request.bootstrapping {
6518        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6519            .await;
6520    }
6521
6522    // Admit inbound hints and queue for verification.
6523    let outcome = admit_and_queue_hints(
6524        &self_id,
6525        source,
6526        &request.replica_hints,
6527        &request.paid_hints,
6528        p2p_node,
6529        config,
6530        storage,
6531        paid_list,
6532        queues,
6533    )
6534    .await;
6535
6536    // Track discovered keys for bootstrap drain detection so that hints
6537    // admitted via inbound sync requests are not missed. Capacity-rejected
6538    // hints keep this source on the "not yet drained" list until its next
6539    // sync re-admits them; a clean cycle clears the source.
6540    if is_bootstrapping {
6541        let live_discovered = outcome.discovered.clone();
6542        let outcomes = [(*source, outcome)];
6543        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6544    }
6545
6546    Ok(())
6547}
6548
6549async fn handle_verification_request(
6550    source: &PeerId,
6551    request: &protocol::VerificationRequest,
6552    storage: &Arc<LmdbStorage>,
6553    paid_list: &Arc<PaidList>,
6554    p2p_node: &Arc<P2PNode>,
6555    request_id: u64,
6556    rr_message_id: Option<&str>,
6557) -> Result<()> {
6558    #[derive(Clone, Copy)]
6559    enum CachedPaidLookup {
6560        NotChecked,
6561        Checked(Option<bool>),
6562    }
6563
6564    #[derive(Clone, Copy)]
6565    struct CachedVerificationLookup {
6566        present: Option<bool>,
6567        paid: CachedPaidLookup,
6568    }
6569
6570    if verification_request_exceeds_limit(request.keys.len()) {
6571        warn!(
6572            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6573            request.keys.len(),
6574        );
6575        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6576        return Ok(());
6577    }
6578
6579    let requested_keys = request.keys.as_slice();
6580
6581    if request.paid_list_check_indices.len() > request.keys.len() {
6582        warn!(
6583            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6584            request.paid_list_check_indices.len(),
6585            request.keys.len(),
6586        );
6587        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6588        return Ok(());
6589    }
6590
6591    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6592    let paid_check_set: HashSet<u32> = request
6593        .paid_list_check_indices
6594        .iter()
6595        .copied()
6596        .filter(|&idx| {
6597            if idx >= keys_len {
6598                warn!(
6599                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6600                    requested_keys.len(),
6601                );
6602                false
6603            } else {
6604                true
6605            }
6606        })
6607        .collect();
6608
6609    let mut results = Vec::with_capacity(requested_keys.len());
6610    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6611    for (i, key) in requested_keys.iter().enumerate() {
6612        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6613        let cached = lookup_cache.entry(*key).or_insert_with(|| {
6614            let present = match storage.exists(key) {
6615                Ok(present) => Some(present),
6616                Err(e) => {
6617                    warn!(
6618                        "Verification request from {source}: failed to check storage for {}: {e}",
6619                        hex::encode(key)
6620                    );
6621                    None
6622                }
6623            };
6624            CachedVerificationLookup {
6625                present,
6626                paid: CachedPaidLookup::NotChecked,
6627            }
6628        });
6629
6630        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6631            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6632                Ok(paid) => Some(paid),
6633                Err(e) => {
6634                    warn!(
6635                        "Verification request from {source}: failed to check paid-list for {}: {e}",
6636                        hex::encode(key)
6637                    );
6638                    None
6639                }
6640            });
6641        }
6642
6643        let paid = if needs_paid {
6644            match cached.paid {
6645                CachedPaidLookup::Checked(paid) => paid,
6646                CachedPaidLookup::NotChecked => None,
6647            }
6648        } else {
6649            None
6650        };
6651
6652        if cached.present.is_none() && paid.is_none() {
6653            continue;
6654        }
6655
6656        results.push(protocol::KeyVerificationResult {
6657            key: *key,
6658            present: cached.present.unwrap_or(false),
6659            paid,
6660        });
6661    }
6662
6663    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6664
6665    Ok(())
6666}
6667
6668async fn dispatch_verification_request(
6669    source: PeerId,
6670    request: protocol::VerificationRequest,
6671    ctx: &ReplicationMessageHandlerContext,
6672    request_id: u64,
6673    received_at: Instant,
6674    rr_message_id: Option<&str>,
6675) -> Result<()> {
6676    let guard = match admit_bounded_responder(
6677        &ctx.verification_responder_admission_semaphore,
6678        &ctx.verification_responder_inflight,
6679        &source,
6680        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6681        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6682    )
6683    .await
6684    {
6685        Ok(guard) => guard,
6686        Err(failure) => {
6687            audit_metrics::record_responder_admission_drop(
6688                ReplicationResponderClass::Verification,
6689                failure.reason.into(),
6690            );
6691            warn!(
6692                responder_class = "verification",
6693                source = %source,
6694                "Verification response dropped at admission: {failure}"
6695            );
6696            return Ok(());
6697        }
6698    };
6699
6700    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6701    let storage = Arc::clone(&ctx.storage);
6702    let paid_list = Arc::clone(&ctx.paid_list);
6703    let p2p_node = Arc::clone(&ctx.p2p_node);
6704    let request_timeout = ctx.config.verification_request_timeout;
6705    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6706    ctx.detached_task_tracker.spawn(async move {
6707        let _guard = guard;
6708        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6709            debug!(
6710                responder_class = "verification",
6711                source = %source,
6712                "Verification responder worker pool closed before dequeue"
6713            );
6714            return;
6715        };
6716        if request_is_stale(received_at, request_timeout) {
6717            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6718            debug!(
6719                responder_class = "verification",
6720                source = %source,
6721                request_age_ms = received_at.elapsed().as_millis(),
6722                "Stale verification request shed at dequeue"
6723            );
6724            return;
6725        }
6726        if let Err(e) = handle_verification_request(
6727            &source,
6728            &request,
6729            &storage,
6730            &paid_list,
6731            &p2p_node,
6732            request_id,
6733            rr_message_id.as_deref(),
6734        )
6735        .await
6736        {
6737            debug!(source = %source, "Verification request handling failed: {e}");
6738        }
6739    });
6740
6741    Ok(())
6742}
6743
6744const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6745    key_count > MAX_INCOMING_VERIFICATION_KEYS
6746}
6747
6748async fn send_verification_results(
6749    source: &PeerId,
6750    p2p_node: &Arc<P2PNode>,
6751    request_id: u64,
6752    results: Vec<protocol::KeyVerificationResult>,
6753    rr_message_id: Option<&str>,
6754) {
6755    send_replication_response(
6756        source,
6757        p2p_node,
6758        request_id,
6759        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6760        rr_message_id,
6761    )
6762    .await;
6763}
6764
6765async fn dispatch_fetch_request(
6766    source: PeerId,
6767    request: protocol::FetchRequest,
6768    ctx: &ReplicationMessageHandlerContext,
6769    request_id: u64,
6770    received_at: Instant,
6771    rr_message_id: Option<&str>,
6772) -> Result<()> {
6773    let guard = match admit_bounded_responder(
6774        &ctx.fetch_responder_admission_semaphore,
6775        &ctx.fetch_responder_inflight,
6776        &source,
6777        FETCH_RESPONDER_MAX_OUTSTANDING,
6778        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6779    )
6780    .await
6781    {
6782        Ok(guard) => guard,
6783        Err(failure) => {
6784            audit_metrics::record_responder_admission_drop(
6785                ReplicationResponderClass::Fetch,
6786                failure.reason.into(),
6787            );
6788            warn!(
6789                responder_class = "fetch",
6790                source = %source,
6791                "Fetch response dropped at admission: {failure}"
6792            );
6793            return Ok(());
6794        }
6795    };
6796
6797    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6798    let storage = Arc::clone(&ctx.storage);
6799    let p2p_node = Arc::clone(&ctx.p2p_node);
6800    let request_timeout = ctx.config.fetch_request_timeout;
6801    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6802    ctx.detached_task_tracker.spawn(async move {
6803        let _guard = guard;
6804        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6805            debug!(
6806                responder_class = "fetch",
6807                source = %source,
6808                "Fetch responder worker pool closed before dequeue"
6809            );
6810            return;
6811        };
6812        if request_is_stale(received_at, request_timeout) {
6813            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6814            debug!(
6815                responder_class = "fetch",
6816                source = %source,
6817                request_age_ms = received_at.elapsed().as_millis(),
6818                "Stale fetch request shed at dequeue"
6819            );
6820            return;
6821        }
6822        if let Err(e) = handle_fetch_request(
6823            &source,
6824            &request,
6825            &storage,
6826            &p2p_node,
6827            request_id,
6828            rr_message_id.as_deref(),
6829        )
6830        .await
6831        {
6832            debug!(source = %source, "Fetch request handling failed: {e}");
6833        }
6834    });
6835
6836    Ok(())
6837}
6838
6839fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6840    received_at.elapsed() >= timeout
6841}
6842
6843async fn handle_fetch_request(
6844    source: &PeerId,
6845    request: &protocol::FetchRequest,
6846    storage: &Arc<LmdbStorage>,
6847    p2p_node: &Arc<P2PNode>,
6848    request_id: u64,
6849    rr_message_id: Option<&str>,
6850) -> Result<()> {
6851    let response = match storage.get(&request.key).await {
6852        Ok(Some(data)) => protocol::FetchResponse::Success {
6853            key: request.key,
6854            data,
6855        },
6856        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
6857        Err(e) => protocol::FetchResponse::Error {
6858            key: request.key,
6859            reason: format!("{e}"),
6860        },
6861    };
6862
6863    send_replication_response(
6864        source,
6865        p2p_node,
6866        request_id,
6867        ReplicationMessageBody::FetchResponse(response),
6868        rr_message_id,
6869    )
6870    .await;
6871
6872    Ok(())
6873}
6874
6875/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
6876/// the prune-confirmation audit, which reuses the same wire message): reply with
6877/// per-key possession digests.
6878struct AuditResponderCompletion {
6879    response_kind: &'static str,
6880    sent: bool,
6881    processing: Duration,
6882    response_send: Duration,
6883}
6884
6885async fn handle_audit_challenge_msg(
6886    source: &PeerId,
6887    challenge: &protocol::AuditChallenge,
6888    storage: &Arc<LmdbStorage>,
6889    p2p_node: &Arc<P2PNode>,
6890    is_bootstrapping: bool,
6891    reply: ReplyRoute<'_>,
6892) -> Result<AuditResponderCompletion> {
6893    #[allow(clippy::cast_possible_truncation)]
6894    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
6895    info!(
6896        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
6897        challenge.keys.len(),
6898        is_bootstrapping,
6899        reply.rr_message_id.is_some(),
6900    );
6901
6902    let processing_started = Instant::now();
6903    let response = audit::handle_audit_challenge(
6904        challenge,
6905        storage,
6906        p2p_node.peer_id(),
6907        is_bootstrapping,
6908        stored_chunks,
6909    )
6910    .await;
6911    let processing = processing_started.elapsed();
6912    let response_kind = audit_response_kind(&response);
6913
6914    let response_send_started = Instant::now();
6915    let sent = send_replication_response_checked(
6916        source,
6917        p2p_node,
6918        reply.request_id,
6919        ReplicationMessageBody::AuditResponse(response),
6920        reply.rr_message_id,
6921        Some(reply.protocol),
6922    )
6923    .await;
6924    let response_send = response_send_started.elapsed();
6925
6926    Ok(AuditResponderCompletion {
6927        response_kind,
6928        sent,
6929        processing,
6930        response_send,
6931    })
6932}
6933
6934#[allow(clippy::too_many_arguments)]
6935fn log_audit_responder_completion(
6936    metrics: &AuditResponderMetrics,
6937    source: PeerId,
6938    class: AuditResponderClass,
6939    kind: &'static str,
6940    challenge_id: u64,
6941    work_items: usize,
6942    response_kind: &'static str,
6943    sent: bool,
6944    received_at: Instant,
6945    worker_started: Instant,
6946    processing: Duration,
6947    response_send: Duration,
6948) {
6949    let dispatch = worker_started.saturating_duration_since(received_at);
6950    let total = received_at.elapsed();
6951    metrics.record_completed(source, processing, total, sent);
6952    if sent {
6953        info!(
6954            target: "ant_node::replication::audit_responder",
6955            event = "completed",
6956            kind,
6957            responder_class = class.as_str(),
6958            source = %source,
6959            challenge_id,
6960            work_items,
6961            response = response_kind,
6962            sent,
6963            dispatch_ms = dispatch.as_millis(),
6964            processing_ms = processing.as_millis(),
6965            response_send_ms = response_send.as_millis(),
6966            total_ms = total.as_millis(),
6967            "Audit responder request completed"
6968        );
6969    } else {
6970        warn!(
6971            target: "ant_node::replication::audit_responder",
6972            event = "completed",
6973            kind,
6974            responder_class = class.as_str(),
6975            source = %source,
6976            challenge_id,
6977            work_items,
6978            response = response_kind,
6979            sent,
6980            dispatch_ms = dispatch.as_millis(),
6981            processing_ms = processing.as_millis(),
6982            response_send_ms = response_send.as_millis(),
6983            total_ms = total.as_millis(),
6984            "Audit responder request completed without sending a reply"
6985        );
6986    }
6987}
6988
6989/// Where a reply goes and how it is addressed.
6990///
6991/// Grouped because the audit responder needs all three together and one of them
6992/// is not derivable from the body: during the rollout window a possession reply
6993/// may have to go out on the core id rather than its family's own (see
6994/// [`is_legacy_possession_challenge`]).
6995struct ReplyRoute<'a> {
6996    /// Correlates the reply with the challenge, at the replication layer.
6997    request_id: u64,
6998    /// Present when the challenge arrived over request-response, in which case
6999    /// the reply rides the same exchange back.
7000    rr_message_id: Option<&'a str>,
7001    /// The protocol id to answer on.
7002    protocol: &'static str,
7003}
7004
7005fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7006    match response {
7007        protocol::AuditResponse::Digests { .. } => "digests",
7008        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7009        protocol::AuditResponse::Rejected { .. } => "rejected",
7010    }
7011}
7012
7013fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7014    match response {
7015        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7016        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7017        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7018    }
7019}
7020
7021fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7022    match response {
7023        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7024        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7025        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7026    }
7027}
7028
7029fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7030    match response {
7031        protocol::SubtreeSliceResponse::Items { .. } => "items",
7032        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7033        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7034    }
7035}
7036
7037fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7038    match response {
7039        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7040        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7041    }
7042}
7043
7044// ---------------------------------------------------------------------------
7045// Message sending helper
7046// ---------------------------------------------------------------------------
7047
7048/// Send a replication response message as a best-effort reply.
7049///
7050/// Encode and send failures are logged by the checked helper. Most response
7051/// paths do not need to branch on send success, so this wrapper keeps those
7052/// call sites explicit about their best-effort behavior.
7053async fn send_replication_response(
7054    peer: &PeerId,
7055    p2p_node: &Arc<P2PNode>,
7056    request_id: u64,
7057    body: ReplicationMessageBody,
7058    rr_message_id: Option<&str>,
7059) {
7060    let _ =
7061        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7062            .await;
7063}
7064
7065/// Send a replication response message and report whether it was accepted.
7066///
7067/// Returns `true` after the message is encoded and accepted by the P2P send
7068/// path. Returns `false` after logging an encode or send failure. Repair-proof
7069/// recording uses this to avoid trusting hints that were not actually sent.
7070///
7071/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7072/// request-response path so saorsa-core can route it back to the caller's
7073/// `send_request` future. Otherwise it is sent as a plain message.
7074///
7075/// `protocol` overrides the id the body would route on by family. Exactly one
7076/// caller needs it: a possession challenge from a peer that predates the family
7077/// split has to be answered where it was asked (see
7078/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7079/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7080async fn send_replication_response_checked(
7081    peer: &PeerId,
7082    p2p_node: &Arc<P2PNode>,
7083    request_id: u64,
7084    body: ReplicationMessageBody,
7085    rr_message_id: Option<&str>,
7086    protocol: Option<&'static str>,
7087) -> bool {
7088    let msg = ReplicationMessage { request_id, body };
7089    let encoded = match msg.encode() {
7090        Ok(data) => data,
7091        Err(e) => {
7092            warn!("Failed to encode replication response: {e}");
7093            return false;
7094        }
7095    };
7096    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7097    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7098    // included for completeness. Other response variants (verification/audit/
7099    // commitment) are intentionally excluded — the round-2 audit reply is now a
7100    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7101    if matches!(
7102        msg.body,
7103        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7104    ) {
7105        protocol::record_served(peer, encoded.len());
7106    }
7107    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7108    let result = if let Some(msg_id) = rr_message_id {
7109        p2p_node
7110            .send_response(peer, protocol, msg_id, encoded)
7111            .await
7112    } else {
7113        p2p_node.send_message(peer, protocol, encoded, &[]).await
7114    };
7115    if let Err(e) = result {
7116        debug!("Failed to send replication response to {peer}: {e}");
7117        return false;
7118    }
7119    true
7120}
7121
7122async fn record_sent_replica_hints(
7123    peer: &PeerId,
7124    hints: &[neighbor_sync::SentReplicaHint],
7125    repair_proofs: &Arc<RwLock<RepairProofs>>,
7126    sync_cycle_epoch: &Arc<RwLock<u64>>,
7127) {
7128    if hints.is_empty() {
7129        return;
7130    }
7131
7132    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7133    let mut proofs = repair_proofs.write().await;
7134    for hint in hints {
7135        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7136            debug!(
7137                "Recorded repair hint proof for peer {peer} and key {}",
7138                hex::encode(hint.key)
7139            );
7140        }
7141    }
7142}
7143
7144// ---------------------------------------------------------------------------
7145// Neighbor sync round
7146// ---------------------------------------------------------------------------
7147
7148/// Run one neighbor sync round.
7149#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7150async fn run_neighbor_sync_round(
7151    p2p_node: &Arc<P2PNode>,
7152    storage: &Arc<LmdbStorage>,
7153    paid_list: &Arc<PaidList>,
7154    queues: &Arc<RwLock<ReplicationQueues>>,
7155    config: &ReplicationConfig,
7156    sync_state: &Arc<RwLock<NeighborSyncState>>,
7157    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7158    sync_cycle_epoch: &Arc<RwLock<u64>>,
7159    repair_proofs: &Arc<RwLock<RepairProofs>>,
7160    is_bootstrapping: &Arc<RwLock<bool>>,
7161    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7162    commitment_state: &Arc<ResponderCommitmentState>,
7163    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7164    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7165    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7166    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7167    gossip_audit: &GossipAuditTrigger,
7168) {
7169    let self_id = *p2p_node.peer_id();
7170    let bootstrapping = *is_bootstrapping.read().await;
7171
7172    // Check if cycle is complete; start new one if needed.
7173    // We check under a read lock, then release it before the expensive
7174    // prune pass and DHT snapshot so other tasks are not starved.
7175    let cycle_complete = sync_state.read().await.is_cycle_complete();
7176    if cycle_complete {
7177        // A completed local neighbor-sync cycle advances the epoch component
7178        // of repair-proof maturity. The per-key wall-clock minimum age is
7179        // checked when audits are selected.
7180        {
7181            let mut history = sync_history.write().await;
7182            for record in history.values_mut() {
7183                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7184            }
7185        }
7186        {
7187            let mut epoch = sync_cycle_epoch.write().await;
7188            *epoch = epoch.saturating_add(1);
7189        }
7190
7191        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7192        // Prune candidacy is unconditional once the hysteresis elapses;
7193        // bootstrap state only defers the remote prune-confirmation audits
7194        // until bootstrap has drained.
7195        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7196        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7197            self_id: &self_id,
7198            storage,
7199            paid_list,
7200            p2p_node,
7201            config,
7202            sync_state,
7203            repair_proofs,
7204            allow_remote_prune_audits,
7205            commitment_state: Some(commitment_state),
7206            audit_challenge_coordinator,
7207        })
7208        .await;
7209
7210        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7211        let neighbors =
7212            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7213                .await;
7214
7215        // Now re-acquire write lock and re-check before swapping cycle.
7216        let mut state = sync_state.write().await;
7217        if state.is_cycle_complete() {
7218            // Preserve cooldown and bootstrap-claim tracking across cycles.
7219            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7220            // would reset the abuse detection timer every cycle.
7221            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7222            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7223            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7224            let old_prune_cursor = state.prune_cursor;
7225            *state = NeighborSyncState::new_cycle(neighbors);
7226            state.last_sync_times = old_sync_times;
7227            state.bootstrap_claims = old_bootstrap_claims;
7228            state.bootstrap_claim_history = old_bootstrap_claim_history;
7229            state.prune_cursor = old_prune_cursor;
7230        }
7231    }
7232
7233    // Select batch of peers.
7234    let batch = {
7235        let mut state = sync_state.write().await;
7236        neighbor_sync::select_sync_batch(
7237            &mut state,
7238            config.neighbor_sync_peer_count,
7239            config.neighbor_sync_cooldown,
7240        )
7241    };
7242
7243    if batch.is_empty() {
7244        return;
7245    }
7246
7247    debug!("Neighbor sync: syncing with {} peers", batch.len());
7248
7249    // Snapshot our current commitment once per round so all peers in
7250    // this batch see the same thing (gossip is the responder's attestation;
7251    // same value across the batch is fine and reduces RwLock churn). Atomically
7252    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7253    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7254    let my_commitment = commitment_state
7255        .current_for_gossip()
7256        .map(|b| b.commitment().clone());
7257
7258    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7259        &batch,
7260        storage,
7261        paid_list,
7262        p2p_node,
7263        config.close_group_size,
7264        config.paid_list_close_group_size,
7265    )
7266    .await;
7267
7268    // Sync with each peer in the batch.
7269    for peer in &batch {
7270        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7271        let outcome = neighbor_sync::sync_with_peer_with_hints(
7272            peer,
7273            p2p_node,
7274            config,
7275            bootstrapping,
7276            hints,
7277            my_commitment.clone(),
7278        )
7279        .await;
7280
7281        if let Some(outcome) = outcome {
7282            handle_sync_response(
7283                &self_id,
7284                peer,
7285                &outcome.response,
7286                &outcome.sent_replica_hints,
7287                p2p_node,
7288                config,
7289                bootstrapping,
7290                bootstrap_state,
7291                storage,
7292                paid_list,
7293                queues,
7294                sync_state,
7295                sync_history,
7296                sync_cycle_epoch,
7297                repair_proofs,
7298                last_commitment_by_peer,
7299                ever_capable_peers,
7300                sig_verify_attempts,
7301                gossip_audit,
7302            )
7303            .await;
7304        } else {
7305            // Sync failed -- remove peer and try to fill slot.
7306            let replacement = {
7307                let mut state = sync_state.write().await;
7308                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7309            };
7310
7311            // Attempt sync with the replacement peer (if one was found).
7312            if let Some(replacement_peer) = replacement {
7313                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7314                    std::slice::from_ref(&replacement_peer),
7315                    storage,
7316                    paid_list,
7317                    p2p_node,
7318                    config.close_group_size,
7319                    config.paid_list_close_group_size,
7320                )
7321                .await;
7322                let hints = replacement_hints
7323                    .remove(&replacement_peer)
7324                    .unwrap_or_default();
7325                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7326                    &replacement_peer,
7327                    p2p_node,
7328                    config,
7329                    bootstrapping,
7330                    hints,
7331                    my_commitment.clone(),
7332                )
7333                .await;
7334
7335                if let Some(outcome) = replacement_outcome {
7336                    handle_sync_response(
7337                        &self_id,
7338                        &replacement_peer,
7339                        &outcome.response,
7340                        &outcome.sent_replica_hints,
7341                        p2p_node,
7342                        config,
7343                        bootstrapping,
7344                        bootstrap_state,
7345                        storage,
7346                        paid_list,
7347                        queues,
7348                        sync_state,
7349                        sync_history,
7350                        sync_cycle_epoch,
7351                        repair_proofs,
7352                        last_commitment_by_peer,
7353                        ever_capable_peers,
7354                        sig_verify_attempts,
7355                        gossip_audit,
7356                    )
7357                    .await;
7358                }
7359            }
7360        }
7361    }
7362}
7363
7364/// Process a successful neighbor sync response: record the sync, check for
7365/// bootstrap claim abuse, and admit inbound hints.
7366#[allow(clippy::too_many_arguments)]
7367async fn handle_sync_response(
7368    self_id: &PeerId,
7369    peer: &PeerId,
7370    resp: &NeighborSyncResponse,
7371    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7372    p2p_node: &Arc<P2PNode>,
7373    config: &ReplicationConfig,
7374    bootstrapping: bool,
7375    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7376    storage: &Arc<LmdbStorage>,
7377    paid_list: &Arc<PaidList>,
7378    queues: &Arc<RwLock<ReplicationQueues>>,
7379    sync_state: &Arc<RwLock<NeighborSyncState>>,
7380    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7381    sync_cycle_epoch: &Arc<RwLock<u64>>,
7382    repair_proofs: &Arc<RwLock<RepairProofs>>,
7383    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7384    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7385    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7386    gossip_audit: &GossipAuditTrigger,
7387) {
7388    // Ingest the peer's commitment if they piggybacked one on the response.
7389    // Same verification as the request path (peer-id binding + signature);
7390    // forged commitments are dropped at the edge. A *changed* commitment here
7391    // is a gossip-audit trigger just like on the request path — so a peer that
7392    // only ever answers sync (never initiates) is still audited (ADR-0002).
7393    if let Some(target) = ingest_peer_commitment(
7394        peer,
7395        resp.commitment.as_ref(),
7396        p2p_node,
7397        last_commitment_by_peer,
7398        ever_capable_peers,
7399        sig_verify_attempts,
7400    )
7401    .await
7402    {
7403        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7404    }
7405
7406    // Record successful sync.
7407    {
7408        let mut state = sync_state.write().await;
7409        neighbor_sync::record_successful_sync(&mut state, peer);
7410    }
7411    {
7412        let mut history = sync_history.write().await;
7413        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7414            last_sync: None,
7415            cycles_since_sync: 0,
7416        });
7417        record.last_sync = Some(Instant::now());
7418        record.cycles_since_sync = 0;
7419    }
7420
7421    // Process inbound hints from response (skip if peer is bootstrapping).
7422    if resp.bootstrapping {
7423        // Gap 6: BootstrapClaimAbuse grace period enforcement.
7424        // Separate state mutation from network I/O to avoid holding the
7425        // write lock across report_trust_event.
7426        let should_report = {
7427            let now = Instant::now();
7428            let mut state = sync_state.write().await;
7429            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7430                BootstrapClaimObservation::WithinGrace { .. } => false,
7431                BootstrapClaimObservation::PastGrace { first_seen } => {
7432                    warn!(
7433                        "Peer {peer} has been claiming bootstrap for {:?}, \
7434                         exceeding grace period of {:?} — reporting abuse",
7435                        now.duration_since(first_seen),
7436                        config.bootstrap_claim_grace_period,
7437                    );
7438                    true
7439                }
7440                BootstrapClaimObservation::Repeated { first_seen } => {
7441                    warn!(
7442                        "Peer {peer} repeated bootstrap claim after previously stopping; \
7443                         first claim was {:?} ago — reporting abuse",
7444                        now.duration_since(first_seen),
7445                    );
7446                    true
7447                }
7448            }
7449        };
7450        if should_report {
7451            p2p_node
7452                .report_trust_event(
7453                    peer,
7454                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7455                )
7456                .await;
7457        }
7458    } else {
7459        // Peer is not claiming bootstrap; clear active claim while retaining
7460        // history so the peer cannot start a second grace window later.
7461        {
7462            let mut state = sync_state.write().await;
7463            state.clear_active_bootstrap_claim(peer);
7464        }
7465        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7466        let outcome = admit_and_queue_hints(
7467            self_id,
7468            peer,
7469            &resp.replica_hints,
7470            &resp.paid_hints,
7471            p2p_node,
7472            config,
7473            storage,
7474            paid_list,
7475            queues,
7476        )
7477        .await;
7478
7479        // Track discovered keys for bootstrap drain detection so that hints
7480        // admitted via regular neighbor sync are not missed. Capacity-
7481        // rejected hints keep this source on the "not yet drained" list
7482        // until its next sync replays them; a clean cycle clears it.
7483        if bootstrapping {
7484            let live_discovered = outcome.discovered.clone();
7485            let outcomes = [(*peer, outcome)];
7486            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7487                .await;
7488        }
7489    }
7490}
7491
7492/// Admit hints and queue them for verification, returning newly-discovered keys.
7493///
7494/// Shared by neighbor-sync request handling, response handling, and bootstrap
7495/// sync so that admission + queueing logic lives in one place.
7496#[allow(clippy::too_many_arguments)]
7497/// Outcome of [`admit_and_queue_hints`].
7498///
7499/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7500/// available; that source is kept outstanding until it re-hints. `displaced`
7501/// tracks older borrowed hints reclaimed for another sender; only the key is
7502/// dropped from bootstrap tracking — the former owner's standing is untouched
7503/// (see [`publish_bootstrap_admission_outcomes`]).
7504struct AdmissionOutcome {
7505    discovered: HashSet<XorName>,
7506    capacity_rejected_count: usize,
7507    displaced: Vec<CapacityDisplacement>,
7508}
7509
7510/// Publish one atomic admission unit into bootstrap drain accounting.
7511///
7512/// Only sources that were themselves capacity-rejected are kept outstanding.
7513/// A fairness displacement forfeits the displaced *key* but never stamps its
7514/// former owner: reclaiming a borrowed slot is this node's own fairness
7515/// decision, so charging it to the victim would let a sustained flooder wedge
7516/// our bootstrap drain open through an unrelated honest peer. Clean sources
7517/// are cleared only after every outcome in the unit is known, so peer
7518/// iteration order cannot falsely clear a rejection recorded later in the same
7519/// bootstrap batch.
7520async fn publish_bootstrap_admission_outcomes(
7521    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7522    outcomes: &[(PeerId, AdmissionOutcome)],
7523    live_discovered: &HashSet<XorName>,
7524) {
7525    let mut rejected_sources = HashSet::new();
7526    let mut clean_sources = HashSet::new();
7527    let mut displaced_keys = HashSet::new();
7528
7529    for (source, outcome) in outcomes {
7530        if outcome.capacity_rejected_count > 0 {
7531            rejected_sources.insert(*source);
7532        } else {
7533            clean_sources.insert(*source);
7534        }
7535        // Only the *key* of a fairness displacement is forfeited here, never
7536        // its owner's standing. Reclaiming a borrowed slot is our own fairness
7537        // decision, not a failure by the peer that held it: stamping the victim
7538        // would let a sustained flooder block our bootstrap drain through an
7539        // unrelated honest peer that never overflowed us. The displaced key
7540        // falls to the same post-bootstrap neighbor-sync and audit/repair
7541        // recovery path that TTL expiry already relies on.
7542        for displacement in &outcome.displaced {
7543            displaced_keys.insert(displacement.key);
7544        }
7545    }
7546    clean_sources.retain(|source| !rejected_sources.contains(source));
7547
7548    let now = Instant::now();
7549    let mut state = bootstrap_state.write().await;
7550    for key in displaced_keys {
7551        state.remove_key(&key);
7552    }
7553    state.pending_keys.extend(live_discovered);
7554    for source in clean_sources {
7555        state.capacity_rejected_sources.remove(&source);
7556    }
7557    for source in rejected_sources {
7558        // First-seen: a source that keeps overflowing us must not keep its own
7559        // record fresh, or bootstrap never drains and auditing stays off.
7560        state.note_capacity_rejected(source, now);
7561    }
7562}
7563
7564#[allow(clippy::too_many_arguments)]
7565async fn admit_and_queue_hints(
7566    self_id: &PeerId,
7567    source_peer: &PeerId,
7568    replica_hints: &[XorName],
7569    paid_hints: &[XorName],
7570    p2p_node: &Arc<P2PNode>,
7571    config: &ReplicationConfig,
7572    storage: &Arc<LmdbStorage>,
7573    paid_list: &Arc<PaidList>,
7574    queues: &Arc<RwLock<ReplicationQueues>>,
7575) -> AdmissionOutcome {
7576    let pending_keys: HashSet<XorName> = {
7577        let q = queues.read().await;
7578        q.pending_keys().into_iter().collect()
7579    };
7580
7581    let admitted = admission::admit_hints(
7582        self_id,
7583        replica_hints,
7584        paid_hints,
7585        p2p_node,
7586        config,
7587        storage,
7588        paid_list,
7589        &pending_keys,
7590    )
7591    .await;
7592
7593    let mut q = queues.write().await;
7594    queue_admitted_hints(source_peer, admitted, storage, &mut q)
7595}
7596
7597fn queue_admitted_hints(
7598    source_peer: &PeerId,
7599    admitted: admission::AdmissionResult,
7600    storage: &LmdbStorage,
7601    q: &mut ReplicationQueues,
7602) -> AdmissionOutcome {
7603    let mut discovered = HashSet::new();
7604    let mut capacity_rejected_count: usize = 0;
7605    let mut displaced = Vec::new();
7606    let now = Instant::now();
7607
7608    for key in admitted.replica_keys {
7609        if !storage.exists(&key).unwrap_or(false) {
7610            let result = q.add_pending_verify(
7611                key,
7612                VerificationEntry {
7613                    state: VerificationState::PendingVerify,
7614                    verified_sources: Vec::new(),
7615                    tried_sources: HashSet::new(),
7616                    created_at: now,
7617                    next_verify_at: now,
7618                    hint_sources: HashSet::from([*source_peer]),
7619                    // Non-empty: this peer claimed possession, so it is a
7620                    // fetch-source candidate. Derives HintPipeline::Replica.
7621                    replica_hint_sources: HashSet::from([*source_peer]),
7622                },
7623            );
7624            match result {
7625                crate::replication::scheduling::AdmissionResult::Admitted => {
7626                    discovered.insert(key);
7627                }
7628                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7629                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7630                    capacity_rejected_count += 1;
7631                }
7632            }
7633        }
7634    }
7635
7636    for key in admitted.paid_only_keys {
7637        let result = q.add_pending_verify(
7638            key,
7639            VerificationEntry {
7640                state: VerificationState::PendingVerify,
7641                verified_sources: Vec::new(),
7642                tried_sources: HashSet::new(),
7643                created_at: now,
7644                next_verify_at: now,
7645                hint_sources: HashSet::from([*source_peer]),
7646                // Empty: a paid hint makes no possession claim, so this peer is
7647                // not a fetch source. Derives HintPipeline::PaidOnly.
7648                replica_hint_sources: HashSet::new(),
7649            },
7650        );
7651        match result {
7652            crate::replication::scheduling::AdmissionResult::Admitted => {
7653                discovered.insert(key);
7654            }
7655            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7656            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7657                capacity_rejected_count += 1;
7658            }
7659        }
7660    }
7661
7662    if capacity_rejected_count > 0 {
7663        debug!(
7664            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7665             rejected at queue capacity; source will need to re-hint after pending_verify drains"
7666        );
7667    }
7668
7669    displaced.extend(q.take_capacity_displacements());
7670
7671    AdmissionOutcome {
7672        discovered,
7673        capacity_rejected_count,
7674        displaced,
7675    }
7676}
7677
7678// ---------------------------------------------------------------------------
7679// Verification cycle
7680// ---------------------------------------------------------------------------
7681
7682/// Run one verification cycle: process pending keys through quorum checks.
7683#[allow(clippy::too_many_lines)]
7684async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7685    let cycle_started = Instant::now();
7686    let VerificationCycleContext {
7687        p2p_node,
7688        paid_list,
7689        storage,
7690        queues,
7691        config,
7692        bootstrap_state,
7693        is_bootstrapping,
7694        bootstrap_complete_notify,
7695        last_commitment_by_peer,
7696        ever_capable_peers,
7697        recent_provers,
7698    } = ctx;
7699
7700    // Self-heal the bootstrap drain before any early-return below: abandoned
7701    // capacity-rejection records must expire, and a drain condition that
7702    // became true without a triggering event must still be observed. Pending
7703    // peer requests legitimately block the drain check itself, but not this.
7704    expire_and_recheck_bootstrap_drain(
7705        bootstrap_state,
7706        queues,
7707        is_bootstrapping,
7708        bootstrap_complete_notify,
7709        config.capacity_rejected_max_age(),
7710    )
7711    .await;
7712
7713    // Bootstrap admits one concurrent neighbor batch as an atomic source
7714    // aggregation unit. Do not select newly queued keys until that batch's
7715    // hints and drain accounting have both been published.
7716    if bootstrap_state.read().await.pending_peer_requests > 0 {
7717        return;
7718    }
7719
7720    // Evict stale entries that have been pending too long (e.g. unreachable
7721    // verification targets during a network partition).
7722    let stale_pending_keys = {
7723        let mut q = queues.write().await;
7724        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7725    };
7726    if !stale_pending_keys.is_empty() {
7727        update_bootstrap_after_verification(
7728            &stale_pending_keys,
7729            bootstrap_state,
7730            queues,
7731            is_bootstrapping,
7732            bootstrap_complete_notify,
7733        )
7734        .await;
7735    }
7736
7737    let pending_keys = {
7738        let mut q = queues.write().await;
7739        // Re-check while holding the queue write lock used by fair selection.
7740        // This closes the race
7741        // where a bootstrap batch starts after the early check: the batch
7742        // cannot publish its hints under the queue write lock until this
7743        // selection either returns or declines to run.
7744        if bootstrap_state.read().await.pending_peer_requests > 0 {
7745            return;
7746        }
7747        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7748    };
7749
7750    if pending_keys.is_empty() {
7751        return;
7752    }
7753    let initial_pending_count = pending_keys.len();
7754
7755    let self_id = *p2p_node.peer_id();
7756
7757    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
7758    // step 4). Paid-list membership settles *validity* — the key is known-paid,
7759    // so no quorum round is needed. It says nothing about whether we must hold
7760    // the bytes; that is decided below.
7761    let mut local_paid_keys = Vec::new();
7762    let mut keys_needing_network = Vec::new();
7763    let mut terminal_keys: Vec<XorName> = Vec::new();
7764    {
7765        let mut q = queues.write().await;
7766        for key in &pending_keys {
7767            if paid_list.contains(key).unwrap_or(false) {
7768                if q.set_pending_state(key, VerificationState::PaidListVerified) {
7769                    local_paid_keys.push(*key);
7770                }
7771            } else {
7772                keys_needing_network.push(*key);
7773            }
7774        }
7775    }
7776
7777    // Storage responsibility is a live routing question, decided identically
7778    // for every known-paid key regardless of how the advertising peer labelled
7779    // its hint — a replica hint is a possession *claim* by the sender, never
7780    // permission for us to store. Held outside the queue lock: `is_responsible`
7781    // awaits into the DHT manager.
7782    let mut local_paid_presence_probe_keys = Vec::new();
7783    if !local_paid_keys.is_empty() {
7784        let mut terminal_paid = Vec::new();
7785        for key in local_paid_keys {
7786            if storage.exists(&key).unwrap_or(false) {
7787                terminal_paid.push(key);
7788            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
7789                // We carry storage responsibility and lack the bytes. The
7790                // presence probe below discovers holders to fetch from; it is
7791                // source discovery, not re-verification.
7792                local_paid_presence_probe_keys.push(key);
7793            } else {
7794                terminal_paid.push(key);
7795            }
7796        }
7797
7798        if !terminal_paid.is_empty() {
7799            let mut q = queues.write().await;
7800            for key in terminal_paid {
7801                q.remove_pending(&key);
7802                terminal_keys.push(key);
7803            }
7804        }
7805    }
7806
7807    let local_paid_probe_count = local_paid_presence_probe_keys.len();
7808    let keys_needing_network_count = keys_needing_network.len();
7809
7810    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
7811    // step 4, authorization succeeds immediately; run a presence-only probe
7812    // to find any holder we can fetch from.
7813    if !local_paid_presence_probe_keys.is_empty() {
7814        let targets = quorum::compute_presence_targets(
7815            &local_paid_presence_probe_keys,
7816            p2p_node,
7817            config,
7818            &self_id,
7819        )
7820        .await;
7821        let evidence = quorum::run_verification_round(
7822            &local_paid_presence_probe_keys,
7823            &targets,
7824            p2p_node,
7825            config,
7826        )
7827        .await;
7828
7829        let mut q = queues.write().await;
7830        for key in local_paid_presence_probe_keys {
7831            if storage.exists(&key).unwrap_or(false) {
7832                q.remove_pending(&key);
7833                terminal_keys.push(key);
7834                continue;
7835            }
7836            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
7837                quorum::present_sources_for_key(&key, ev, &targets)
7838            });
7839            if let Some(entry) = q.get_pending(&key) {
7840                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
7841            }
7842            if sources.is_empty() {
7843                warn!(
7844                    "Locally paid key {} has no responding holders yet; deferring retry",
7845                    hex::encode(key)
7846                );
7847                q.defer_pending(&key, config.verification_request_timeout);
7848            } else {
7849                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7850                // Atomic remove+enqueue: if fetch_queue is at capacity, the
7851                // pending entry is preserved and retried next cycle (no
7852                // silent drop of verified replica-repair work).
7853                let _ = q.promote_pending_to_fetch(key, distance, sources);
7854            }
7855        }
7856    }
7857
7858    // Steps 2-5: Network verification (skipped if all keys resolved locally).
7859    if !keys_needing_network.is_empty() {
7860        // Step 2: Compute targets and run network verification round.
7861        let targets =
7862            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
7863                .await;
7864
7865        let evidence =
7866            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
7867
7868        // Step 3: Evaluate results — collect outcomes without holding the write
7869        // lock across paid-list I/O.
7870        //
7871        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
7872        // table and recent_provers cache up front so the synchronous
7873        // evaluate_key_evidence_with_holder_check predicate can consult
7874        // them without awaiting. The predicate downgrades a Present
7875        // claim to Unresolved unless the peer is credited for that key.
7876        // Snapshot per-peer commitment data. We need two views:
7877        //   - `commitment_by_peer_snapshot`: peers that currently have
7878        //     a verified commitment record on file (used to look up
7879        //     their current hash).
7880        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
7881        //     set. Sourced from a separate set rather than the
7882        //     commitment map so eviction (PeerRemoved cleanup, sybil
7883        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
7884        //     a previously-v12 peer to "legacy" credit-unconditionally.
7885        //     Legacy / pre-v12 peers that have never sent a commitment
7886        //     remain absent from the set and are credited via the
7887        //     legacy path so mixed-version networks stay live.
7888        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
7889            let map = last_commitment_by_peer.read().await;
7890            map.iter()
7891                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
7892                // of every peer's ~5 KiB commitment.
7893                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
7894                .collect()
7895        };
7896        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
7897        // Take a full snapshot of recent_provers under the read lock,
7898        // then release. The cache is bounded (16/key × keys), so the
7899        // clone is cheap.
7900        let provers_snapshot = recent_provers.read().await.clone();
7901        // For the replica-fetch path, we need to know whether THIS
7902        // node already holds the key being verified. The v12 §6
7903        // holder-credit gate is meant to prevent uncredited Present
7904        // claims from contributing to paid-list / reward quorum for
7905        // keys we DO hold (and could audit ourselves). For keys we
7906        // are trying to FETCH (i.e. not in local storage), there is
7907        // no possible local audit credit, and gating the presence
7908        // quorum on credit would deadlock replica-repair in a
7909        // fully v12-capable close group.
7910        let mut locally_held: HashSet<XorName> = HashSet::new();
7911        for key in &keys_needing_network {
7912            if storage.exists(key).unwrap_or(false) {
7913                locally_held.insert(*key);
7914            }
7915        }
7916        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
7917            if !locally_held.contains(key) {
7918                // Replica-fetch path: we don't hold this key, so we
7919                // cannot have collected audit credit for it. Trust
7920                // Present claims to drive fetch-source promotion;
7921                // chunk-PUT payment_verifier is the security backstop
7922                // when the bytes actually arrive.
7923                return true;
7924            }
7925            if !capable_peer_snapshot.contains(peer) {
7926                // Pre-v12 / legacy peer that has never gossiped a
7927                // commitment. The v12 §6 holder-eligibility check
7928                // doesn't apply: their Present evidence comes through
7929                // the legacy path and we credit it unconditionally
7930                // so a mixed-version network stays live during
7931                // transition.
7932                return true;
7933            }
7934            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
7935                // Peer is commitment_capable (sticky) but currently
7936                // has no live commitment record on file (e.g. their
7937                // last gossip was evicted from the LRU cache, or it
7938                // failed verification). Withhold credit until they
7939                // re-prove storage under a fresh commitment.
7940                return false;
7941            };
7942            provers_snapshot.is_credited_holder(key, peer, hash)
7943        };
7944
7945        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
7946        {
7947            let q = queues.read().await;
7948            for key in &keys_needing_network {
7949                let Some(ev) = evidence.get(key) else {
7950                    continue;
7951                };
7952                if q.get_pending(key).is_none() {
7953                    continue;
7954                }
7955                let outcome = quorum::evaluate_key_evidence_with_holder_check(
7956                    key,
7957                    ev,
7958                    &targets,
7959                    config,
7960                    holder_credit,
7961                );
7962                evaluated.push((*key, outcome));
7963            }
7964        } // read lock released
7965
7966        // Step 4: Insert verified keys into PaidForList (no lock held).
7967        let mut paid_insert_keys: Vec<XorName> = Vec::new();
7968        for (key, outcome) in &evaluated {
7969            if matches!(
7970                outcome,
7971                KeyVerificationOutcome::QuorumVerified { .. }
7972                    | KeyVerificationOutcome::PaidListVerified { .. }
7973            ) {
7974                paid_insert_keys.push(*key);
7975            }
7976        }
7977        for key in &paid_insert_keys {
7978            if let Err(e) = paid_list.insert(key).await {
7979                warn!("Failed to add verified key to PaidForList: {e}");
7980            }
7981        }
7982
7983        // Verification established validity; the paid-list insert above records
7984        // it. Downloading the bytes is a separate duty, owed only by the
7985        // storage-admission group, asked on the same terms for every verified
7986        // key — the advertising peer's replica/paid labelling is a claim about
7987        // itself and carries no authority over what we store. This check is a
7988        // cheap pre-filter that keeps never-responsible keys out of the fetch
7989        // queue entirely; the authoritative gate is the per-attempt recheck in
7990        // `execute_single_fetch`, because a key can wait in the nearest-first
7991        // fetch queue long enough for this promotion-time answer to go stale.
7992        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
7993        for (key, outcome) in &evaluated {
7994            if matches!(
7995                outcome,
7996                KeyVerificationOutcome::QuorumVerified { .. }
7997                    | KeyVerificationOutcome::PaidListVerified { .. }
7998            ) && !storage.exists(key).unwrap_or(false)
7999                && is_storage_admitted(&self_id, key, p2p_node, config).await
8000            {
8001                fetch_allowed_keys.insert(*key);
8002            }
8003        }
8004
8005        // Step 5: Update queues with the evaluated outcomes.
8006        let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
8007        let mut q = queues.write().await;
8008        for (key, outcome) in evaluated {
8009            let replica_hint_sources = q
8010                .get_pending(&key)
8011                .map(|entry| entry.replica_hint_sources.clone())
8012                .unwrap_or_default();
8013            if let Some(ev) = evidence.get(&key) {
8014                if let Some(source) =
8015                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8016                {
8017                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8018                }
8019            }
8020            match outcome {
8021                KeyVerificationOutcome::QuorumVerified { sources }
8022                | KeyVerificationOutcome::PaidListVerified { sources } => {
8023                    let mut fetch_sources = sources;
8024                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8025                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8026                    if fetch_eligible && !fetch_sources.is_empty() {
8027                        let distance =
8028                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8029                        // Atomic remove+enqueue: on fetch_queue capacity miss
8030                        // the pending entry is preserved so this verified key
8031                        // is retried on the next cycle (no silent drop).
8032                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8033                        // Not terminal — either moved to fetch queue, or
8034                        // retained as pending until queue drains.
8035                    } else if fetch_eligible && fetch_sources.is_empty() {
8036                        warn!(
8037                            "Verified storage-admitted key {} has no holders yet; deferring retry",
8038                            hex::encode(key)
8039                        );
8040                        q.defer_pending(&key, config.verification_request_timeout);
8041                    } else {
8042                        q.remove_pending(&key);
8043                        terminal_keys.push(key);
8044                    }
8045                }
8046                KeyVerificationOutcome::QuorumFailed => {
8047                    q.remove_pending(&key);
8048                    terminal_keys.push(key);
8049                }
8050                KeyVerificationOutcome::QuorumInconclusive => {
8051                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8052                    q.defer_pending(&key, config.verification_request_timeout);
8053                }
8054            }
8055        }
8056        drop(q);
8057
8058        for (peer, bad_hint_count) in bad_singleton_hints {
8059            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8060            warn!(
8061                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8062                 sole-source replica hints; \
8063                 reporting {reports} bounded trust failure(s)"
8064            );
8065            for _ in 0..reports {
8066                p2p_node
8067                    .report_trust_event(
8068                        &peer,
8069                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8070                    )
8071                    .await;
8072            }
8073        }
8074    }
8075
8076    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8077    // the drain condition.
8078    update_bootstrap_after_verification(
8079        &terminal_keys,
8080        bootstrap_state,
8081        queues,
8082        is_bootstrapping,
8083        bootstrap_complete_notify,
8084    )
8085    .await;
8086
8087    let (pending_after, fetch_after, in_flight_after) = {
8088        let q = queues.read().await;
8089        (
8090            q.pending_count(),
8091            q.fetch_queue_count(),
8092            q.in_flight_count(),
8093        )
8094    };
8095    let terminal_key_count = terminal_keys.len();
8096    let elapsed_ms = cycle_started.elapsed().as_millis();
8097
8098    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8099        info!(
8100            target: "ant_node::replication::verification",
8101            "Slow replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8102        );
8103    } else {
8104        debug!(
8105            target: "ant_node::replication::verification",
8106            "Replication verification cycle: pending_start={initial_pending_count}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8107        );
8108    }
8109}
8110
8111/// Add peers that claimed possession as fallback fetch sources.
8112///
8113/// Paid-only advertisers make no possession claim and are absent from
8114/// `replica_hint_sources` by construction, so they are never added.
8115fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8116    for source in replica_hint_sources {
8117        if !sources.contains(source) {
8118            sources.push(*source);
8119        }
8120    }
8121}
8122
8123/// Return the sole replica advertiser when either the close group definitively
8124/// rejects the key or the advertiser explicitly denies possessing it.
8125/// Paid-only advertisements, corroborated replica hints, and inconclusive
8126/// rounds without that direct contradiction are deliberately non-penalizing.
8127fn punishable_singleton_replica_hint_source(
8128    replica_hint_sources: &HashSet<PeerId>,
8129    outcome: &KeyVerificationOutcome,
8130    evidence: &crate::replication::types::KeyVerificationEvidence,
8131) -> Option<PeerId> {
8132    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8133    // reserved for peers that actually claimed possession.
8134    if replica_hint_sources.len() != 1 {
8135        return None;
8136    }
8137    let source = *replica_hint_sources.iter().next()?;
8138    let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8139    let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8140
8141    (rejected_by_close_group || denied_possession).then_some(source)
8142}
8143
8144/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8145/// bootstrap pending set and transition out of bootstrapping when drained.
8146async fn update_bootstrap_after_verification(
8147    terminal_keys: &[XorName],
8148    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8149    queues: &Arc<RwLock<ReplicationQueues>>,
8150    is_bootstrapping: &Arc<RwLock<bool>>,
8151    bootstrap_complete_notify: &Arc<Notify>,
8152) {
8153    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8154        return;
8155    }
8156    {
8157        let mut bs = bootstrap_state.write().await;
8158        for key in terminal_keys {
8159            bs.remove_key(key);
8160        }
8161    }
8162    let q = queues.read().await;
8163    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8164        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8165    }
8166}
8167
8168/// Retire bootstrap work owed by a peer that permanently left the routing
8169/// table, then immediately re-check drain so this removal can complete
8170/// bootstrap without waiting for an unrelated pipeline event.
8171async fn update_bootstrap_after_peer_removed(
8172    peer: &PeerId,
8173    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8174    queues: &Arc<RwLock<ReplicationQueues>>,
8175    is_bootstrapping: &Arc<RwLock<bool>>,
8176    bootstrap_complete_notify: &Arc<Notify>,
8177) {
8178    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8179    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8180
8181    if !orphaned_keys.is_empty() {
8182        let mut state = bootstrap_state.write().await;
8183        for key in &orphaned_keys {
8184            state.remove_key(key);
8185        }
8186    }
8187
8188    if orphaned_keys.is_empty() && !cleared_rejection {
8189        return;
8190    }
8191    let q = queues.read().await;
8192    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8193        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8194    }
8195}
8196
8197/// Periodic bootstrap-drain self-healing, run on every verification worker
8198/// tick until bootstrap drains.
8199///
8200/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8201/// recording of a capacity rejection leaves an entry no future event can
8202/// clear — `max_age` expiry is its only exit. And a clean-cycle
8203/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8204/// quiet node the drain condition can become true with nothing left to
8205/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8206/// drain itself, so this is invoked before `run_verification_cycle`'s
8207/// early-returns.
8208async fn expire_and_recheck_bootstrap_drain(
8209    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8210    queues: &Arc<RwLock<ReplicationQueues>>,
8211    is_bootstrapping: &Arc<RwLock<bool>>,
8212    bootstrap_complete_notify: &Arc<Notify>,
8213    max_age: Duration,
8214) {
8215    if bootstrap_state.read().await.is_drained() {
8216        return;
8217    }
8218    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8219    let q = queues.read().await;
8220    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8221        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8222    }
8223}
8224
8225/// Set `is_bootstrapping` to `false` and wake all waiters.
8226async fn complete_bootstrap(
8227    is_bootstrapping: &Arc<RwLock<bool>>,
8228    bootstrap_complete_notify: &Arc<Notify>,
8229) {
8230    *is_bootstrapping.write().await = false;
8231    bootstrap_complete_notify.notify_waiters();
8232    info!("Replication bootstrap complete");
8233}
8234
8235// ---------------------------------------------------------------------------
8236// Fetch types and single-fetch executor
8237// ---------------------------------------------------------------------------
8238
8239/// Result classification for a single fetch attempt.
8240enum FetchResult {
8241    /// Data fetched, integrity-checked, and stored successfully.
8242    Stored,
8243    /// Content-address integrity check failed — do not retry.
8244    IntegrityFailed,
8245    /// Source failed (network error or non-success response) — retryable.
8246    SourceFailed,
8247    /// Live routing state no longer places this node in the storage-admission
8248    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8249    /// the fetch was serving has lapsed, so no alternate source is tried and
8250    /// no trust event is reported: the source did nothing wrong.
8251    NoLongerResponsible,
8252}
8253
8254/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8255/// worker loop to update queue state.
8256struct FetchOutcome {
8257    key: XorName,
8258    result: FetchResult,
8259}
8260
8261/// What the fetch worker must do next for a key whose fetch attempt resolved.
8262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8263enum FetchFollowUp {
8264    /// The key terminally left the fetch pipeline (its in-flight entry is
8265    /// removed and any verification retry-slot reservation released); the
8266    /// caller must run bootstrap accounting for it.
8267    Terminal,
8268    /// The key returned to `pending_verify` for a later verification round.
8269    RequeuedForVerification,
8270    /// Retry immediately from this next untried verified source.
8271    RetryFrom(PeerId),
8272}
8273
8274/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8275///
8276/// Split out of the fetch-worker loop so the per-variant queue transitions
8277/// are unit-testable without a live network. The caller holds the queues
8278/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8279/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8280/// retry-slot reservation, and the caller's terminal handling shrinks the
8281/// bootstrap pending set — dropping the key without that accounting would
8282/// stall bootstrap drain forever.
8283///
8284/// The nursery `option_if_let_else` rewrite is impossible here: both
8285/// `map_or_else` closures would need `&mut *q` simultaneously.
8286#[allow(clippy::option_if_let_else)]
8287fn apply_fetch_result(
8288    q: &mut ReplicationQueues,
8289    key: &XorName,
8290    result: &FetchResult,
8291    verification_retry_after: Duration,
8292) -> FetchFollowUp {
8293    match result {
8294        FetchResult::Stored | FetchResult::NoLongerResponsible => {
8295            q.complete_fetch(key);
8296            FetchFollowUp::Terminal
8297        }
8298        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8299            if let Some(next_peer) = q.retry_fetch(key) {
8300                FetchFollowUp::RetryFrom(next_peer)
8301            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8302                FetchFollowUp::RequeuedForVerification
8303            } else {
8304                FetchFollowUp::Terminal
8305            }
8306        }
8307    }
8308}
8309
8310/// Whether this node currently sits inside the storage-admission group for
8311/// `key`, per live local routing state.
8312///
8313/// This is the one question every storage decision in this module asks; see
8314/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8315/// network I/O — but it awaits into the DHT manager, so callers must not
8316/// hold the queues lock across it.
8317async fn is_storage_admitted(
8318    self_id: &PeerId,
8319    key: &XorName,
8320    p2p_node: &Arc<P2PNode>,
8321    config: &ReplicationConfig,
8322) -> bool {
8323    admission::is_responsible(
8324        self_id,
8325        key,
8326        p2p_node,
8327        storage_admission_width(config.close_group_size),
8328    )
8329    .await
8330}
8331
8332#[allow(clippy::too_many_lines)]
8333/// Execute a single fetch request against `source` for `key`.
8334///
8335/// Handles encoding, network I/O, integrity checking, storage, and trust
8336/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8337/// queue state without holding any locks during the network round-trip.
8338///
8339/// This is the authoritative storage-responsibility gate: each attempt —
8340/// including every per-source retry, which re-enters here — rechecks live
8341/// routing state before spending bandwidth, and once more before writing
8342/// bytes that arrived after a round-trip. The verification-time check that
8343/// promoted the key into the fetch queue is only a pre-filter; the queue is
8344/// nearest-first and deep, so a promotion decision can go stale under
8345/// topology churn before the key is ever dequeued.
8346async fn execute_single_fetch(
8347    p2p_node: Arc<P2PNode>,
8348    storage: Arc<LmdbStorage>,
8349    config: Arc<ReplicationConfig>,
8350    key: XorName,
8351    source: PeerId,
8352) -> FetchOutcome {
8353    let self_id = *p2p_node.peer_id();
8354    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8355        debug!(
8356            "Skipping fetch for {}: no longer in the storage-admission group",
8357            hex::encode(key)
8358        );
8359        return FetchOutcome {
8360            key,
8361            result: FetchResult::NoLongerResponsible,
8362        };
8363    }
8364
8365    let request = protocol::FetchRequest { key };
8366    let msg = ReplicationMessage {
8367        request_id: rand::thread_rng().gen::<u64>(),
8368        body: ReplicationMessageBody::FetchRequest(request),
8369    };
8370
8371    let encoded = match msg.encode() {
8372        Ok(data) => data,
8373        Err(e) => {
8374            warn!("Failed to encode fetch request: {e}");
8375            return FetchOutcome {
8376                key,
8377                result: FetchResult::SourceFailed,
8378            };
8379        }
8380    };
8381
8382    let result = p2p_node
8383        .send_request(
8384            &source,
8385            REPLICATION_PROTOCOL_ID,
8386            encoded,
8387            config.fetch_request_timeout,
8388        )
8389        .await;
8390
8391    match result {
8392        Ok(response) => {
8393            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8394                p2p_node
8395                    .report_trust_event(
8396                        &source,
8397                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8398                    )
8399                    .await;
8400                return FetchOutcome {
8401                    key,
8402                    result: FetchResult::SourceFailed,
8403                };
8404            };
8405
8406            match resp_msg.body {
8407                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8408                    key: resp_key,
8409                    data,
8410                }) => {
8411                    // Validate the response key matches the requested key.
8412                    // A malicious peer could serve valid data for a different
8413                    // key, passing integrity checks while the requested key
8414                    // is falsely marked as fetched.
8415                    if resp_key != key {
8416                        warn!(
8417                            "Fetch response key mismatch: requested {}, got {}",
8418                            hex::encode(key),
8419                            hex::encode(resp_key)
8420                        );
8421                        p2p_node
8422                            .report_trust_event(
8423                                &source,
8424                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8425                            )
8426                            .await;
8427                        return FetchOutcome {
8428                            key,
8429                            result: FetchResult::IntegrityFailed,
8430                        };
8431                    }
8432
8433                    // Enforce chunk size invariant on fetched data.
8434                    // Checked before the content-address hash to avoid
8435                    // hashing up to 10 MiB of oversized junk data.
8436                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8437                        warn!(
8438                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8439                            hex::encode(resp_key),
8440                            data.len(),
8441                            crate::ant_protocol::MAX_CHUNK_SIZE,
8442                        );
8443                        p2p_node
8444                            .report_trust_event(
8445                                &source,
8446                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8447                            )
8448                            .await;
8449                        return FetchOutcome {
8450                            key,
8451                            result: FetchResult::IntegrityFailed,
8452                        };
8453                    }
8454
8455                    // Content-address integrity check.
8456                    let computed = crate::client::compute_address(&data);
8457                    if computed != resp_key {
8458                        warn!(
8459                            "Fetched record integrity check failed: expected {}, got {}",
8460                            hex::encode(resp_key),
8461                            hex::encode(computed)
8462                        );
8463                        p2p_node
8464                            .report_trust_event(
8465                                &source,
8466                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8467                            )
8468                            .await;
8469                        return FetchOutcome {
8470                            key,
8471                            result: FetchResult::IntegrityFailed,
8472                        };
8473                    }
8474
8475                    // Responsibility can lapse during the network round-trip.
8476                    // The bandwidth is already spent; declining the write is
8477                    // what still avoids the disk write and the later
8478                    // fetch→store→prune churn. Edge flapping is dampened by
8479                    // the margin `storage_admission_width` adds over
8480                    // `close_group_size`.
8481                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8482                        debug!(
8483                            "Fetched {} but responsibility lapsed in transit; not storing",
8484                            hex::encode(key)
8485                        );
8486                        return FetchOutcome {
8487                            key,
8488                            result: FetchResult::NoLongerResponsible,
8489                        };
8490                    }
8491
8492                    if let Err(e) = storage.put(&resp_key, &data).await {
8493                        warn!(
8494                            "Failed to store fetched record {}: {e}",
8495                            hex::encode(resp_key)
8496                        );
8497                        return FetchOutcome {
8498                            key,
8499                            result: FetchResult::SourceFailed,
8500                        };
8501                    }
8502
8503                    FetchOutcome {
8504                        key,
8505                        result: FetchResult::Stored,
8506                    }
8507                }
8508                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8509                    ..
8510                }) => {
8511                    // This peer was selected as a fetch source because it
8512                    // recently answered `Present` during verification. A
8513                    // subsequent NotFound is evidence of a stale/false claim
8514                    // or chunk wiping, so penalize lightly and try another
8515                    // verified source.
8516                    warn!(
8517                        "Fetch: verified source {source} returned NotFound for {}",
8518                        hex::encode(key)
8519                    );
8520                    p2p_node
8521                        .report_trust_event(
8522                            &source,
8523                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8524                        )
8525                        .await;
8526                    FetchOutcome {
8527                        key,
8528                        result: FetchResult::SourceFailed,
8529                    }
8530                }
8531                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8532                    reason,
8533                    ..
8534                }) => {
8535                    warn!(
8536                        "Fetch: peer {source} returned error for {}: {reason}",
8537                        hex::encode(key)
8538                    );
8539                    p2p_node
8540                        .report_trust_event(
8541                            &source,
8542                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8543                        )
8544                        .await;
8545                    FetchOutcome {
8546                        key,
8547                        result: FetchResult::SourceFailed,
8548                    }
8549                }
8550                _ => {
8551                    // Unexpected message type — treat as malformed.
8552                    p2p_node
8553                        .report_trust_event(
8554                            &source,
8555                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8556                        )
8557                        .await;
8558                    FetchOutcome {
8559                        key,
8560                        result: FetchResult::SourceFailed,
8561                    }
8562                }
8563            }
8564        }
8565        Err(e) => {
8566            debug!("Fetch request to {source} failed: {e}");
8567            // No ApplicationFailure here — P2PNode::send_request() already
8568            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
8569            FetchOutcome {
8570                key,
8571                result: FetchResult::SourceFailed,
8572            }
8573        }
8574    }
8575}
8576
8577// ---------------------------------------------------------------------------
8578// Audit result handler
8579// ---------------------------------------------------------------------------
8580
8581/// Format the first confirmed-failed key as a 16-hex-char label.
8582///
8583/// Pairs with `challenged_peer` to form a stable cross-host correlation
8584/// handle in the audit-failure log line, e.g.
8585///
8586/// ```text
8587/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
8588/// ```
8589///
8590/// Falls back to `"0x"` when the list is empty so the log line never
8591/// contains a misleading default.
8592fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8593    confirmed_failed_keys.first().map_or_else(
8594        || "0x".to_string(),
8595        |k| format!("0x{}", hex::encode(&k[..8])),
8596    )
8597}
8598
8599/// Execute the side effects for a subtree storage-commitment audit failure.
8600///
8601/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
8602/// legitimately time out on slow or loaded honest peers, so it never touches the
8603/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
8604/// failures still penalise immediately and revoke holder credit.
8605async fn handle_subtree_failed_audit(
8606    challenged_peer: &PeerId,
8607    confirmed_failed_key_count: usize,
8608    reason: &AuditFailureReason,
8609    p2p_node: &Arc<P2PNode>,
8610    sync_state: &Arc<RwLock<NeighborSyncState>>,
8611    recent_provers: &Arc<RwLock<RecentProvers>>,
8612) {
8613    if matches!(reason, AuditFailureReason::Timeout) {
8614        debug!(
8615            "Audit timeout for {challenged_peer} fully graced \
8616             (subtree audit does not evict on timeout)"
8617        );
8618        return;
8619    }
8620
8621    // The caller already logged the rich failure line with reason + per-category
8622    // summary; avoid a redundant second error log here.
8623    let _ = confirmed_failed_key_count;
8624    {
8625        let mut state = sync_state.write().await;
8626        state.clear_active_bootstrap_claim(challenged_peer);
8627    }
8628    {
8629        let mut provers_guard = recent_provers.write().await;
8630        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8631    }
8632    p2p_node
8633        .report_trust_event(
8634            challenged_peer,
8635            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8636        )
8637        .await;
8638}
8639
8640/// Handle audit result: log findings and emit trust events.
8641async fn handle_subtree_audit_result(
8642    result: &AuditTickResult,
8643    p2p_node: &Arc<P2PNode>,
8644    sync_state: &Arc<RwLock<NeighborSyncState>>,
8645    recent_provers: &Arc<RwLock<RecentProvers>>,
8646    config: &ReplicationConfig,
8647) {
8648    match result {
8649        AuditTickResult::Passed {
8650            challenged_peer,
8651            keys_checked,
8652        } => {
8653            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8654            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8655            // Peer responded normally — clear the active bootstrap claim while
8656            // retaining history so a later claim is treated as repeated abuse.
8657            {
8658                let mut state = sync_state.write().await;
8659                state.clear_active_bootstrap_claim(challenged_peer);
8660            }
8661            p2p_node
8662                .report_trust_event(
8663                    challenged_peer,
8664                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8665                )
8666                .await;
8667        }
8668        AuditTickResult::Failed {
8669            evidence,
8670            no_response_class,
8671        } => {
8672            if let FailureEvidence::AuditFailure {
8673                challenged_peer,
8674                confirmed_failed_keys,
8675                summary,
8676                reason,
8677                ..
8678            } = evidence
8679            {
8680                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
8681                // Rich diagnostics (from main's audit-failure logging) + the
8682                // first-failed-key correlation handle.
8683                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8684                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8685                error!(
8686                    "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}",
8687                    audit_failure_class,
8688                    confirmed_failed_keys.len(),
8689                    summary.challenged_keys,
8690                    summary.absent_keys,
8691                    summary.digest_mismatch_keys,
8692                );
8693                // Route the side effects through the subtree-only failure path.
8694                // Responsible-chunk `AuditChallenge` handling intentionally uses
8695                // its own old immediate-penalty handler below.
8696                handle_subtree_failed_audit(
8697                    challenged_peer,
8698                    confirmed_failed_keys.len(),
8699                    reason,
8700                    p2p_node,
8701                    sync_state,
8702                    recent_provers,
8703                )
8704                .await;
8705            }
8706        }
8707        AuditTickResult::BootstrapClaim { peer } => {
8708            // Gap 6: BootstrapClaimAbuse grace period in audit path.
8709            // Separate state mutation from network I/O to avoid holding the
8710            // write lock across report_trust_event.
8711            let should_report = {
8712                let now = Instant::now();
8713                let mut state = sync_state.write().await;
8714                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8715                {
8716                    BootstrapClaimObservation::WithinGrace { .. } => {
8717                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8718                        false
8719                    }
8720                    BootstrapClaimObservation::PastGrace { first_seen } => {
8721                        warn!(
8722                            "Audit: peer {peer} claiming bootstrap past grace period \
8723                             ({:?} > {:?}), reporting abuse",
8724                            now.duration_since(first_seen),
8725                            config.bootstrap_claim_grace_period,
8726                        );
8727                        true
8728                    }
8729                    BootstrapClaimObservation::Repeated { first_seen } => {
8730                        warn!(
8731                            "Audit: peer {peer} repeated bootstrap claim after previously \
8732                             stopping; first claim was {:?} ago, reporting abuse",
8733                            now.duration_since(first_seen),
8734                        );
8735                        true
8736                    }
8737                }
8738            };
8739            if should_report {
8740                p2p_node
8741                    .report_trust_event(
8742                        peer,
8743                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8744                    )
8745                    .await;
8746            }
8747        }
8748        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8749    }
8750}
8751
8752/// Whether a confirmed audit failure with this reason clears the peer's active
8753/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
8754/// bootstrapping); every confirmed storage-integrity reason does.
8755///
8756/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
8757/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
8758/// still reports the normal audit trust penalty.
8759fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
8760    !matches!(reason, AuditFailureReason::Timeout)
8761}
8762
8763/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
8764/// events and manage bootstrap-claim state.
8765///
8766/// This is intentionally separate from the subtree audit result handler. A
8767/// responsible-chunk `AuditChallenge` `Failed` result reports
8768/// `ApplicationFailure` immediately for every reason, including `Timeout`,
8769/// restoring the pre-ADR-0002 behaviour.
8770#[allow(clippy::too_many_lines)]
8771async fn handle_audit_result(
8772    result: &AuditTickResult,
8773    p2p_node: &Arc<P2PNode>,
8774    sync_state: &Arc<RwLock<NeighborSyncState>>,
8775    config: &ReplicationConfig,
8776) {
8777    match result {
8778        AuditTickResult::Passed {
8779            challenged_peer,
8780            keys_checked,
8781        } => {
8782            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
8783            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8784            {
8785                let mut state = sync_state.write().await;
8786                state.clear_active_bootstrap_claim(challenged_peer);
8787            }
8788            p2p_node
8789                .report_trust_event(
8790                    challenged_peer,
8791                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8792                )
8793                .await;
8794        }
8795        AuditTickResult::Failed {
8796            evidence,
8797            no_response_class,
8798        } => {
8799            if let FailureEvidence::AuditFailure {
8800                challenged_peer,
8801                confirmed_failed_keys,
8802                summary,
8803                reason,
8804                ..
8805            } = evidence
8806            {
8807                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
8808                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8809                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8810                error!(
8811                    "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}",
8812                    audit_failure_class,
8813                    confirmed_failed_keys.len(),
8814                    summary.challenged_keys,
8815                    summary.absent_keys,
8816                    summary.digest_mismatch_keys,
8817                );
8818                if audit_failure_clears_bootstrap_claim(reason) {
8819                    let mut state = sync_state.write().await;
8820                    state.clear_active_bootstrap_claim(challenged_peer);
8821                } else {
8822                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
8823                }
8824                p2p_node
8825                    .report_trust_event(
8826                        challenged_peer,
8827                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8828                    )
8829                    .await;
8830            }
8831        }
8832        AuditTickResult::BootstrapClaim { peer } => {
8833            let should_report = {
8834                let now = Instant::now();
8835                let mut state = sync_state.write().await;
8836                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8837                {
8838                    BootstrapClaimObservation::WithinGrace { .. } => {
8839                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8840                        false
8841                    }
8842                    BootstrapClaimObservation::PastGrace { first_seen } => {
8843                        warn!(
8844                            "Audit: peer {peer} claiming bootstrap past grace period \
8845                             ({:?} > {:?}), reporting abuse",
8846                            now.duration_since(first_seen),
8847                            config.bootstrap_claim_grace_period,
8848                        );
8849                        true
8850                    }
8851                    BootstrapClaimObservation::Repeated { first_seen } => {
8852                        warn!(
8853                            "Audit: peer {peer} repeated bootstrap claim after previously \
8854                             stopping; first claim was {:?} ago, reporting abuse",
8855                            now.duration_since(first_seen),
8856                        );
8857                        true
8858                    }
8859                }
8860            };
8861            if should_report {
8862                p2p_node
8863                    .report_trust_event(
8864                        peer,
8865                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8866                    )
8867                    .await;
8868            }
8869        }
8870        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8871    }
8872}
8873
8874/// Whether a confirmed audit failure with this reason should revoke the
8875/// peer's `recent_provers` holder credit immediately (v12 §6).
8876///
8877/// `true` for any reason where the peer actually answered (or admitted
8878/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
8879/// bytes for committed key"), `MalformedResponse` — these prove the
8880/// peer no longer holds what it committed to, so it must not keep
8881/// holder credit for the proof TTL. `false` for `Timeout`: a single
8882/// dropped packet must not strip an honest peer; the 40-min TTL is the
8883/// deliberate liveness cushion there.
8884fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
8885    !matches!(reason, AuditFailureReason::Timeout)
8886}
8887
8888/// Apply the holder-credit revocation decision for a confirmed audit
8889/// failure. Pure over `RecentProvers` so the handler wiring is unit-
8890/// testable without a live `P2PNode`: the production `Failed` arm of
8891/// `handle_subtree_audit_result` calls exactly this.
8892fn apply_audit_failure_credit_revocation(
8893    provers: &mut RecentProvers,
8894    challenged_peer: &PeerId,
8895    reason: &AuditFailureReason,
8896) {
8897    if audit_failure_revokes_holder_credit(reason) {
8898        provers.forget_peer(challenged_peer);
8899    }
8900}
8901
8902// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
8903
8904// ---------------------------------------------------------------------------
8905// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
8906// ---------------------------------------------------------------------------
8907
8908/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
8909/// message handler passes one value instead of a long argument list; all
8910/// fields are cheap `Arc` clones.
8911#[derive(Clone)]
8912struct GossipAuditTrigger {
8913    p2p_node: Arc<P2PNode>,
8914    config: Arc<ReplicationConfig>,
8915    recent_provers: Arc<RwLock<RecentProvers>>,
8916    sync_state: Arc<RwLock<NeighborSyncState>>,
8917    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
8918    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
8919    /// only when a real audit is about to be sent — never by a losing lottery
8920    /// ticket — so gossip traffic alone can never suppress a paid first audit.
8921    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
8922    detached_task_tracker: TaskTracker,
8923    /// Gossip-private lottery attempt window: stamped on every roll (win or
8924    /// lose) so a gossip flood cannot re-roll the lottery within the window.
8925    /// The first-audit scheduler never reads this map.
8926    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
8927}
8928
8929/// What a gossip ingest yields for the audit trigger: the commitment hash to
8930/// pin and the `key_count` needed to size the response deadline from the actual
8931/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
8932/// or not) so a stable-keyset node stays auditable — not just on its first
8933/// commitment.
8934#[derive(Debug, Clone, Copy)]
8935struct AuditTarget {
8936    pin_hash: [u8; 32],
8937    key_count: u32,
8938}
8939
8940/// ADR-0004: a commitment that backed a payment, surfaced by the payment
8941/// verifier's cross-check so it can receive a **deterministic first audit**.
8942///
8943/// Sent from the verifier to the replication engine's first-audit drainer. The
8944/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
8945/// audits of the same peer revert to the gossip lottery), orders most-recently-
8946/// monetized first, and runs the same `run_subtree_audit` under the same
8947/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
8948#[derive(Debug, Clone, Copy)]
8949pub struct MonetizedPinEvent {
8950    /// The peer whose commitment backed the payment.
8951    pub peer: PeerId,
8952    /// The pinned commitment hash.
8953    pub pin: [u8; 32],
8954    /// The committed key count (sizes the audit deadline).
8955    pub key_count: u32,
8956    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
8957    /// pin whose quote is older than the answerability window (ADR-0004 A1
8958    /// guardrail A): with grace removed, challenging an aged-out pin would
8959    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
8960    pub quote_ts: SystemTime,
8961}
8962
8963/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
8964/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
8965/// stamps `now`), `false` if it was audited within
8966/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
8967/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
8968/// without a live node: a burst of gossips from one peer yields at most one
8969/// `true` per cooldown window.
8970fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8971    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8972    let known = match map.get(peer) {
8973        Some(&last) => {
8974            if now.saturating_duration_since(last) < cooldown {
8975                return false;
8976            }
8977            true
8978        }
8979        None => false,
8980    };
8981    // Bound the map under churn like its siblings (drop the oldest stamp) before
8982    // admitting a brand-new peer.
8983    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
8984        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
8985            map.remove(&victim);
8986        }
8987    }
8988    map.insert(*peer, now);
8989    true
8990}
8991
8992/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
8993/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
8994/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
8995/// already covered; the authoritative check-and-stamp still runs at promotion,
8996/// so this is only an optimization and never the security boundary.
8997fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8998    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8999    map.get(peer).map_or(true, |&last| {
9000        now.saturating_duration_since(last) >= cooldown
9001    })
9002}
9003
9004/// The gossip-audit launch decision in ONE place so the ordering is shared
9005/// between production and its test (ADR-0002 "occasional surprise exams").
9006///
9007/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9008/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9009/// sampled first, a gossip flood would re-roll it on every message until one
9010/// won, multiplying audits, so each peer gets at most one lottery roll per
9011/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9012/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9013/// also consults — only after a WIN, i.e. only when a real audit is about to be
9014/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9015/// wire, so it must not defer a paid first audit (repeatable losses could
9016/// otherwise hold a monetized pin past its answerability window). Production
9017/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9018/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9019/// here fails the test.
9020fn audit_launch_decision(
9021    attempts: &mut HashMap<PeerId, Instant>,
9022    launched: &mut HashMap<PeerId, Instant>,
9023    peer: &PeerId,
9024    now: Instant,
9025    lottery_wins: bool,
9026) -> bool {
9027    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9028    // window even on a loss; private to the gossip path).
9029    if !cooldown_allows_audit(attempts, peer, now) {
9030        return false;
9031    }
9032    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9033    // shared.
9034    if !lottery_wins {
9035        return false;
9036    }
9037    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9038    // either path still suppresses this launch), stamped only on launch.
9039    cooldown_allows_audit(launched, peer, now)
9040}
9041
9042/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9043/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9044/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9045/// handling is never blocked on a network round-trip.
9046async fn maybe_trigger_gossip_audit(
9047    trigger: &GossipAuditTrigger,
9048    peer: &PeerId,
9049    target: AuditTarget,
9050) {
9051    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9052    // lives in the pure `audit_launch_decision` so the ordering is shared with
9053    // its test. Sample the lottery here, then let the helper apply the gates.
9054    let now = Instant::now();
9055    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9056    {
9057        // Lock order: attempts before the shared cooldown; this is the only
9058        // place both are held together.
9059        let mut attempts = trigger.lottery_attempts.write().await;
9060        let mut launched = trigger.cooldown.write().await;
9061        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9062            return;
9063        }
9064    }
9065
9066    let detached_task_tracker = trigger.detached_task_tracker.clone();
9067    let trigger = trigger.clone();
9068    let peer = *peer;
9069    detached_task_tracker.spawn(async move {
9070        let credit = storage_commitment_audit::AuditCredit {
9071            recent_provers: &trigger.recent_provers,
9072        };
9073        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9074            &trigger.p2p_node,
9075            &trigger.config,
9076            &peer,
9077            target.pin_hash,
9078            target.key_count,
9079            Some(&credit),
9080            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9081        )
9082        .await;
9083        handle_subtree_audit_result(
9084            &result,
9085            &trigger.p2p_node,
9086            &trigger.sync_state,
9087            &trigger.recent_provers,
9088            &trigger.config,
9089        )
9090        .await;
9091    });
9092}
9093
9094/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9095///
9096/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9097/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9098/// of its last attempt. Holds one write lock across the decision so two
9099/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9100/// caller's expensive verify so a slow/failed verify still rate-limits the next
9101/// message. Bounds the map under a flood of distinct peer ids.
9102async fn sig_verify_rate_limit_ok(
9103    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9104    source: &PeerId,
9105    now: Instant,
9106) -> bool {
9107    let mut attempts = sig_verify_attempts.write().await;
9108    if let Some(&last) = attempts.get(source) {
9109        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9110            return false;
9111        }
9112    }
9113    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9114        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9115            attempts.remove(&victim);
9116        }
9117    }
9118    attempts.insert(*source, now);
9119    true
9120}
9121
9122/// Verify + store an inbound commitment from a gossip peer.
9123///
9124/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9125/// the bootstrap-sync loop. Drops the commitment unless all five gates
9126/// pass:
9127///   1. `source` is in our DHT routing table (sybil/churn cap).
9128///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9129///      binding to the authenticated transport peer).
9130///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9131///      (the embedded pubkey actually belongs to the claimed identity —
9132///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9133///   4. `verify_commitment_signature(commitment)` succeeds against the
9134///      embedded public key. The signed payload binds the pubkey, so an
9135///      adversary cannot swap the key while keeping the body.
9136///   5. The cache has room or this is an update for an existing entry
9137///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9138///
9139/// On all-pass, the commitment is stored as the auditor's per-peer
9140/// "last known commitment" for use as `expected_commitment_hash` in
9141/// future audits.
9142///
9143/// Failures (no commitment / mismatched peer id / bad signature) are
9144/// silent drops — gossip is best-effort and a malformed commitment from
9145/// one peer should not affect anything else.
9146///
9147/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9148/// or not its root changed), so the caller can run a probabilistic,
9149/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9150/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9151/// being auditable, so it cannot pass one audit and then delete data while
9152/// re-gossiping the same root forever. The cooldown + probability bound the
9153/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9154/// gate) or there is nothing to pin.
9155///
9156/// Handle a capable peer gossiping `None` (a commitment downgrade).
9157///
9158/// A capable peer that previously gossiped a commitment but now gossips `None`
9159/// is trying to drop off the audit path. Within the answerability window we keep
9160/// the cached commitment pinned AND return it as an audit target so this gossip
9161/// still schedules a subtree audit against the peer's last known commitment — if
9162/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9163/// the trigger MUST fire here or the downgrade is never re-challenged).
9164///
9165/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9166/// honours for its own retired commitment: once that elapses since we last
9167/// received the peer's commitment, an honest peer has legitimately retired that
9168/// root (its responder side `retire_current`s and lets it age out) and can no
9169/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9170/// failure, so we then forget the cached commitment (keeping the sticky
9171/// `commitment_capable` bit) and stop pinning it.
9172async fn handle_commitment_downgrade(
9173    source: &PeerId,
9174    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9175) -> Option<AuditTarget> {
9176    let now = Instant::now();
9177    let cached = {
9178        let map = last_commitment_by_peer.read().await;
9179        map.get(source).and_then(|rec| {
9180            if !rec.commitment_capable {
9181                return None;
9182            }
9183            let last = rec.last_commitment()?;
9184            let pin = rec.commitment_hash()?;
9185            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9186            Some((pin, last.key_count, fresh))
9187        })
9188    };
9189    match cached {
9190        Some((pin, key_count, true)) => {
9191            warn!(
9192                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9193                 (downgrade attempt); auditing against its last cached commitment"
9194            );
9195            Some(AuditTarget {
9196                pin_hash: pin,
9197                key_count,
9198            })
9199        }
9200        Some((_, _, false)) => {
9201            // Cached commitment has aged past the answerability window — forget
9202            // it so we stop pinning a root the peer is no longer obliged to
9203            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9204            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9205            // from this peer may have refreshed `received_at` in the gap between
9206            // our read and write locks; if so, leave its fresh commitment intact.
9207            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9208                let still_stale =
9209                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9210                if still_stale {
9211                    rec.clear_commitment();
9212                    debug!(
9213                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9214                         commitment aged past the answerability TTL; forgetting it"
9215                    );
9216                }
9217            }
9218            None
9219        }
9220        None => None,
9221    }
9222}
9223
9224async fn ingest_peer_commitment(
9225    source: &PeerId,
9226    commitment: Option<&StorageCommitment>,
9227    p2p_node: &Arc<P2PNode>,
9228    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9229    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9230    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9231) -> Option<AuditTarget> {
9232    let Some(c) = commitment else {
9233        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9234    };
9235    // RT-membership gate: only accept commitments from peers in our
9236    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9237    // populate the cache, which closes the hole where a flood of
9238    // off-RT identities could fill the cap and evict honest
9239    // peers. The neighbor-sync request handler applies the same gate
9240    // before admitting inbound replication hints (see neighbor_sync.rs
9241    // `sender_in_rt`); we mirror that policy here for the commitment
9242    // piggyback.
9243    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9244        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9245        return None;
9246    }
9247    // Peer-id binding: the commitment's claimed sender must match the
9248    // authenticated transport peer (`source`). Defeats relay/replay
9249    // and also pins which embedded public key we are about to verify
9250    // against — the verify itself trusts the embedded key, so the
9251    // peer-id binding is the link to a real identity.
9252    if &c.sender_peer_id != source.as_bytes() {
9253        warn!(
9254            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9255             (dropped, possible relay attempt)"
9256        );
9257        return None;
9258    }
9259    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9260    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9261    // with a throwaway key they own and lie about which identity it
9262    // belongs to (the embedded-key signature would verify trivially).
9263    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9264    if derived_peer_id != c.sender_peer_id {
9265        warn!(
9266            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9267             {source} (dropped, throwaway-key attack)"
9268        );
9269        return None;
9270    }
9271    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9272    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9273    // sybil/RT-membership-bypassing peer that flooded valid-looking
9274    // gossip would otherwise burn CPU on every message. The rate
9275    // limit is checked AFTER cheap structural gates (RT, peer-id
9276    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9277    //
9278    // Tracked in `sig_verify_attempts` (separate from
9279    // last_commitment_by_peer) so EVERY attempt — successful or not —
9280    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9281    // would skip the cap for peers we've never successfully verified,
9282    // letting a flood of invalid-but-structurally-plausible gossips
9283    // burn CPU.
9284    let now = Instant::now();
9285    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9286        debug!(
9287            "ingest_peer_commitment: rate-limited sig verify from {source} \
9288             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9289        );
9290        return None;
9291    }
9292    // Signature verify, using the public key embedded in the commitment
9293    // itself. The pubkey is bound by the signature payload (see
9294    // commitment_signed_payload) so an adversary cannot keep the body
9295    // and swap the key to one they hold the secret for.
9296    if !crate::replication::commitment::verify_commitment_signature(c) {
9297        warn!(
9298            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9299             (dropped, forged commitment)"
9300        );
9301        return None;
9302    }
9303    // The new commitment's hash, used to store and to pin for the audit target.
9304    let new_hash = commitment_hash(c);
9305    let mut map = last_commitment_by_peer.write().await;
9306    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9307    // evict an arbitrary existing entry to make room. Updates for peers
9308    // already in the map are always accepted (they replace, not grow).
9309    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9310        // Drop one arbitrary entry. HashMap iter order is random which
9311        // is fine — over time PeerRemoved cleanup keeps the working set
9312        // anchored on the real RT membership; this cap only fires under
9313        // active flooding attempts.
9314        if let Some(victim) = map.keys().next().copied() {
9315            map.remove(&victim);
9316            warn!(
9317                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9318                 evicted {victim} to admit {source}"
9319            );
9320        }
9321    }
9322    // Preserve sticky commitment_capable across updates — once true,
9323    // always true. New entries start with capable = true (we just
9324    // verified a valid commitment from this peer).
9325    map.entry(*source)
9326        .and_modify(|r| {
9327            // set_commitment refreshes the cached hash (§13) alongside the
9328            // commitment + received_at so they never drift.
9329            r.set_commitment(c.clone(), now);
9330            r.last_sig_verify_at = now;
9331            r.commitment_capable = true; // sticky-redundant but explicit
9332        })
9333        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9334    drop(map);
9335    // Record the sticky "ever v12-capable" bit in a set independent of
9336    // `last_commitment_by_peer` (whose entries can be evicted by
9337    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9338    // shield and the §6 holder-eligibility closure consult to decide
9339    // whether the peer is expected to speak v12.
9340    //
9341    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9342    // identity-rotation attacks: once full, new entries are refused.
9343    // Refusal degrades over-cap peers to the behaviour before this set
9344    // existed (treated as legacy on rejoin), which is not a security
9345    // regression and preserves the historic set stable.
9346    {
9347        let mut set = ever_capable_peers.write().await;
9348        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9349            set.insert(*source);
9350        } else {
9351            warn!(
9352                "ingest_peer_commitment: ever_capable_peers at cap \
9353                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9354            );
9355        }
9356    }
9357    // Return an audit target for EVERY valid stored commitment (changed or
9358    // not), so the caller's cooldown+probability-gated trigger keeps a
9359    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9360    // failure (new_hash == None, unreachable for a real commitment) yields None.
9361    new_hash.map(|pin_hash| AuditTarget {
9362        pin_hash,
9363        key_count: c.key_count,
9364    })
9365}
9366
9367// ---------------------------------------------------------------------------
9368// Storage-bound audit (v12) — responder commitment rotation
9369// ---------------------------------------------------------------------------
9370
9371/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9372/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9373/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9374async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9375    let bytes = match tokio::fs::read(path).await {
9376        Ok(b) => b,
9377        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9378            debug!(
9379                "Commitment retention: no snapshot at {} (fresh start)",
9380                path.display()
9381            );
9382            return;
9383        }
9384        Err(e) => {
9385            warn!(
9386                "Commitment retention: failed to read {}: {e}",
9387                path.display()
9388            );
9389            return;
9390        }
9391    };
9392    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9393        state.restore(&persisted);
9394        info!(
9395            "Commitment retention: reloaded {} slot(s) from {}",
9396            state.retained_slot_count(),
9397            path.display()
9398        );
9399    } else {
9400        warn!(
9401            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9402            path.display()
9403        );
9404    }
9405}
9406
9407/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9408/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9409/// needless disk writes on idle nodes. On success updates `last` to the bytes
9410/// written; on a serialization/write error the existing on-disk snapshot is left
9411/// intact (never truncated).
9412async fn persist_retention_if_changed(
9413    state: &ResponderCommitmentState,
9414    path: &Path,
9415    last: &mut Option<Vec<u8>>,
9416) {
9417    let Some(bytes) = state.snapshot().to_bytes() else {
9418        warn!("Commitment retention: serialization failed; keeping previous snapshot");
9419        return;
9420    };
9421    if last.as_deref() == Some(bytes.as_slice()) {
9422        return;
9423    }
9424    if write_retention_atomic(path, bytes.clone()).await {
9425        *last = Some(bytes);
9426    }
9427}
9428
9429/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9430/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9431/// success. Only the retention-persist loop writes this path, so a fixed temp
9432/// name is safe.
9433async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9434    let path = path.to_path_buf();
9435    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9436        let tmp = path.with_extension("tmp");
9437        std::fs::write(&tmp, &bytes)?;
9438        std::fs::File::open(&tmp)?.sync_all()?;
9439        std::fs::rename(&tmp, &path)?;
9440        // Fsync the directory so the rename (the durable-commit point) is not
9441        // lost on a crash right after it. An empty parent (relative filename)
9442        // means the current directory.
9443        let dir = path
9444            .parent()
9445            .filter(|p| !p.as_os_str().is_empty())
9446            .unwrap_or_else(|| Path::new("."));
9447        std::fs::File::open(dir)?.sync_all()?;
9448        Ok(())
9449    })
9450    .await;
9451    match res {
9452        Ok(Ok(())) => true,
9453        Ok(Err(e)) => {
9454            warn!("Commitment retention: persist failed: {e}");
9455            false
9456        }
9457        Err(e) => {
9458            warn!("Commitment retention: persist task join failed: {e}");
9459            false
9460        }
9461    }
9462}
9463
9464/// Read the current LMDB key set, build + sign a fresh
9465/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9466/// The prior `current` is demoted to `previous`; the prior `previous` is
9467/// dropped (per `ResponderCommitmentState::rotate`).
9468///
9469/// For content-addressed chunks (Autonomi's chunk store), `address ==
9470/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9471/// re-read each chunk's bytes to compute the leaf hash.
9472///
9473/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9474/// rotate. The auditor side handles "no commitment for this peer" by
9475/// falling back to the legacy plain-digest audit path.
9476async fn rebuild_and_rotate_commitment(
9477    storage: &Arc<LmdbStorage>,
9478    identity: &Arc<NodeIdentity>,
9479    state: &Arc<ResponderCommitmentState>,
9480    p2p: &Arc<P2PNode>,
9481    config: &Arc<ReplicationConfig>,
9482) -> Result<()> {
9483    let stored_keys = storage
9484        .all_keys()
9485        .await
9486        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9487
9488    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9489    // everything currently on disk ("hold"). This is the half of the retention
9490    // contract that lets out-of-range chunks age out: a key that has left our
9491    // close group is excluded from the NEXT commitment, so once its last gossip
9492    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9493    // set, `ResponderCommitmentState::is_held` goes false,
9494    // and the pruner (which until then vetoes its deletion) reclaims it. Without
9495    // this filter the pruner's reprieve would keep re-committing stale keys
9496    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9497    // re-committed and re-gossiped every rotation — a permanent pin).
9498    let storage_empty = stored_keys.is_empty();
9499    let self_id = *p2p.peer_id();
9500    let mut keys = Vec::with_capacity(stored_keys.len());
9501    for k in stored_keys {
9502        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9503            keys.push(k);
9504        }
9505    }
9506
9507    if keys.is_empty() {
9508        if storage_empty {
9509            // Storage is genuinely empty — there is nothing to answer for, so
9510            // drop the previously advertised commitment immediately. Keeping it
9511            // would leave remote auditors pinning a hash we can never satisfy
9512            // again (the bytes are gone).
9513            if state.retained_slot_count() > 0 {
9514                debug!("Commitment rotation: storage empty, clearing retained slots");
9515                state.clear_all();
9516            }
9517            return Ok(());
9518        }
9519        // Bytes are still on disk but no key is currently in range. We must NOT
9520        // clear retention here: a peer may still be pinning a root we gossiped
9521        // moments ago and could demand its bytes in a round-2 challenge, which
9522        // we can still answer (the bytes are present). But we must STOP
9523        // advertising the stale commitment: retire it so `current()` returns
9524        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
9525        // The retired slot then ages out by its gossip-answerability TTL while
9526        // remaining answerable for in-flight pins until then. Once it ages out,
9527        // `is_held` flips false and the pruner reclaims the now-uncommitted,
9528        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
9529        // pointing at the stale root, which the gossip loop would keep
9530        // re-stamping — pinning its keys forever.)
9531        debug!(
9532            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9533             (stays answerable until its gossip TTL lapses, bytes still on disk)"
9534        );
9535        state.retire_current();
9536        return Ok(());
9537    }
9538
9539    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
9540    // to more than the protocol limit; auditor would reject the
9541    // commitment otherwise).
9542    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9543    if keys.len() > cap {
9544        warn!(
9545            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9546             truncating — investigate as this likely means a misconfiguration",
9547            keys.len(),
9548            cap
9549        );
9550    }
9551
9552    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
9553    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
9554    // full chunk re-read per rotation.
9555    //
9556    // Consequence to be precise about: because the leaf is `(key, key)`,
9557    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
9558    // commitment therefore binds "which keys I claim to hold"; it does NOT
9559    // by itself prove byte possession. Byte possession is enforced by the
9560    // round-2 slice audit: a Bao verified slice decoded against the chunk
9561    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
9562    // nonce, so a responder that holds the key list but dropped the bytes
9563    // cannot answer. This is sound ONLY while keys are content addresses;
9564    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
9565    // (`evaluate_subtree_structure`), so a non-content-addressed
9566    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
9567    // earn credit for `key`. If this module is ever reused for
9568    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
9569    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
9570    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9571
9572    // No-op-rotation guard: compute just the Merkle root from `entries`
9573    // and compare against the currently-advertised commitment's root.
9574    // If they match, the key set is unchanged and a new rotation would
9575    // only swap a randomized ML-DSA signature for a fresh one — same
9576    // content, different commitment_hash. That invalidates every
9577    // outstanding `recent_provers` credit on this node across the
9578    // close group with no security benefit, breaking steady-state
9579    // quorum liveness on large nodes that can't re-audit every key
9580    // every rotation interval. Skip the rotation entirely when the
9581    // tree is unchanged.
9582    // Build the tree ONCE here (moving `entries`): it serves both the no-op
9583    // root check below and, if we proceed, the signed commitment via
9584    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
9585    // inside `BuiltCommitment::build`).
9586    let candidate_tree = commitment::MerkleTree::build(entries)
9587        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9588    let candidate_root = candidate_tree.root();
9589    if let Some(current) = state.current() {
9590        if current.commitment().root == candidate_root {
9591            debug!(
9592                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9593                hex::encode(candidate_root)
9594            );
9595            // Even though we skip re-signing (to avoid invalidating holder
9596            // credit), retention must still advance on the wall clock: a
9597            // previously-gossiped commitment that holds a now-out-of-range key
9598            // must be able to age out of the answerability window even when the
9599            // committed key set is frozen here for many rotations. Without this,
9600            // the no-op guard would pin a stale slot — and its key — forever.
9601            state.age_out();
9602            return Ok(());
9603        }
9604    }
9605
9606    let sk_bytes = identity.secret_key_bytes().to_vec();
9607    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9608        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9609    let pk_bytes = identity.public_key().as_bytes().to_vec();
9610    let peer_id_bytes = *p2p.peer_id().as_bytes();
9611
9612    let built = commitment_state::BuiltCommitment::build_from_tree(
9613        candidate_tree,
9614        &peer_id_bytes,
9615        &sk,
9616        &pk_bytes,
9617    )
9618    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9619
9620    let hash = hex::encode(built.hash());
9621    let key_count = built.commitment().key_count;
9622    state.rotate(built);
9623    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9624    Ok(())
9625}
9626
9627#[cfg(test)]
9628#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9629mod tests {
9630    use super::*;
9631    use super::{
9632        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9633        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9634        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9635        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9636        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9637        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9638        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9639        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9640    };
9641    use crate::payment::VerificationContext;
9642    use crate::replication::audit::AuditTickResult;
9643    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9644    use crate::replication::recent_provers::RecentProvers;
9645    use crate::replication::types::{AuditFailureReason, FailureEvidence};
9646    use lru::LruCache;
9647    use saorsa_core::identity::PeerId;
9648    use std::collections::HashMap;
9649    use std::num::NonZeroUsize;
9650    use std::sync::atomic::Ordering;
9651    use std::sync::Arc;
9652    use std::time::Duration;
9653    use std::time::Instant;
9654    use std::time::SystemTime;
9655
9656    #[test]
9657    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9658        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9659            assert_eq!(match_replication_protocol(id), Some((id, false)));
9660            assert_eq!(
9661                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
9662                Some((id, true))
9663            );
9664        }
9665        assert_eq!(
9666            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
9667            None
9668        );
9669        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
9670        assert_eq!(match_replication_protocol(RR_PREFIX), None);
9671    }
9672
9673    #[test]
9674    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
9675        use crate::replication::protocol::{
9676            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
9677            SubtreeSliceChallenge,
9678        };
9679
9680        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
9681            challenge_id: 1,
9682            nonce: [0u8; 32],
9683            challenged_peer_id: [0u8; 32],
9684            expected_commitment_hash: [0u8; 32],
9685            openings: vec![],
9686        });
9687        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
9688            challenge_id: 1,
9689            nonce: [0u8; 32],
9690            challenged_peer_id: [0u8; 32],
9691            keys: vec![[0u8; 32]],
9692        });
9693        let digest_response =
9694            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
9695        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
9696            key: [0u8; 32],
9697            data: vec![],
9698            proof_of_payment: vec![],
9699        });
9700
9701        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
9702        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
9703
9704        for body in [&digest_challenge, &digest_response, &core] {
9705            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
9706            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
9707        }
9708
9709        for body in [&subtree, &digest_challenge, &digest_response, &core] {
9710            assert!(body_matches_protocol(body, response_protocol_for(body)));
9711        }
9712    }
9713
9714    fn test_peer(b: u8) -> PeerId {
9715        let mut bytes = [0u8; 32];
9716        bytes[0] = b;
9717        PeerId::from_bytes(bytes)
9718    }
9719
9720    /// A structurally valid offer for `data`: real content address, a proof of
9721    /// the minimum accepted size, distinguished by `proof_marker` so a test can
9722    /// tell whose proof came back out of the queue.
9723    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
9724        protocol::FreshReplicationOffer {
9725            key: crate::client::compute_address(&data),
9726            data,
9727            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
9728        }
9729    }
9730
9731    fn admit_test_offer(
9732        in_flight: &FreshOfferInFlight,
9733        offer: protocol::FreshReplicationOffer,
9734        source: PeerId,
9735    ) -> FreshOfferAdmission {
9736        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
9737    }
9738
9739    #[test]
9740    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
9741        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9742        let data = vec![0x11u8; 64];
9743
9744        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
9745        let FreshOfferAdmission::Opened(entry) = opened else {
9746            panic!("first offer for a key should open the entry")
9747        };
9748
9749        // A second sender contributes its proof instead of being turned away:
9750        // its bytes are provably the same, so only the proof is worth keeping.
9751        assert!(
9752            matches!(
9753                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
9754                FreshOfferAdmission::Joined
9755            ),
9756            "a duplicate from a new source should queue its proof"
9757        );
9758        // The same peer twice is not extra evidence, just extra work.
9759        assert!(
9760            matches!(
9761                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
9762                FreshOfferAdmission::DuplicateSource
9763            ),
9764            "one source should hold at most one queued proof per key"
9765        );
9766
9767        // An entry that outlived its handler would bar the key forever.
9768        drop(entry);
9769        assert!(
9770            matches!(
9771                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
9772                FreshOfferAdmission::Opened(_)
9773            ),
9774            "a released key should be openable again"
9775        );
9776    }
9777
9778    #[test]
9779    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
9780        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9781
9782        // A node only receives offers for keys close to its own ID, so accepted
9783        // keys share a long prefix. Any prefix-derived shard index would have
9784        // funnelled these two onto one lock and serialized them.
9785        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
9786        assert!(
9787            matches!(
9788                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
9789                FreshOfferAdmission::Opened(_)
9790            ),
9791            "distinct keys should never block each other"
9792        );
9793    }
9794
9795    /// The regression that motivated queueing proofs at all.
9796    ///
9797    /// A sender whose proof does not verify must cost the network its own
9798    /// attempt and nothing more. Refusing every later offer outright made the
9799    /// first arrival the only arrival, so one bad proof lost the record — and
9800    /// the delayed possession check then charged that absence to this node.
9801    #[test]
9802    fn a_failing_proof_hands_the_key_to_the_next_sender() {
9803        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9804        let data = vec![0x5Au8; 128];
9805        let forger = test_peer(0xF0);
9806        let genuine = test_peer(0x0F);
9807
9808        let FreshOfferAdmission::Opened(mut entry) =
9809            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
9810        else {
9811            panic!("the first offer should open the entry");
9812        };
9813        assert!(
9814            matches!(
9815                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
9816                FreshOfferAdmission::Joined
9817            ),
9818            "the genuine sender must not be turned away by the forger"
9819        );
9820
9821        let first = entry
9822            .next_attempt()
9823            .expect("the opener's proof comes first");
9824        assert_eq!(first.source, forger);
9825
9826        // Treat the forger's proof as failed: the next one is still reachable,
9827        // and it is tried against the bytes already held rather than a refetch.
9828        let second = entry
9829            .next_attempt()
9830            .expect("a failed proof must not consume the key");
9831        assert_eq!(second.source, genuine);
9832        assert_eq!(
9833            second.proof_of_payment,
9834            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
9835        );
9836        assert_eq!(
9837            entry.data(),
9838            data.as_slice(),
9839            "every proof is tried against the one copy of the bytes"
9840        );
9841
9842        // Draining the queue releases the key rather than stranding it.
9843        assert!(entry.next_attempt().is_none());
9844        assert!(
9845            matches!(
9846                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
9847                FreshOfferAdmission::Opened(_)
9848            ),
9849            "an exhausted entry should release its key"
9850        );
9851    }
9852
9853    /// The cap has to be a lifetime budget, not a queue depth.
9854    ///
9855    /// The handler pops a proof before verifying it, so gating admission on the
9856    /// *instantaneous* queue length lets a fresh source refill the slot that pop
9857    /// just freed. Each refill is another on-chain payment verification, run
9858    /// sequentially while the entry holds its admission permit and a worker
9859    /// slot, so a stream of distinct sources could keep one key's handler — and
9860    /// one of only four workers — busy indefinitely.
9861    #[test]
9862    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
9863        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9864        let data = vec![0x3Du8; 32];
9865
9866        let FreshOfferAdmission::Opened(mut entry) =
9867            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
9868        else {
9869            panic!("the first offer should open the entry")
9870        };
9871
9872        // Drive pop-then-admit with a fresh source every time, exactly as a
9873        // sybil stream would. The budget must be spent by admissions, not
9874        // returned by pops.
9875        let mut admitted = 1;
9876        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
9877            let _ = entry.next_attempt();
9878            if matches!(
9879                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
9880                FreshOfferAdmission::Joined
9881            ) {
9882                admitted += 1;
9883            }
9884        }
9885
9886        assert!(
9887            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
9888            "a key accepted {admitted} proofs over its lifetime, but the budget is \
9889             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
9890        );
9891    }
9892
9893    #[test]
9894    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
9895        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9896        let data = vec![0x2Cu8; 32];
9897
9898        // The opener occupies the first slot, so the cap is reached after
9899        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
9900        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
9901        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
9902            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
9903            assert!(
9904                matches!(
9905                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
9906                    FreshOfferAdmission::Joined
9907                ),
9908                "sender {i} is within the legitimate close-group fan-out"
9909            );
9910        }
9911
9912        let surplus = test_peer(0xEE);
9913        assert!(
9914            matches!(
9915                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
9916                FreshOfferAdmission::Full
9917            ),
9918            "past the cap a proof is surplus: enough are already queued to place the record"
9919        );
9920    }
9921
9922    #[test]
9923    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
9924        assert!(!verification_request_exceeds_limit(
9925            config::MAX_VERIFICATION_KEYS_PER_CYCLE
9926        ));
9927        assert!(verification_request_exceeds_limit(
9928            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
9929        ));
9930    }
9931
9932    // The heavy round-1 limiter enforces the per-peer rate cooldown
9933    // and single-use round-1 → round-2 sessions.
9934    #[tokio::test]
9935    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
9936        let limiter = SubtreeRound1Limiter::new(
9937            Duration::from_secs(3600),
9938            config::MAX_CONCURRENT_SUBTREE_ROUND1,
9939        );
9940        let peer = test_peer(1);
9941
9942        // First round-1 is admitted; drop the guard so concurrency is free again.
9943        let guard = limiter.admit(&peer).await;
9944        assert!(guard.is_some(), "first round-1 admitted");
9945        drop(guard);
9946        // A second round-1 within the cooldown is dropped even though the heavy
9947        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
9948        assert!(
9949            limiter.admit(&peer).await.is_none(),
9950            "second round-1 within cooldown is rate-dropped"
9951        );
9952        // A different peer has its own cooldown.
9953        assert!(limiter.admit(&test_peer(2)).await.is_some());
9954
9955        // Session: opened by round 1, consumed exactly once by the matching round 2.
9956        let hash = [7u8; 32];
9957        let nonce = [9u8; 32];
9958        limiter.open_session(peer, 42, hash, nonce).await;
9959        // Wrong nonce / commitment does not match.
9960        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
9961        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
9962        // A round 2 with no prior round 1 (wrong challenge_id) misses.
9963        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
9964        // The matching round 2 consumes it — and only once (single-use).
9965        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
9966        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
9967    }
9968
9969    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
9970    // so a party holding several identities refills its allowance by rotating
9971    // between them and can keep the heavy pool busy indefinitely. The work
9972    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
9973    // so a fresh identity is refused exactly like a repeat caller once it is
9974    // spent. That is the difference between bounding concurrency and bounding
9975    // sustained work.
9976    #[tokio::test]
9977    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
9978        // Cooldown disabled so only the work budget can refuse anything.
9979        let limiter =
9980            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
9981        assert!(
9982            limiter.admit(&test_peer(1)).await.is_some(),
9983            "a node starts with budget in hand so it can serve audits at once"
9984        );
9985
9986        // Serve enough proof work to run the balance into debt. Charging exactly
9987        // the burst would leave it at zero, which the next nanosecond of refill
9988        // lifts back above the line — the debt is the point.
9989        limiter
9990            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
9991            .await;
9992
9993        for id in 2..8u8 {
9994            assert!(
9995                limiter.admit(&test_peer(id)).await.is_none(),
9996                "a never-seen peer must still be refused while the budget is spent"
9997            );
9998        }
9999    }
10000
10001    // The budget is a rate, not a quota: it comes back on its own, so an honest
10002    // auditor blocked by a flood is only delayed. Carrying the debt is what
10003    // prices an expensive proof above a cheap one — without it, a proof reading
10004    // a maximal subtree would cost no more of the next caller's wait than a
10005    // one-leaf proof.
10006    #[test]
10007    fn round1_work_budget_carries_debt_and_refills_over_time() {
10008        let now = Instant::now();
10009        let at = |secs: u64| {
10010            now.checked_add(Duration::from_secs(secs))
10011                .unwrap_or_else(Instant::now)
10012        };
10013        let mut budget = Round1WorkBudget {
10014            balance: 0,
10015            last_refill: now,
10016        };
10017        assert!(!budget.has_budget(now), "empty means empty");
10018
10019        // A proof costing four seconds' worth of refill leaves four seconds of
10020        // debt, so the wait scales with what was actually served.
10021        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10022        assert!(
10023            !budget.has_budget(at(3)),
10024            "still in debt three seconds after an over-large proof"
10025        );
10026        assert!(
10027            budget.has_budget(at(5)),
10028            "the debt is worked off at the refill rate"
10029        );
10030
10031        // Idle time does not bank unbounded credit for a later flood.
10032        budget.refill(at(24 * 60 * 60));
10033        assert_eq!(
10034            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10035            "refill is capped at the burst size"
10036        );
10037    }
10038
10039    // The heavy round-1 pool size is the tightest bound the responder applies and
10040    // the one least backed by fleet measurement, so it is read from config rather
10041    // than baked into the binary: a fleet that lands on the wrong number retunes
10042    // instead of waiting for a release. These pin that the configured value is
10043    // what actually gates admission, and that a 0 degrades to slow, not to off —
10044    // a wedged-shut responder would read on every auditor as a graced timeout,
10045    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10046    #[tokio::test]
10047    async fn round1_pool_size_comes_from_config() {
10048        // Cooldown disabled so only concurrency can refuse anything.
10049        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10050        let held = limiter.admit(&test_peer(1)).await;
10051        assert!(held.is_some(), "the single configured slot is admitted");
10052        assert!(
10053            limiter.admit(&test_peer(2)).await.is_none(),
10054            "a second concurrent round 1 is refused at a configured pool of 1, \
10055             proving admission follows config rather than the compiled-in default"
10056        );
10057        drop(held);
10058        assert!(
10059            limiter.admit(&test_peer(2)).await.is_some(),
10060            "the slot is reusable once the first proof completes"
10061        );
10062    }
10063
10064    #[tokio::test]
10065    async fn round1_pool_size_of_zero_is_clamped_to_one() {
10066        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10067        assert!(
10068            limiter.admit(&test_peer(1)).await.is_some(),
10069            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10070        );
10071    }
10072
10073    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10074        let mut k = [0u8; 32];
10075        k[0] = b;
10076        k
10077    }
10078
10079    #[test]
10080    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10081        let source = test_peer(0x91);
10082        let corroborator = test_peer(0x92);
10083        let mut evidence = types::KeyVerificationEvidence {
10084            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10085            paid_list: HashMap::new(),
10086        };
10087        let failed = KeyVerificationOutcome::QuorumFailed;
10088
10089        assert_eq!(
10090            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10091            Some(source)
10092        );
10093        assert_eq!(
10094            punishable_singleton_replica_hint_source(
10095                &HashSet::from([source, corroborator]),
10096                &failed,
10097                &evidence,
10098            ),
10099            None,
10100            "corroborated hints must not use the sole-source penalty lane"
10101        );
10102        assert_eq!(
10103            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10104            None,
10105            "paid-list advertisements do not claim possession, so they leave the \
10106             replica-hint source set empty and cannot be penalized"
10107        );
10108
10109        evidence
10110            .presence
10111            .insert(source, PresenceEvidence::Unresolved);
10112        assert_eq!(
10113            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10114            Some(source),
10115            "definitive close-group rejection is punishable without direct contradiction"
10116        );
10117        assert_eq!(
10118            punishable_singleton_replica_hint_source(
10119                &HashSet::from([source]),
10120                &KeyVerificationOutcome::QuorumInconclusive,
10121                &evidence,
10122            ),
10123            None,
10124            "timeouts and inconclusive evidence are neutral"
10125        );
10126
10127        evidence.presence.insert(source, PresenceEvidence::Absent);
10128        assert_eq!(
10129            punishable_singleton_replica_hint_source(
10130                &HashSet::from([source]),
10131                &KeyVerificationOutcome::QuorumVerified {
10132                    sources: vec![corroborator],
10133                },
10134                &evidence,
10135            ),
10136            Some(source),
10137            "an explicit denial is punishable regardless of the overall outcome"
10138        );
10139    }
10140
10141    /// Build a round-2 slice challenge matching an open session. `openings` is
10142    /// empty: these tests exercise admission and session handling only, which
10143    /// run before any block is opened.
10144    fn slice_challenge(
10145        challenge_id: u64,
10146        commitment_hash: [u8; 32],
10147        nonce: [u8; 32],
10148    ) -> protocol::SubtreeSliceChallenge {
10149        protocol::SubtreeSliceChallenge {
10150            challenge_id,
10151            nonce,
10152            challenged_peer_id: [0u8; 32],
10153            expected_commitment_hash: commitment_hash,
10154            openings: Vec::new(),
10155        }
10156    }
10157
10158    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10159    // responder caps MUST NOT burn the single-use round-1 session.
10160    //
10161    // The handler used to consume the session first and admit second, so a
10162    // transient local capacity drop permanently destroyed that audit exchange —
10163    // every retry hit the `no live round-1 session` path and got `Transient`,
10164    // even after load cleared. Turning momentary local load into a deterministic
10165    // round-2 miss costs the responder its whole-slice credit for that round.
10166    #[tokio::test]
10167    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10168        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10169        let inflight = Arc::new(RwLock::new(HashMap::new()));
10170        let round1 =
10171            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10172        let peer = test_peer(0xB1);
10173        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10174        let challenge = slice_challenge(id, hash, nonce);
10175
10176        round1.open_session(peer, id, hash, nonce).await;
10177
10178        // Saturate this peer's share so the next admission must be refused.
10179        let mut hold = Vec::new();
10180        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10181            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10182                .await
10183            {
10184                Ok(guard) => hold.push(guard),
10185                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10186            }
10187        }
10188
10189        let refused =
10190            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10191        assert!(
10192            matches!(refused, SliceAdmission::Capacity(_)),
10193            "a saturated peer share must refuse on capacity, not on session"
10194        );
10195
10196        // Load clears. The session must have survived the refusal.
10197        drop(hold);
10198        let retried =
10199            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10200        assert!(
10201            matches!(retried, SliceAdmission::Admitted(_)),
10202            "the round-1 session must survive a capacity refusal so the retry succeeds"
10203        );
10204
10205        // Still single-use: the successful admission consumed it exactly once.
10206        drop(retried);
10207        let replayed =
10208            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10209        assert!(
10210            matches!(replayed, SliceAdmission::NoSession),
10211            "a consumed session must not be replayable"
10212        );
10213    }
10214
10215    // The permit taken for the session probe is released when the probe misses,
10216    // so an unsessioned flood cannot pin the responder pool shut.
10217    #[tokio::test]
10218    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10219        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10220        let inflight = Arc::new(RwLock::new(HashMap::new()));
10221        let round1 =
10222            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10223        let peer = test_peer(0xB2);
10224        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10225
10226        // Far more unsessioned challenges than the per-peer cap would allow if
10227        // the slot leaked on the miss path.
10228        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10229            let outcome =
10230                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10231            assert!(
10232                matches!(outcome, SliceAdmission::NoSession),
10233                "no session was ever opened, so every attempt must miss"
10234            );
10235        }
10236
10237        assert_eq!(
10238            semaphore.available_permits(),
10239            MAX_CONCURRENT_AUDIT_RESPONSES,
10240            "every global permit must be returned"
10241        );
10242        assert!(
10243            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10244            "no per-peer slot may be left occupied"
10245        );
10246    }
10247
10248    #[test]
10249    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10250        assert!(!audit_failure_revokes_holder_credit(
10251            &AuditFailureReason::Timeout
10252        ));
10253        assert!(audit_failure_revokes_holder_credit(
10254            &AuditFailureReason::DigestMismatch
10255        ));
10256    }
10257
10258    #[tokio::test]
10259    async fn audit_responder_admission_reports_per_peer_cap_full() {
10260        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10261        let inflight = Arc::new(RwLock::new(HashMap::new()));
10262        let peer = test_peer(0xA1);
10263
10264        let mut guards = Vec::new();
10265        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10266            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10267                .await
10268            {
10269                Ok(guard) => guards.push(guard),
10270                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10271            }
10272        }
10273
10274        let Err(err) =
10275            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10276        else {
10277            panic!("admission should fail once per-peer cap is full");
10278        };
10279        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10280        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10281        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10282        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10283
10284        drop(guards);
10285    }
10286
10287    #[tokio::test]
10288    async fn audit_responder_admission_reports_global_pool_full() {
10289        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10290        let inflight = Arc::new(RwLock::new(HashMap::new()));
10291        let peer = test_peer(0xA2);
10292
10293        let mut held_global_permits = Vec::new();
10294        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10295            held_global_permits.push(
10296                Arc::clone(&semaphore)
10297                    .try_acquire_owned()
10298                    .expect("test should be able to exhaust the global pool"),
10299            );
10300        }
10301
10302        let Err(err) =
10303            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10304        else {
10305            panic!("admission should fail once global pool is full");
10306        };
10307        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10308        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10309        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10310        assert_eq!(err.peer_inflight, 0);
10311        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10312
10313        drop(held_global_permits);
10314    }
10315
10316    #[tokio::test]
10317    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10318        let semaphore = Arc::new(Semaphore::new(1));
10319        let inflight = Arc::new(RwLock::new(HashMap::new()));
10320        let peer = test_peer(0xA3);
10321
10322        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10323            .await
10324            .expect("first responder should be admitted");
10325        assert_eq!(semaphore.available_permits(), 0);
10326        assert_eq!(inflight.read().await.get(&peer), Some(&1));
10327
10328        drop(guard);
10329        assert_eq!(semaphore.available_permits(), 1);
10330        assert!(!inflight.read().await.contains_key(&peer));
10331    }
10332
10333    #[tokio::test]
10334    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10335        let semaphore = Arc::new(Semaphore::new(1));
10336        let inflight = Arc::new(RwLock::new(HashMap::new()));
10337        let peer = test_peer(0xA4);
10338        let held_map = inflight.write().await;
10339
10340        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10341        assert!(
10342            tokio::time::timeout(Duration::from_millis(10), waiting)
10343                .await
10344                .is_err(),
10345            "admission should still be waiting for the peer map"
10346        );
10347
10348        drop(held_map);
10349        assert_eq!(semaphore.available_permits(), 1);
10350        assert!(!inflight.read().await.contains_key(&peer));
10351    }
10352
10353    #[test]
10354    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10355        let timeout = Duration::from_secs(1);
10356        let old_received_at = Instant::now()
10357            .checked_sub(timeout)
10358            .unwrap_or_else(Instant::now);
10359
10360        assert!(request_is_stale(old_received_at, timeout));
10361        assert!(!request_is_stale(Instant::now(), timeout));
10362    }
10363
10364    #[tokio::test]
10365    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10366        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10367        let inflight = Arc::new(RwLock::new(HashMap::new()));
10368        let first_peer = test_peer(0xB3);
10369        let second_peer = test_peer(0xB4);
10370
10371        let first_guard = admit_bounded_responder(
10372            &semaphore,
10373            &inflight,
10374            &first_peer,
10375            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10376            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10377        )
10378        .await
10379        .expect("first sync from a peer should be admitted");
10380        let duplicate = admit_bounded_responder(
10381            &semaphore,
10382            &inflight,
10383            &first_peer,
10384            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10385            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10386        )
10387        .await;
10388        let other_peer = admit_bounded_responder(
10389            &semaphore,
10390            &inflight,
10391            &second_peer,
10392            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10393            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10394        )
10395        .await;
10396
10397        assert!(matches!(
10398            duplicate,
10399            Err(ResponderAdmissionFailure {
10400                reason: ResponderRejectReason::PerPeerCapFull,
10401                ..
10402            })
10403        ));
10404        assert!(other_peer.is_ok());
10405        drop(first_guard);
10406        drop(other_peer);
10407    }
10408
10409    /// One flooding peer must not be able to hold every fresh-offer slot.
10410    ///
10411    /// This is the eviction primitive the per-peer share closes: with only a
10412    /// global bound, a single source occupies the pool, every honest offer in
10413    /// that window is refused, and because a refusal reads as absence to the
10414    /// sender's delayed possession check those refusals land as
10415    /// audit-severity penalties on *this* node.
10416    #[tokio::test]
10417    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10418        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10419        let inflight = Arc::new(RwLock::new(HashMap::new()));
10420        let flooder = test_peer(0xC1);
10421        let honest = test_peer(0xC2);
10422
10423        let mut held = Vec::new();
10424        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10425            held.push(
10426                admit_bounded_responder(
10427                    &semaphore,
10428                    &inflight,
10429                    &flooder,
10430                    FRESH_OFFER_MAX_OUTSTANDING,
10431                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10432                )
10433                .await
10434                .expect("offers within the per-peer share are admitted"),
10435            );
10436        }
10437
10438        let flooder_excess = admit_bounded_responder(
10439            &semaphore,
10440            &inflight,
10441            &flooder,
10442            FRESH_OFFER_MAX_OUTSTANDING,
10443            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10444        )
10445        .await;
10446        assert!(
10447            matches!(
10448                flooder_excess,
10449                Err(ResponderAdmissionFailure {
10450                    reason: ResponderRejectReason::PerPeerCapFull,
10451                    ..
10452                })
10453            ),
10454            "one source must not exceed its fresh-offer share"
10455        );
10456
10457        let honest_offer = admit_bounded_responder(
10458            &semaphore,
10459            &inflight,
10460            &honest,
10461            FRESH_OFFER_MAX_OUTSTANDING,
10462            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10463        )
10464        .await;
10465        assert!(
10466            honest_offer.is_ok(),
10467            "an honest sender must still be admitted while another peer floods"
10468        );
10469
10470        assert!(
10471            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10472                < FRESH_OFFER_MAX_OUTSTANDING,
10473            "the per-peer share must leave room for other sources"
10474        );
10475
10476        drop(held);
10477        drop(honest_offer);
10478    }
10479
10480    /// Paid notifies get the same per-source treatment as every other class.
10481    #[tokio::test]
10482    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10483        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10484        let inflight = Arc::new(RwLock::new(HashMap::new()));
10485        let flooder = test_peer(0xC3);
10486        let honest = test_peer(0xC4);
10487
10488        let mut held = Vec::new();
10489        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10490            held.push(
10491                admit_bounded_responder(
10492                    &semaphore,
10493                    &inflight,
10494                    &flooder,
10495                    PAID_NOTIFY_MAX_OUTSTANDING,
10496                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10497                )
10498                .await
10499                .expect("notifies within the per-peer share are admitted"),
10500            );
10501        }
10502
10503        assert!(
10504            matches!(
10505                admit_bounded_responder(
10506                    &semaphore,
10507                    &inflight,
10508                    &flooder,
10509                    PAID_NOTIFY_MAX_OUTSTANDING,
10510                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10511                )
10512                .await,
10513                Err(ResponderAdmissionFailure {
10514                    reason: ResponderRejectReason::PerPeerCapFull,
10515                    ..
10516                })
10517            ),
10518            "one source must not exceed its paid-notify share"
10519        );
10520        assert!(
10521            admit_bounded_responder(
10522                &semaphore,
10523                &inflight,
10524                &honest,
10525                PAID_NOTIFY_MAX_OUTSTANDING,
10526                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10527            )
10528            .await
10529            .is_ok(),
10530            "an honest sender must still be admitted while another peer floods"
10531        );
10532
10533        drop(held);
10534    }
10535
10536    /// The fresh-offer per-source bound must guarantee headroom for a peer
10537    /// holding nothing, without throttling a single legitimate fan-out.
10538    ///
10539    /// Sized as a quota rather than a reserve, this bound refused offers during
10540    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
10541    /// refusal is charged to THIS node at audit severity because the sender
10542    /// never reads it.
10543    #[test]
10544    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10545        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10546
10547        assert_eq!(
10548            FRESH_OFFER_MAX_OUTSTANDING - share,
10549            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10550            "a source holding none must always find a free slot"
10551        );
10552        assert!(
10553            share < FRESH_OFFER_MAX_OUTSTANDING,
10554            "one peer must not be able to take the whole pool"
10555        );
10556        // The failure this pins: a share sized like the request/response
10557        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
10558        // one-way bulk traffic.
10559        assert!(
10560            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10561            "fresh offers are one-way bulk, not request/response — their share \
10562             must not be sized like the request classes'"
10563        );
10564    }
10565
10566    /// A malformed offer must be refused before it can occupy an admission
10567    /// slot, so junk cannot hold capacity for the length of a verification.
10568    #[test]
10569    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10570        let key = test_key(0xC5);
10571
10572        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10573
10574        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10575            .expect("an offer with no proof must be refused");
10576        assert!(
10577            rejection.penalise,
10578            "an honest sender always attaches a proof"
10579        );
10580
10581        // A proof is retained per queued sender, so its size has to be bounded
10582        // here rather than at the verifier, which only sees it on a worker.
10583        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10584        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10585            .expect("an undersized proof must be refused");
10586        assert!(
10587            rejection.penalise,
10588            "no honest sender constructs an undersized proof"
10589        );
10590        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10591        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10592            .expect("an oversized proof must be refused");
10593        assert!(
10594            rejection.penalise,
10595            "no honest sender constructs an oversized proof"
10596        );
10597
10598        let rejection = fresh_offer_structural_rejection(
10599            &key,
10600            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10601            &valid_proof,
10602        )
10603        .expect("an oversized offer must be refused");
10604        assert!(
10605            rejection.penalise,
10606            "no honest sender constructs an oversized offer"
10607        );
10608
10609        let data = vec![0u8; 1];
10610        assert!(
10611            fresh_offer_structural_rejection(
10612                &crate::client::compute_address(&data),
10613                &data,
10614                &valid_proof
10615            )
10616            .is_none(),
10617            "a well-formed offer must reach admission"
10618        );
10619    }
10620
10621    /// Knowing a key must not be enough to enter its entry.
10622    ///
10623    /// Opening an entry on an unverified key/bytes association would let a peer
10624    /// that has only *learned* the key — every recipient of its `PaidNotify`,
10625    /// not just the close group that gets the chunk — seize it with junk.
10626    /// Joining one would be worse: the handler tries each queued proof against
10627    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
10628    /// on bytes it never offered.
10629    #[test]
10630    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10631        let genuine_data = vec![0x5Au8; 128];
10632        let key = crate::client::compute_address(&genuine_data);
10633        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10634
10635        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10636            .expect("bytes that do not hash to the advertised key must be refused");
10637        assert!(
10638            rejection.penalise,
10639            "no honest sender offers bytes that do not hash to the advertised key"
10640        );
10641
10642        // Dispatch reaches the entry only past that rejection, so the forged
10643        // offer never touched the key and the genuine one still opens it.
10644        assert!(
10645            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10646            "the offer that actually carries the key's bytes must reach the entry"
10647        );
10648
10649        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10650        assert!(
10651            matches!(
10652                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10653                FreshOfferAdmission::Opened(_)
10654            ),
10655            "an offer refused on payload shape must leave the key openable"
10656        );
10657    }
10658
10659    #[tokio::test]
10660    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
10661        let peer = test_peer(0xA5);
10662        let key = test_key(0xA5);
10663        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10664        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10665        let is_bootstrapping = Arc::new(RwLock::new(true));
10666        let bootstrap_complete_notify = Arc::new(Notify::new());
10667
10668        let now = Instant::now();
10669        queues.write().await.add_pending_verify(
10670            key,
10671            VerificationEntry {
10672                state: VerificationState::PendingVerify,
10673                verified_sources: Vec::new(),
10674                tried_sources: HashSet::new(),
10675                created_at: now,
10676                next_verify_at: now,
10677                hint_sources: HashSet::from([peer]),
10678                replica_hint_sources: HashSet::from([peer]),
10679            },
10680        );
10681        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
10682        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10683        {
10684            let q = queues.read().await;
10685            assert!(
10686                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
10687                "capacity rejection should initially block bootstrap drain"
10688            );
10689        }
10690
10691        update_bootstrap_after_peer_removed(
10692            &peer,
10693            &bootstrap_state,
10694            &queues,
10695            &is_bootstrapping,
10696            &bootstrap_complete_notify,
10697        )
10698        .await;
10699
10700        let state = bootstrap_state.read().await;
10701        assert!(state.capacity_rejected_sources.is_empty());
10702        assert!(state.pending_keys.is_empty());
10703        assert!(state.is_drained());
10704        drop(state);
10705        assert!(!*is_bootstrapping.read().await);
10706    }
10707
10708    /// A fairness displacement forfeits the key but must not stamp its former
10709    /// owner: the owner did nothing wrong, and stamping it lets a flooding
10710    /// source block bootstrap drain through an unrelated honest peer.
10711    #[tokio::test]
10712    async fn fairness_displacement_does_not_stamp_its_victim() {
10713        let displaced_owner = test_peer(0xB1);
10714        let incoming_source = test_peer(0xB2);
10715        let displaced_key = test_key(0xB1);
10716        let admitted_key = test_key(0xB2);
10717        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10718        {
10719            let mut state = bootstrap_state.write().await;
10720            state.pending_keys.insert(displaced_key);
10721            state
10722                .capacity_rejected_sources
10723                .insert(incoming_source, Instant::now());
10724        }
10725        let outcomes = [(
10726            incoming_source,
10727            AdmissionOutcome {
10728                discovered: HashSet::from([admitted_key]),
10729                capacity_rejected_count: 0,
10730                displaced: vec![CapacityDisplacement {
10731                    key: displaced_key,
10732                    owner: displaced_owner,
10733                }],
10734            },
10735        )];
10736
10737        publish_bootstrap_admission_outcomes(
10738            &bootstrap_state,
10739            &outcomes,
10740            &HashSet::from([admitted_key]),
10741        )
10742        .await;
10743
10744        let state = bootstrap_state.read().await;
10745        assert!(!state.pending_keys.contains(&displaced_key));
10746        assert!(state.pending_keys.contains(&admitted_key));
10747        assert!(
10748            !state
10749                .capacity_rejected_sources
10750                .contains_key(&displaced_owner),
10751            "the displaced owner must not be charged for our own fairness reclaim"
10752        );
10753        assert!(!state
10754            .capacity_rejected_sources
10755            .contains_key(&incoming_source));
10756    }
10757
10758    /// A source that keeps overflowing us must not keep its own record fresh.
10759    ///
10760    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
10761    /// rejection the debt could never age out, so `check_bootstrap_drained`
10762    /// stayed false forever and auditing never started (Invariant 19).
10763    #[tokio::test]
10764    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
10765        const REJECTION_ROUNDS: usize = 5;
10766
10767        let source = test_peer(0xB3);
10768        let key = test_key(0xB3);
10769        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10770
10771        let first_seen = {
10772            let outcomes = [(
10773                source,
10774                AdmissionOutcome {
10775                    discovered: HashSet::new(),
10776                    capacity_rejected_count: 1,
10777                    displaced: Vec::new(),
10778                },
10779            )];
10780            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
10781                .await;
10782            bootstrap_state
10783                .read()
10784                .await
10785                .capacity_rejected_sources
10786                .get(&source)
10787                .copied()
10788                .expect("first rejection recorded")
10789        };
10790
10791        for _ in 0..REJECTION_ROUNDS {
10792            let outcomes = [(
10793                source,
10794                AdmissionOutcome {
10795                    discovered: HashSet::from([key]),
10796                    capacity_rejected_count: 1,
10797                    displaced: Vec::new(),
10798                },
10799            )];
10800            publish_bootstrap_admission_outcomes(
10801                &bootstrap_state,
10802                &outcomes,
10803                &HashSet::from([key]),
10804            )
10805            .await;
10806        }
10807
10808        let recorded = bootstrap_state
10809            .read()
10810            .await
10811            .capacity_rejected_sources
10812            .get(&source)
10813            .copied()
10814            .expect("debt still outstanding");
10815        assert_eq!(
10816            recorded, first_seen,
10817            "repeat rejections must not restart the expiry clock"
10818        );
10819    }
10820
10821    /// The verification-worker tick's self-heal path: a capacity rejection
10822    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
10823    /// blocks drain until the TTL expires it, at which point the same tick
10824    /// completes bootstrap without any external event.
10825    #[tokio::test]
10826    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
10827        let peer = test_peer(0xA6);
10828        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10829        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10830        let is_bootstrapping = Arc::new(RwLock::new(true));
10831        let bootstrap_complete_notify = Arc::new(Notify::new());
10832
10833        // PeerRemoved was fully processed before the rejection landed, so no
10834        // future event will ever clear this entry.
10835        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10836
10837        // Within the TTL the tick keeps waiting for re-delivery.
10838        expire_and_recheck_bootstrap_drain(
10839            &bootstrap_state,
10840            &queues,
10841            &is_bootstrapping,
10842            &bootstrap_complete_notify,
10843            ReplicationConfig::default().capacity_rejected_max_age(),
10844        )
10845        .await;
10846        assert!(!bootstrap_state.read().await.is_drained());
10847        assert!(*is_bootstrapping.read().await);
10848
10849        // Past the TTL the tick expires the orphan and completes bootstrap.
10850        expire_and_recheck_bootstrap_drain(
10851            &bootstrap_state,
10852            &queues,
10853            &is_bootstrapping,
10854            &bootstrap_complete_notify,
10855            Duration::ZERO,
10856        )
10857        .await;
10858        assert!(bootstrap_state.read().await.is_drained());
10859        assert!(!*is_bootstrapping.read().await);
10860    }
10861
10862    #[test]
10863    fn first_audit_terminal_outcomes_are_stable() {
10864        let peer = test_peer(1);
10865        let passed = AuditTickResult::Passed {
10866            challenged_peer: peer,
10867            keys_checked: 1,
10868        };
10869        let timed_out = AuditTickResult::Failed {
10870            evidence: FailureEvidence::AuditFailure {
10871                challenge_id: 1,
10872                challenged_peer: peer,
10873                confirmed_failed_keys: vec![test_key(1)],
10874                summary: crate::replication::types::AuditFailureSummary::default(),
10875                reason: AuditFailureReason::Timeout,
10876            },
10877            no_response_class: Some("timeout"),
10878        };
10879
10880        assert_eq!(
10881            first_audit_terminal_outcome(&passed),
10882            FirstAuditTerminalOutcome::Passed
10883        );
10884        assert_eq!(
10885            first_audit_terminal_outcome(&timed_out),
10886            FirstAuditTerminalOutcome::Timeout
10887        );
10888        assert_eq!(
10889            first_audit_terminal_outcome(&AuditTickResult::Idle),
10890            FirstAuditTerminalOutcome::Idle
10891        );
10892        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
10893        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
10894        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
10895        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
10896        assert_eq!(
10897            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
10898            "insufficient_keys"
10899        );
10900        assert_eq!(
10901            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
10902            "bootstrap_claim"
10903        );
10904    }
10905
10906    #[test]
10907    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
10908        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
10909        let mut rng = StdRng::seed_from_u64(7);
10910        let peer = test_peer(1);
10911        let base = MonetizedPinEvent {
10912            peer,
10913            pin: [1; 32],
10914            key_count: 100,
10915            quote_ts: SystemTime::now(),
10916        };
10917
10918        // First insert into an empty slot: Queued.
10919        assert_eq!(
10920            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
10921            FirstAuditQueueOutcome::Queued
10922        );
10923
10924        // A strictly LOWER-count same-peer nomination must NOT displace it.
10925        let lower = MonetizedPinEvent {
10926            pin: [2; 32],
10927            key_count: 50,
10928            ..base
10929        };
10930        assert_eq!(
10931            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
10932            FirstAuditQueueOutcome::SuppressedLower
10933        );
10934        assert_eq!(
10935            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10936            Some(([1; 32], 100)),
10937            "the higher-count pin is retained"
10938        );
10939
10940        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
10941        let higher = MonetizedPinEvent {
10942            pin: [3; 32],
10943            key_count: 400,
10944            ..base
10945        };
10946        assert_eq!(
10947            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
10948            FirstAuditQueueOutcome::Coalesced
10949        );
10950        assert_eq!(
10951            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10952            Some(([3; 32], 400))
10953        );
10954
10955        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
10956        let equal_newer = MonetizedPinEvent {
10957            pin: [4; 32],
10958            key_count: 400,
10959            ..base
10960        };
10961        assert_eq!(
10962            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
10963            FirstAuditQueueOutcome::Coalesced
10964        );
10965        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10966        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
10967        let equal_older = MonetizedPinEvent {
10968            pin: [5; 32],
10969            key_count: 400,
10970            ..base
10971        };
10972        assert_eq!(
10973            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
10974            FirstAuditQueueOutcome::RetainedOnTie
10975        );
10976        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10977
10978        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
10979        let other_peer = MonetizedPinEvent {
10980            peer: test_peer(2),
10981            pin: [6; 32],
10982            key_count: 100,
10983            ..base
10984        };
10985        assert_eq!(
10986            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
10987            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
10988        );
10989        assert_eq!(pending.len(), 1);
10990        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
10991    }
10992
10993    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
10994
10995    #[test]
10996    fn first_audit_limiter_enforces_burst_then_refills() {
10997        let base = Instant::now();
10998        let mut limiter = FirstAuditLimiter::new(base);
10999        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11000
11001        // The full burst is admitted back-to-back (distinct peers).
11002        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11003            let peer = test_peer(u8::try_from(i).expect("small burst"));
11004            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11005            limiter.commit_launch(peer, 10, base);
11006        }
11007        // Bucket empty: the next distinct peer is deferred, never dropped.
11008        let extra = test_peer(0xEE);
11009        assert_eq!(
11010            limiter.assess(&extra, 10, base, 0),
11011            LimiterVerdict::RateDeferred
11012        );
11013
11014        // One full interval later exactly one token is available again.
11015        let later = base + interval;
11016        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11017        limiter.commit_launch(extra, 10, later);
11018        let extra2 = test_peer(0xEF);
11019        assert_eq!(
11020            limiter.assess(&extra2, 10, later, 0),
11021            LimiterVerdict::RateDeferred
11022        );
11023    }
11024
11025    #[test]
11026    fn first_audit_limiter_refill_keeps_fractional_remainder() {
11027        let base = Instant::now();
11028        let mut limiter = FirstAuditLimiter::new(base);
11029        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11030        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11031            let peer = test_peer(u8::try_from(i).expect("small burst"));
11032            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11033            limiter.commit_launch(peer, 1, base);
11034        }
11035        // 1.5 intervals later one token is earned and the half interval is
11036        // NOT lost to drift...
11037        let at_1_5 = base + interval + interval / 2;
11038        let p = test_peer(0xAA);
11039        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11040        limiter.commit_launch(p, 1, at_1_5);
11041        // ...so the next token arrives at 2.0 intervals, not 2.5.
11042        let at_2_0 = base + interval * 2;
11043        let q = test_peer(0xAB);
11044        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11045    }
11046
11047    #[test]
11048    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11049        let base = Instant::now();
11050        let mut limiter = FirstAuditLimiter::new(base);
11051        let peer = test_peer(1);
11052        assert_eq!(
11053            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11054            LimiterVerdict::RateDeferred
11055        );
11056        // A freed slot admits without any clock movement.
11057        assert_eq!(
11058            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11059            LimiterVerdict::Admit
11060        );
11061    }
11062
11063    #[test]
11064    fn first_audit_limiter_assess_consumes_nothing() {
11065        let base = Instant::now();
11066        let mut limiter = FirstAuditLimiter::new(base);
11067        let peer = test_peer(3);
11068        // Repeated assessment must not burn budget or stamp the window: only
11069        // `commit_launch` consumes (the cooldown gate between assess and
11070        // commit can defer, and that deferral must be free).
11071        for _ in 0..10 {
11072            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11073        }
11074        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11075            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11076            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11077            limiter.commit_launch(p, 5, base);
11078        }
11079    }
11080
11081    #[test]
11082    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11083        let base = Instant::now();
11084        let mut limiter = FirstAuditLimiter::new(base);
11085        let peer = test_peer(7);
11086        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11087        limiter.commit_launch(peer, 100, base);
11088
11089        // A rotated pin with a similar count inside the window is dropped...
11090        let soon = base + Duration::from_secs(60);
11091        assert_eq!(
11092            limiter.assess(&peer, 100, soon, 0),
11093            LimiterVerdict::WindowDeduped
11094        );
11095        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11096        assert_eq!(
11097            limiter.assess(&peer, 150, soon, 0),
11098            LimiterVerdict::WindowDeduped
11099        );
11100        // ...but a >1.5x committed-count jump re-nominates immediately (an
11101        // inflated sidecar-only pin is invisible to the gossip lottery, so
11102        // the window must not shield it).
11103        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11104
11105        // Window expiry re-admits an unchanged count.
11106        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11107        assert_eq!(
11108            limiter.assess(&peer, 100, expired, 0),
11109            LimiterVerdict::Admit
11110        );
11111    }
11112
11113    #[test]
11114    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11115        // A window-deduped nomination must be DROPPED, not kept pending as
11116        // rate-deferred, even when the bucket is also empty: re-queuing a
11117        // suppressed rotation would hold a pending slot for two hours.
11118        let base = Instant::now();
11119        let mut limiter = FirstAuditLimiter::new(base);
11120        let peer = test_peer(9);
11121        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11122        limiter.commit_launch(peer, 10, base);
11123        let other = test_peer(10);
11124        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11125        limiter.commit_launch(other, 10, base);
11126        assert_eq!(
11127            limiter.assess(&peer, 10, base, 0),
11128            LimiterVerdict::WindowDeduped
11129        );
11130    }
11131
11132    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11133    /// is answerable now but would age out of the answerability window during
11134    /// the launch jitter, so scheduling state is only ever committed for a pin
11135    /// that can still be challenged when it actually sends.
11136    #[test]
11137    fn first_audit_horizon_prefilter_boundary() {
11138        let now = SystemTime::now();
11139        // C = the too-old cutoff; H = the worst-case send horizon.
11140        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11141        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11142        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11143        let boundary = now
11144            .checked_add(h)
11145            .and_then(|t| t.checked_sub(c))
11146            .expect("boundary time");
11147
11148        // In window at `now` (age = C - H < C)...
11149        assert!(quote_within_audit_window(boundary, now));
11150        // ...but the horizon prefilter rejects it (age == C at now + H).
11151        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11152
11153        // A hair newer stays answerable through the horizon; a hair older does
11154        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11155        // a nanosecond step would round to the same instant there.
11156        let newer = boundary
11157            .checked_add(Duration::from_micros(1))
11158            .expect("newer");
11159        let older = boundary
11160            .checked_sub(Duration::from_micros(1))
11161            .expect("older");
11162        assert!(quote_answerable_through_nominal_jitter(newer, now));
11163        assert!(!quote_answerable_through_nominal_jitter(older, now));
11164
11165        // A quote too far in the FUTURE is rejected at `now`, independent of the
11166        // horizon.
11167        let future = now
11168            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11169            .and_then(|t| t.checked_add(Duration::from_secs(60)))
11170            .expect("future");
11171        assert!(!quote_answerable_through_nominal_jitter(future, now));
11172    }
11173
11174    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11175    /// answerability check fails at promotion is fully state-neutral — it stamps
11176    /// no `first_audited`, no per-peer window, refunds its token, releases its
11177    /// in-flight slot, does not flip the lane, and does not count a launch — and
11178    /// a same-peer, same-count successor enqueued DURING the reservation is
11179    /// retained and becomes the next reservation after the cancel. This is the
11180    /// exact hole the reviewer flagged: suppression must never outlive a launch
11181    /// that did not send.
11182    /// A pending pin that has aged past the answerability horizon must not
11183    /// suppress a live lower-count nomination for the same peer: under token
11184    /// starvation no reserve scan ever collects the dead entry, so without the
11185    /// enqueue-time check the peer would stay unauditable through this path
11186    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11187    #[test]
11188    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11189        let obs = Arc::new(FirstAuditObservability::default());
11190        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11191        let peer = test_peer(1);
11192
11193        let dead_quote = SystemTime::now()
11194            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11195            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11196            .expect("past wall time");
11197        let stale_high = MonetizedPinEvent {
11198            peer,
11199            pin: [1; 32],
11200            key_count: 400,
11201            quote_ts: dead_quote,
11202        };
11203        scheduler.enqueue(stale_high, &obs);
11204        assert_eq!(scheduler.pending_len(), 1);
11205
11206        // A fresh, lower-count nomination (a post-prune commitment).
11207        let fresh_lower = MonetizedPinEvent {
11208            peer,
11209            pin: [2; 32],
11210            key_count: 100,
11211            quote_ts: SystemTime::now(),
11212        };
11213        scheduler.enqueue(fresh_lower, &obs);
11214
11215        assert_eq!(scheduler.pending_len(), 1);
11216        assert_eq!(
11217            scheduler.pending.peek(&peer).map(|e| e.pin),
11218            Some([2; 32]),
11219            "the live nomination replaced the dead incumbent"
11220        );
11221        assert_eq!(
11222            obs.suppressed_lower.load(Ordering::Relaxed),
11223            0,
11224            "no self-erasure signal for displacing a dead pin"
11225        );
11226        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11227        assert_eq!(
11228            obs.outside_answerability_window.load(Ordering::Relaxed),
11229            1,
11230            "the dead incumbent is accounted as an expiry"
11231        );
11232    }
11233
11234    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11235    /// nomination still loses to an answerable higher-count pending pin.
11236    #[test]
11237    fn first_audit_live_incumbent_still_suppresses_lower_count() {
11238        let obs = Arc::new(FirstAuditObservability::default());
11239        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11240        let peer = test_peer(1);
11241
11242        let live_high = MonetizedPinEvent {
11243            peer,
11244            pin: [1; 32],
11245            key_count: 400,
11246            quote_ts: SystemTime::now(),
11247        };
11248        scheduler.enqueue(live_high, &obs);
11249        let cheaper = MonetizedPinEvent {
11250            peer,
11251            pin: [2; 32],
11252            key_count: 100,
11253            quote_ts: SystemTime::now(),
11254        };
11255        scheduler.enqueue(cheaper, &obs);
11256
11257        assert_eq!(scheduler.pending_len(), 1);
11258        assert_eq!(
11259            scheduler.pending.peek(&peer).map(|e| e.pin),
11260            Some([1; 32]),
11261            "the higher-count live pin is retained"
11262        );
11263        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11264        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11265    }
11266
11267    /// A fresh nomination for peer `b` (distinct pin per peer).
11268    fn live_nomination(b: u8) -> MonetizedPinEvent {
11269        MonetizedPinEvent {
11270            peer: test_peer(b),
11271            pin: [b; 32],
11272            key_count: 100,
11273            quote_ts: SystemTime::now(),
11274        }
11275    }
11276
11277    /// The pending admission cap must equal the number of usable launches the
11278    /// token budget can perform inside one answerability window, counted by
11279    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11280    /// tokens at age zero, one refill per launch interval), not by repeating
11281    /// the derivation formula. Any larger and admitted work is guaranteed to
11282    /// expire unlaunched; any smaller and the budget idles while nominations
11283    /// are displaced.
11284    #[test]
11285    fn first_audit_pending_cap_matches_strict_launch_horizon() {
11286        let quote_ts = SystemTime::now();
11287        // Burst launches fire at age zero and must pass the reserve predicate.
11288        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11289        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11290        let mut refill = 1u32;
11291        loop {
11292            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11293            let at = quote_ts + age;
11294            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11295                break;
11296            }
11297            usable += 1;
11298            refill += 1;
11299            assert!(refill < 10_000, "runaway horizon simulation");
11300        }
11301        assert_eq!(
11302            FIRST_AUDIT_PENDING_CAP, usable,
11303            "cap must match the simulated strict launch horizon"
11304        );
11305    }
11306
11307    /// The pending queue is sized to the launch budget while the dedup set
11308    /// keeps the commitment-cache bound: shrinking `first_audited` would
11309    /// forget audited pins and re-admit duplicates.
11310    #[test]
11311    fn first_audit_pending_cap_independent_of_dedup_cap() {
11312        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11313        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11314        assert_eq!(
11315            scheduler.first_audited.cap().get(),
11316            MAX_LAST_COMMITMENT_BY_PEER
11317        );
11318    }
11319
11320    /// Admission beyond the cap displaces exactly one incumbent per overflow
11321    /// and every displacement is accounted as `capacity_evicted` — the steady
11322    /// overload signal — never silent loss, and never an admission refusal.
11323    #[test]
11324    fn first_audit_admission_beyond_cap_displaces_and_counts() {
11325        let obs = Arc::new(FirstAuditObservability::default());
11326        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11327        let overflow: usize = 5;
11328        let total = FIRST_AUDIT_PENDING_CAP + overflow;
11329
11330        for i in 0..total {
11331            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11332            scheduler.enqueue(live_nomination(b), &obs);
11333        }
11334
11335        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11336        assert_eq!(
11337            obs.capacity_evicted.load(Ordering::Relaxed),
11338            u64::try_from(overflow).expect("overflow fits u64"),
11339            "each admission past the cap displaces exactly one entry"
11340        );
11341        assert_eq!(
11342            obs.queued.load(Ordering::Relaxed),
11343            u64::try_from(total).expect("total fits u64"),
11344            "displacement is not an admission refusal"
11345        );
11346        // Every arrival was admitted (the newest always enters the sample).
11347        let last = u8::try_from(total).expect("test peer count fits u8");
11348        assert!(
11349            scheduler.pending.peek(&test_peer(last)).is_some(),
11350            "the newest arrival always enters the sample"
11351        );
11352    }
11353
11354    /// The reviewer-demonstrated suppression route: a target followed by an
11355    /// ordered batch of distinct-peer nominations, all inside one ingress
11356    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11357    /// the token bucket EMPTY so no reservation can intervene. Under the old
11358    /// keep-newest LRU the target was evicted with certainty; under random
11359    /// displacement its per-overflow eviction probability is `1/cap`, so
11360    /// across repeated trials the target must survive some runs and be
11361    /// displaced in others — never deterministically flushed, and every
11362    /// displacement accounted.
11363    #[test]
11364    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11365        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11366        assert!(FIRST_AUDIT_PENDING_CAP < flood);
11367        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11368
11369        let trials = 100u64;
11370        let mut survived = 0u32;
11371        let mut evicted = 0u32;
11372        for trial in 0..trials {
11373            let obs = Arc::new(FirstAuditObservability::default());
11374            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11375            // Deterministic per-trial seed: the run is fully reproducible (no
11376            // flake budget at all) while still exercising 100 distinct
11377            // eviction sequences.
11378            scheduler.rng = StdRng::seed_from_u64(trial);
11379            // Drain the burst tokens so the pre-overflow reservation
11380            // opportunity cannot fire: this isolates pure retention.
11381            scheduler.limiter.reserve_token();
11382            scheduler.limiter.reserve_token();
11383
11384            let target = test_peer(200);
11385            scheduler.enqueue(live_nomination(200), &obs);
11386            for i in 0..flood {
11387                let b = u8::try_from(i + 1).expect("flood peer fits u8");
11388                scheduler.enqueue(live_nomination(b), &obs);
11389            }
11390
11391            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11392            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11393                .expect("overflow count fits u64");
11394            assert_eq!(
11395                obs.capacity_evicted.load(Ordering::Relaxed),
11396                overflows,
11397                "every overflow past the cap is accounted, none silent"
11398            );
11399            if scheduler.pending.peek(&target).is_some() {
11400                survived += 1;
11401            } else {
11402                evicted += 1;
11403            }
11404        }
11405        // With eviction probability 1/cap per overflow, P(target survives one
11406        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11407        // 100 seeded trials — and the seeds make the split exactly
11408        // reproducible rather than a (vanishingly small) flake budget.
11409        assert!(
11410            survived > 0,
11411            "target must survive some ordered floods — deterministic eviction \
11412             would mean keep-newest retention regressed"
11413        );
11414        assert!(
11415            evicted > 0,
11416            "target must also be displaceable — otherwise overflow is refusing \
11417             admissions instead of sampling"
11418        );
11419    }
11420
11421    /// With a token AVAILABLE, an overflowing arrival must first give pending
11422    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
11423    /// one entry out of the queue, so admission proceeds without any eviction.
11424    #[test]
11425    fn first_audit_overflow_reserves_before_destructive_eviction() {
11426        let obs = Arc::new(FirstAuditObservability::default());
11427        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11428        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11429
11430        for i in 0..FIRST_AUDIT_PENDING_CAP {
11431            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11432            scheduler.enqueue(live_nomination(b), &obs);
11433        }
11434        let overflowing = live_nomination(250);
11435        assert!(scheduler.would_displace(&overflowing));
11436
11437        // The drainer's pre-overflow sequence: reserve, then enqueue.
11438        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11439        assert!(
11440            !scheduler.would_displace(&overflowing),
11441            "a successful reservation frees the slot"
11442        );
11443        scheduler.enqueue(overflowing, &obs);
11444
11445        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11446        assert_eq!(
11447            obs.capacity_evicted.load(Ordering::Relaxed),
11448            0,
11449            "no destructive eviction when a launch opportunity existed"
11450        );
11451    }
11452
11453    /// Displacement stamps no suppression state: a displaced peer's next
11454    /// nomination re-enters like any newcomer (it is NOT window-deduped or
11455    /// treated as a duplicate), so under overload every peer keeps an
11456    /// unpredictable chance of prompt first audit.
11457    #[test]
11458    fn first_audit_displaced_peer_may_be_renominated() {
11459        let obs = Arc::new(FirstAuditObservability::default());
11460        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11461        let total = FIRST_AUDIT_PENDING_CAP + 1;
11462
11463        for i in 0..total {
11464            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11465            scheduler.enqueue(live_nomination(b), &obs);
11466        }
11467        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11468        // Find whichever peer the random displacement removed.
11469        let displaced = (1..=total)
11470            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11471            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11472            .expect("exactly one admitted peer was displaced");
11473
11474        scheduler.enqueue(live_nomination(displaced), &obs);
11475
11476        assert!(
11477            scheduler.pending.peek(&test_peer(displaced)).is_some(),
11478            "the displaced peer re-enters the sample"
11479        );
11480        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11481        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11482        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11483        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11484    }
11485
11486    /// The periodic sweep collects expired pending entries even when the token
11487    /// bucket is empty — the reserve path returns at the budget gate and never
11488    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
11489    /// honest under fleet-wide starvation.
11490    #[test]
11491    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11492        let obs = Arc::new(FirstAuditObservability::default());
11493        let mono = Instant::now();
11494        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11495
11496        let dead_quote = SystemTime::now()
11497            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11498            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11499            .expect("past wall time");
11500        scheduler.enqueue(
11501            MonetizedPinEvent {
11502                peer: test_peer(1),
11503                pin: [1; 32],
11504                key_count: 100,
11505                quote_ts: dead_quote,
11506            },
11507            &obs,
11508        );
11509        scheduler.enqueue(
11510            MonetizedPinEvent {
11511                peer: test_peer(2),
11512                pin: [2; 32],
11513                key_count: 100,
11514                quote_ts: SystemTime::now(),
11515            },
11516            &obs,
11517        );
11518        assert_eq!(scheduler.pending_len(), 2);
11519
11520        // Empty the bucket so the reserve path is budget-gated (fleet-wide
11521        // starvation) and cannot collect the dead entry itself.
11522        scheduler.limiter.tokens = 0;
11523        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11524        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11525        assert_eq!(
11526            scheduler.pending_len(),
11527            2,
11528            "budget-gated reserve scans nothing"
11529        );
11530
11531        let wall_now = SystemTime::now();
11532        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11533        assert_eq!(scheduler.pending_len(), 1);
11534        assert!(
11535            scheduler.pending.peek(&test_peer(2)).is_some(),
11536            "the live entry survives the sweep"
11537        );
11538        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11539        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11540        assert!(
11541            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11542            "the age gauge reflects only live work after the sweep"
11543        );
11544    }
11545
11546    #[test]
11547    #[allow(clippy::too_many_lines)]
11548    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11549        let obs = Arc::new(FirstAuditObservability::default());
11550        let mono = Instant::now();
11551        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11552
11553        // A pre-existing window sentinel for an UNRELATED peer must survive the
11554        // cancel byte-for-byte (cancel never touches `recent`).
11555        let sentinel_peer = test_peer(0xAA);
11556        scheduler.limiter.promote(sentinel_peer, 500, mono);
11557        let sentinel_before = scheduler
11558            .limiter
11559            .recent
11560            .peek(&sentinel_peer)
11561            .copied()
11562            .expect("sentinel present");
11563
11564        let peer = test_peer(1);
11565        let a = MonetizedPinEvent {
11566            peer,
11567            pin: [1; 32],
11568            key_count: 100,
11569            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
11570        };
11571        scheduler.enqueue(a, &obs);
11572
11573        let tokens_before = scheduler.tokens();
11574        let lane_before = scheduler.oldest_first_lane;
11575        let launched_before = obs.launched.load(Ordering::Relaxed);
11576        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11577
11578        // Reserve A (jitter 0 so it is immediately due).
11579        let inflight0 = obs.inflight.load(Ordering::Relaxed);
11580        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11581        assert_eq!(scheduler.reserved_peer(), Some(peer));
11582        assert_eq!(
11583            scheduler.tokens(),
11584            tokens_before - 1,
11585            "reserve consumes a token"
11586        );
11587        assert_eq!(
11588            obs.inflight.load(Ordering::Relaxed),
11589            1,
11590            "reserve holds a slot"
11591        );
11592
11593        // A same-peer, same-count successor arrives DURING the reservation. It
11594        // must be retained (bypasses the window for the reserved peer) and must
11595        // NOT create a second reservation.
11596        let b = MonetizedPinEvent {
11597            peer,
11598            pin: [2; 32],
11599            key_count: 100,
11600            quote_ts: SystemTime::now(),
11601        };
11602        scheduler.enqueue(b, &obs);
11603        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11604        assert!(
11605            !scheduler.try_reserve(
11606                mono,
11607                obs.inflight.load(Ordering::Relaxed),
11608                Duration::ZERO,
11609                &cooldown,
11610                &obs
11611            ),
11612            "no second reservation while one is outstanding"
11613        );
11614
11615        // Resolve A with an injected wall time PAST A's answerability cutoff.
11616        let reservation = scheduler
11617            .take_due_reservation(mono)
11618            .expect("A is due at jitter 0");
11619        let wall_fail = a
11620            .quote_ts
11621            .checked_add(GOSSIP_ANSWERABILITY_TTL)
11622            .and_then(|t| t.checked_add(Duration::from_secs(1)))
11623            .expect("past-cutoff wall time");
11624        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11625        assert!(
11626            promoted.is_none(),
11627            "answerability lapsed -> cancelled, not promoted"
11628        );
11629
11630        // State-neutral cancel.
11631        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11632        assert!(
11633            scheduler.limiter.recent.peek(&peer).is_none(),
11634            "cancel stamps no per-peer window"
11635        );
11636        assert_eq!(
11637            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11638            Some(sentinel_before),
11639            "unrelated window sentinel untouched"
11640        );
11641        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11642        assert_eq!(
11643            scheduler.tokens(),
11644            tokens_before,
11645            "token refunded on cancel"
11646        );
11647        assert_eq!(
11648            obs.inflight.load(Ordering::Relaxed),
11649            0,
11650            "in-flight slot released"
11651        );
11652        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11653        assert_eq!(
11654            obs.launched.load(Ordering::Relaxed),
11655            launched_before,
11656            "no launch counted"
11657        );
11658        assert_eq!(
11659            obs.outside_answerability_window.load(Ordering::Relaxed),
11660            1,
11661            "the cancel reason is recorded"
11662        );
11663
11664        // The successor is still pending and is now fully schedulable: a fresh
11665        // reserve makes B the next reservation (proving eligibility, not merely
11666        // that the limiter would admit it).
11667        assert_eq!(
11668            scheduler.pending_len(),
11669            1,
11670            "successor still pending after cancel"
11671        );
11672        assert!(scheduler.reserved.is_none());
11673        assert!(scheduler.try_reserve(
11674            mono,
11675            obs.inflight.load(Ordering::Relaxed),
11676            Duration::ZERO,
11677            &cooldown,
11678            &obs
11679        ));
11680        assert_eq!(
11681            scheduler.reserved_peer(),
11682            Some(peer),
11683            "the retained successor becomes the next reservation"
11684        );
11685    }
11686
11687    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
11688    /// race, the reserved event is requeued ONLY if no same-peer successor is
11689    /// already pending. A successor arrived after the reservation, so it is the
11690    /// newer nomination (e.g. a count jump) and must not be overwritten by the
11691    /// older reserved event.
11692    #[test]
11693    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
11694        let obs = Arc::new(FirstAuditObservability::default());
11695        let mono = Instant::now();
11696        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11697        let peer = test_peer(1);
11698
11699        // Reserve A.
11700        let a = MonetizedPinEvent {
11701            peer,
11702            pin: [1; 32],
11703            key_count: 100,
11704            quote_ts: SystemTime::now(),
11705        };
11706        scheduler.enqueue(a, &obs);
11707        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
11708        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
11709
11710        // A newer same-peer successor B (a count jump) arrives during the
11711        // reservation and is retained.
11712        let b = MonetizedPinEvent {
11713            peer,
11714            pin: [2; 32],
11715            key_count: 400,
11716            quote_ts: SystemTime::now(),
11717        };
11718        scheduler.enqueue(b, &obs);
11719        assert_eq!(scheduler.pending_len(), 1);
11720
11721        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
11722        // is already stamped for the peer, so promotion loses the race.
11723        let reservation = scheduler.take_due_reservation(mono).expect("due");
11724        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11725        cooldown.insert(peer, mono); // freshly on cooldown
11726        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
11727        assert!(promoted.is_none(), "cooldown race -> not promoted");
11728
11729        // B (newer) is preserved; A did NOT overwrite it.
11730        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
11731        assert_eq!(
11732            scheduler.pending.peek(&peer).map(|e| e.pin),
11733            Some([2; 32]),
11734            "the newer successor B is retained, not the older reserved A"
11735        );
11736        assert!(scheduler.first_audited.is_empty());
11737        assert!(scheduler.limiter.recent.peek(&peer).is_none());
11738    }
11739
11740    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
11741    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
11742    /// and saturates to `0` for a future-dated quote (clock skew) without
11743    /// panicking. A climbing value is the pending-work-aging-out signal.
11744    #[test]
11745    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
11746        let now = SystemTime::now();
11747        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11748        assert_eq!(
11749            scheduler.oldest_pending_quote_age_ms(now),
11750            0,
11751            "empty pending -> zero"
11752        );
11753
11754        // Two peers: quotes 10s and 2s old. The gauge must track the older.
11755        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
11756            let _ = coalesce_first_audit_event(
11757                &mut scheduler.pending,
11758                MonetizedPinEvent {
11759                    peer: test_peer(peer_id),
11760                    pin,
11761                    key_count: 100,
11762                    quote_ts: now - Duration::from_secs(secs),
11763                },
11764                true,
11765                &mut scheduler.rng,
11766            );
11767        }
11768        assert_eq!(
11769            scheduler.oldest_pending_quote_age_ms(now),
11770            10_000,
11771            "tracks the oldest (10s), not the newest (2s)"
11772        );
11773
11774        // A future-dated quote (clock skew) saturates to zero, never panics.
11775        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11776        let _ = coalesce_first_audit_event(
11777            &mut skewed.pending,
11778            MonetizedPinEvent {
11779                peer: test_peer(3),
11780                pin: [3; 32],
11781                key_count: 100,
11782                quote_ts: now + Duration::from_secs(5),
11783            },
11784            true,
11785            &mut skewed.rng,
11786        );
11787        assert_eq!(
11788            skewed.oldest_pending_quote_age_ms(now),
11789            0,
11790            "future quote_ts saturates to zero"
11791        );
11792    }
11793
11794    /// A flood of strictly-lower-count same-peer nominations must neither
11795    /// displace the retained higher pin NOR disturb its recency position (each
11796    /// is suppressed via `peek`, no `push`), and each must be counted as
11797    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
11798    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
11799    /// (the documented `lru` contract that also drives the reserve scan's lane
11800    /// ordering), deliberately independent of the overflow policy: eviction is
11801    /// random-victim, so no assertion may require a particular peer to be
11802    /// displaced.
11803    #[test]
11804    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
11805        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
11806            LruCache::new(NonZeroUsize::new(2).unwrap());
11807        let mut rng = StdRng::seed_from_u64(11);
11808        let victim = test_peer(1);
11809        let other = test_peer(2);
11810        // Victim (high count) inserted first (older), then `other` (newer/MRU).
11811        let _ = coalesce_first_audit_event(
11812            &mut pending,
11813            MonetizedPinEvent {
11814                peer: victim,
11815                pin: [1; 32],
11816                key_count: 400,
11817                quote_ts: SystemTime::now(),
11818            },
11819            true,
11820            &mut rng,
11821        );
11822        let _ = coalesce_first_audit_event(
11823            &mut pending,
11824            MonetizedPinEvent {
11825                peer: other,
11826                pin: [9; 32],
11827                key_count: 100,
11828                quote_ts: SystemTime::now(),
11829            },
11830            true,
11831            &mut rng,
11832        );
11833        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11834        assert_eq!(
11835            order_before,
11836            vec![other, victim],
11837            "sanity: `other` is MRU, the victim is LRU"
11838        );
11839
11840        // Flood the victim with cheaper nominations.
11841        let mut suppressed = 0u64;
11842        for i in 0..8u8 {
11843            let out = coalesce_first_audit_event(
11844                &mut pending,
11845                MonetizedPinEvent {
11846                    peer: victim,
11847                    pin: [i; 32],
11848                    key_count: 50,
11849                    quote_ts: SystemTime::now(),
11850                },
11851                true,
11852                &mut rng,
11853            );
11854            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
11855            suppressed += 1;
11856        }
11857        assert_eq!(suppressed, 8);
11858        // Victim pin/count unchanged.
11859        assert_eq!(
11860            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
11861            Some(([1; 32], 400))
11862        );
11863        // Recency untouched: the iteration order (which the reserve lanes
11864        // consume) is byte-for-byte what it was before the flood.
11865        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11866        assert_eq!(
11867            order_after, order_before,
11868            "the suppressed-lower flood must not have changed any recency position"
11869        );
11870    }
11871
11872    /// The cooldown-race requeue counts a genuine different-peer capacity
11873    /// eviction (the ADR promises capacity loss is observable).
11874    #[test]
11875    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
11876        let obs = Arc::new(FirstAuditObservability::default());
11877        let mono = Instant::now();
11878        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11879        // Pending capacity 1 so a requeue of a different peer must evict.
11880        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11881        let reserved_peer = test_peer(1);
11882        let other_peer = test_peer(2);
11883
11884        // Reserve peer 1.
11885        scheduler.enqueue(
11886            MonetizedPinEvent {
11887                peer: reserved_peer,
11888                pin: [1; 32],
11889                key_count: 100,
11890                quote_ts: SystemTime::now(),
11891            },
11892            &obs,
11893        );
11894        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11895        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11896
11897        // A DIFFERENT peer fills the single pending slot during the reservation.
11898        scheduler.enqueue(
11899            MonetizedPinEvent {
11900                peer: other_peer,
11901                pin: [2; 32],
11902                key_count: 100,
11903                quote_ts: SystemTime::now(),
11904            },
11905            &obs,
11906        );
11907        assert_eq!(scheduler.pending_len(), 1);
11908
11909        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
11910        let reservation = scheduler.take_due_reservation(mono).expect("due");
11911        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11912        cooldown.insert(reserved_peer, mono);
11913        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
11914        assert!(scheduler
11915            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11916            .is_none());
11917        assert_eq!(
11918            obs.capacity_evicted.load(Ordering::Relaxed),
11919            cap_before + 1,
11920            "the requeue eviction of a different peer is counted"
11921        );
11922        assert_eq!(
11923            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
11924            Some([1; 32])
11925        );
11926    }
11927
11928    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
11929    /// nomination arriving while an inflated pin is PENDING must not displace it.
11930    /// The inflated pin stays and is the one launched.
11931    #[test]
11932    fn first_audit_pending_lower_count_does_not_replace_higher() {
11933        let obs = Arc::new(FirstAuditObservability::default());
11934        let mono = Instant::now();
11935        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11936        let peer = test_peer(1);
11937
11938        // Inflated (high-count) sidecar pin lands in pending.
11939        scheduler.enqueue(
11940            MonetizedPinEvent {
11941                peer,
11942                pin: [1; 32],
11943                key_count: 400,
11944                quote_ts: SystemTime::now(),
11945            },
11946            &obs,
11947        );
11948        // A cheaper same-peer settlement arrives right after.
11949        scheduler.enqueue(
11950            MonetizedPinEvent {
11951                peer,
11952                pin: [2; 32],
11953                key_count: 100,
11954                quote_ts: SystemTime::now(),
11955            },
11956            &obs,
11957        );
11958
11959        assert_eq!(scheduler.pending_len(), 1);
11960        assert_eq!(
11961            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11962            Some(([1; 32], 400)),
11963            "the inflated pin must not be erased by the cheaper successor"
11964        );
11965        // The dropped cheaper nomination is counted through the enqueue path.
11966        assert_eq!(
11967            obs.suppressed_lower.load(Ordering::Relaxed),
11968            1,
11969            "the attempted cheaper-pin self-erasure is observable"
11970        );
11971
11972        // It reserves and promotes as the inflated pin/count.
11973        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11974        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11975        let reservation = scheduler.take_due_reservation(mono).expect("due");
11976        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11977        let (event, _slot) = scheduler
11978            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11979            .expect("promotes");
11980        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
11981    }
11982
11983    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
11984    /// loses the cooldown race must be requeued OVER a lower-count same-peer
11985    /// successor that arrived during its jitter, and must remain launchable once
11986    /// the shared cooldown expires — the cheaper successor cannot suppress it.
11987    #[test]
11988    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
11989        let obs = Arc::new(FirstAuditObservability::default());
11990        let mono = Instant::now();
11991        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11992        let peer = test_peer(1);
11993
11994        // Reserve the inflated pin.
11995        scheduler.enqueue(
11996            MonetizedPinEvent {
11997                peer,
11998                pin: [1; 32],
11999                key_count: 400,
12000                quote_ts: SystemTime::now(),
12001            },
12002            &obs,
12003        );
12004        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12005        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12006
12007        // A cheaper successor arrives during the reservation (bypasses the
12008        // window as the reserved peer) and sits in pending.
12009        scheduler.enqueue(
12010            MonetizedPinEvent {
12011                peer,
12012                pin: [2; 32],
12013                key_count: 100,
12014                quote_ts: SystemTime::now(),
12015            },
12016            &obs,
12017        );
12018        assert_eq!(scheduler.pending_len(), 1);
12019
12020        // Resolve: answerability passes but the shared cooldown is already
12021        // stamped, so the reservation loses the race and requeues.
12022        let reservation = scheduler.take_due_reservation(mono).expect("due");
12023        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12024        cooldown.insert(peer, mono);
12025        assert!(scheduler
12026            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12027            .is_none());
12028
12029        // The inflated pin (400) replaced the cheaper successor (100).
12030        assert_eq!(scheduler.pending_len(), 1);
12031        assert_eq!(
12032            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12033            Some(([1; 32], 400)),
12034            "the inflated reserved pin must survive the requeue over the cheaper successor"
12035        );
12036        assert!(scheduler.first_audited.is_empty());
12037        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12038
12039        // Once the shared cooldown expires, the inflated pin reserves and
12040        // promotes with its intended pin/count.
12041        let later = mono
12042            .checked_add(Duration::from_secs(
12043                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12044            ))
12045            .expect("later");
12046        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12047        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12048        let reservation = scheduler.take_due_reservation(later).expect("due");
12049        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12050        let (event, _slot) = scheduler
12051            .resolve(
12052                reservation,
12053                SystemTime::now(),
12054                later,
12055                &mut cooldown_later,
12056                &obs,
12057            )
12058            .expect("promotes after cooldown");
12059        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12060    }
12061
12062    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12063    /// launch lane, driven through the real scheduler (reserve -> resolve ->
12064    /// promote), so a stream of fresh nominations cannot keep every launch on
12065    /// the newest lane and starve the oldest.
12066    #[test]
12067    fn first_audit_lane_alternates_across_promotions() {
12068        let obs = Arc::new(FirstAuditObservability::default());
12069        let mono = Instant::now();
12070        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12071        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12072
12073        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12074        let oldest_peer = test_peer(1);
12075        let newest_peer = test_peer(2);
12076        scheduler.enqueue(
12077            MonetizedPinEvent {
12078                peer: oldest_peer,
12079                pin: [1; 32],
12080                key_count: 100,
12081                quote_ts: SystemTime::now(),
12082            },
12083            &obs,
12084        );
12085        scheduler.enqueue(
12086            MonetizedPinEvent {
12087                peer: newest_peer,
12088                pin: [2; 32],
12089                key_count: 100,
12090                quote_ts: SystemTime::now(),
12091            },
12092            &obs,
12093        );
12094
12095        let mut launched_peers = Vec::new();
12096        for _ in 0..2 {
12097            assert!(scheduler.try_reserve(
12098                mono,
12099                obs.inflight.load(Ordering::Relaxed),
12100                Duration::ZERO,
12101                &cooldown,
12102                &obs
12103            ));
12104            let reservation = scheduler.take_due_reservation(mono).expect("due");
12105            // Answerable wall time == the quote's own time (age 0).
12106            let (event, _slot) = scheduler
12107                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12108                .expect("fresh in-window quote promotes");
12109            launched_peers.push(event.peer);
12110        }
12111
12112        // First launch takes the newest lane (lane starts false = newest), the
12113        // second takes the oldest lane: strict alternation.
12114        assert_eq!(
12115            launched_peers,
12116            vec![newest_peer, oldest_peer],
12117            "consecutive promotions alternate newest-then-oldest lane"
12118        );
12119    }
12120
12121    #[test]
12122    fn first_audit_count_jump_boundaries() {
12123        // Exactly 1.5x is NOT a jump; strictly above is.
12124        assert!(!first_audit_count_jump(100, 150));
12125        assert!(first_audit_count_jump(100, 151));
12126        // Anything beats an audited zero; zero never jumps.
12127        assert!(first_audit_count_jump(0, 1));
12128        assert!(!first_audit_count_jump(0, 0));
12129        // Equal max counts must not jump (and must not overflow).
12130        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12131    }
12132
12133    /// A verified payment's quote list includes the local node's own quote, so
12134    /// the verifier emits a monetized-pin event for the local peer on every
12135    /// payment it verifies. The node cannot network-audit itself, so the
12136    /// scheduler must drop such an event at ingress: never queued, and hence
12137    /// never launched nor marked first-audited.
12138    #[test]
12139    fn first_audit_queue_drops_self_targeting_events() {
12140        let obs = Arc::new(FirstAuditObservability::default());
12141        let self_peer = test_peer(1);
12142        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12143        let self_event = MonetizedPinEvent {
12144            peer: self_peer,
12145            pin: [7; 32],
12146            key_count: 1,
12147            quote_ts: SystemTime::now(),
12148        };
12149
12150        scheduler.enqueue(self_event, &obs);
12151        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12152        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12153        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12154
12155        // A remote peer's event still queues normally under the same filter.
12156        let remote_event = MonetizedPinEvent {
12157            peer: test_peer(2),
12158            pin: [8; 32],
12159            ..self_event
12160        };
12161        scheduler.enqueue(remote_event, &obs);
12162        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12163        assert_eq!(scheduler.pending_len(), 1);
12164        assert_eq!(
12165            obs.self_target_skipped.load(Ordering::Relaxed),
12166            1,
12167            "remote event must not count as a self-target skip"
12168        );
12169    }
12170
12171    #[test]
12172    fn fresh_offer_runs_store_admission_payment_checks() {
12173        let context = fresh_offer_payment_context();
12174        assert_eq!(context, VerificationContext::FreshReplication);
12175        // Fresh replication must keep verifying exactly like a direct client
12176        // PUT (store-strength cache, same live checks); the variant only
12177        // exists so price-floor telemetry can tell the two paths apart.
12178        assert!(context.is_store_admission());
12179    }
12180
12181    #[test]
12182    fn paid_notify_uses_paid_list_admission_payment_checks() {
12183        assert_eq!(
12184            paid_notify_payment_context(),
12185            VerificationContext::PaidListAdmission
12186        );
12187    }
12188
12189    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12190    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12191    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12192    #[test]
12193    fn monetized_quote_audit_window_fails_closed_both_ends() {
12194        let now = SystemTime::now();
12195        // Fresh (just quoted) and small future/past skew -> audited.
12196        assert!(quote_within_audit_window(now, now));
12197        assert!(quote_within_audit_window(
12198            now + Duration::from_secs(60),
12199            now
12200        ));
12201        assert!(quote_within_audit_window(
12202            now - Duration::from_secs(3600),
12203            now
12204        ));
12205        // Far future (badly-skewed / replayed) -> skipped.
12206        assert!(!quote_within_audit_window(
12207            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12208            now
12209        ));
12210        // Older than the window -> skipped (pin may have aged out).
12211        assert!(!quote_within_audit_window(
12212            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12213            now
12214        ));
12215    }
12216
12217    #[tokio::test]
12218    async fn replication_branch_lagged_events_are_counted() {
12219        let before = audit_metrics::replication_event_lagged_total();
12220        let flow = handle_replication_event_recv_error(
12221            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12222        );
12223        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12224        let after = audit_metrics::replication_event_lagged_total();
12225        assert_eq!(after.saturating_sub(before), 3);
12226    }
12227
12228    #[tokio::test]
12229    async fn replication_branch_closed_events_stop_the_loop() {
12230        let flow =
12231            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12232        assert_eq!(flow, std::ops::ControlFlow::Break(()));
12233    }
12234
12235    #[tokio::test]
12236    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12237        let (sender, mut receiver) = mpsc::channel(1);
12238        let dropped_body =
12239            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12240                keys: Vec::new(),
12241                paid_list_check_indices: Vec::new(),
12242            });
12243        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12244        let first = InboundReplicationMessage {
12245            source: test_peer(0xC1),
12246            msg: ReplicationMessage {
12247                request_id: 1,
12248                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12249                    key: test_key(1),
12250                }),
12251            },
12252            rr_message_id: None,
12253            received_at: Instant::now(),
12254        };
12255        let second = InboundReplicationMessage {
12256            source: test_peer(0xC2),
12257            msg: ReplicationMessage {
12258                request_id: 2,
12259                body: dropped_body.clone(),
12260            },
12261            rr_message_id: None,
12262            received_at: Instant::now(),
12263        };
12264
12265        assert!(try_enqueue_serial_message(&sender, first).is_ok());
12266        let dropped = try_enqueue_serial_message(&sender, second)
12267            .expect_err("a full serial queue must refuse the second message");
12268        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12269        assert_eq!(dropped.message_class, "verification_request");
12270        assert_eq!(dropped.queue_depth, 1);
12271        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12272        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12273
12274        let queued = receiver
12275            .recv()
12276            .await
12277            .expect("first message should remain queued");
12278        assert_eq!(queued.msg.request_id, 1);
12279        assert!(receiver.try_recv().is_err());
12280    }
12281
12282    #[tokio::test]
12283    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12284        let peer = test_peer(0x44);
12285        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12286
12287        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12288        let mut digest_guards = Vec::new();
12289        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12290            let guard = admit_audit_responder(
12291                &semaphore,
12292                &digest_inflight,
12293                &peer,
12294                AuditResponderClass::Digest,
12295            )
12296            .await;
12297            assert!(guard.is_ok());
12298            digest_guards.push(guard);
12299        }
12300        assert!(
12301            admit_audit_responder(
12302                &semaphore,
12303                &digest_inflight,
12304                &peer,
12305                AuditResponderClass::Digest,
12306            )
12307            .await
12308            .is_err(),
12309            "digest class must stop at its documented per-source cap"
12310        );
12311        drop(digest_guards);
12312
12313        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12314        let mut subtree_guards = Vec::new();
12315        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12316            let guard = admit_audit_responder(
12317                &semaphore,
12318                &subtree_inflight,
12319                &peer,
12320                AuditResponderClass::Subtree,
12321            )
12322            .await;
12323            assert!(guard.is_ok());
12324            subtree_guards.push(guard);
12325        }
12326        assert!(
12327            admit_audit_responder(
12328                &semaphore,
12329                &subtree_inflight,
12330                &peer,
12331                AuditResponderClass::Subtree,
12332            )
12333            .await
12334            .is_err(),
12335            "subtree class must retain the deployed cap of two"
12336        );
12337        drop(subtree_guards);
12338    }
12339
12340    #[test]
12341    fn in_scope_audit_deadlines_share_one_formula() {
12342        let config = config::ReplicationConfig::default();
12343        for key_count in [1, 4, 16] {
12344            assert_eq!(
12345                audit::responsible_audit_response_timeout(&config, key_count),
12346                config.audit_response_timeout(key_count)
12347            );
12348            assert_eq!(
12349                pruning::prune_audit_response_timeout(&config, key_count),
12350                config.audit_response_timeout(key_count)
12351            );
12352        }
12353        assert_eq!(
12354            possession::possession_probe_response_timeout(&config),
12355            config.audit_response_timeout(1)
12356        );
12357    }
12358
12359    #[test]
12360    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12361        const EXISTING_SOURCE_ID: u8 = 1;
12362        const HINT_SENDER_ID: u8 = 2;
12363
12364        let existing_source = test_peer(EXISTING_SOURCE_ID);
12365        let hint_sender = test_peer(HINT_SENDER_ID);
12366        let mut sources = vec![existing_source];
12367
12368        let hint_sources = HashSet::from([hint_sender]);
12369        add_replica_hint_sources(&mut sources, &hint_sources);
12370        add_replica_hint_sources(&mut sources, &hint_sources);
12371
12372        // A paid-only advertiser leaves the claim set empty (see
12373        // `queue_admitted_hints`), so it contributes no fetch source.
12374        add_replica_hint_sources(&mut sources, &HashSet::new());
12375
12376        assert_eq!(sources, vec![existing_source, hint_sender]);
12377    }
12378
12379    #[test]
12380    fn audit_timeout_preserves_active_bootstrap_claim() {
12381        assert!(!audit_failure_clears_bootstrap_claim(
12382            &AuditFailureReason::Timeout
12383        ));
12384    }
12385
12386    fn strike_peer(b: u8) -> PeerId {
12387        let mut bytes = [0u8; 32];
12388        bytes[0] = b;
12389        PeerId::from_bytes(bytes)
12390    }
12391
12392    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12393    // cooldown must collapse a gossip flood into at most one audit per window.
12394
12395    #[test]
12396    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12397        let peer = strike_peer(1);
12398        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12399        let t0 = Instant::now();
12400        // First gossip in the window passes; a burst of further gossips at the
12401        // same instant are all suppressed.
12402        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12403        let mut passed = 1;
12404        for _ in 0..100 {
12405            if cooldown_allows_audit(&mut map, &peer, t0) {
12406                passed += 1;
12407            }
12408        }
12409        assert_eq!(
12410            passed, 1,
12411            "a flood at one instant must trigger exactly one audit"
12412        );
12413    }
12414
12415    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12416    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12417    // consumes the window. This is the property the isolated cooldown tests above
12418    // cannot see: they never sample the lottery, so a regression that reordered
12419    // the gates (sample probability first, only stamp the cooldown on a win)
12420    // would still pass them while breaking flood-resistance: a flood would then
12421    // re-roll the lottery on EVERY message until one won, multiplying audits.
12422    //
12423    // We model the exact production gate order (attempt-window, lottery,
12424    // shared cooldown) with a lottery driven by a fixed outcome instead of
12425    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
12426    // messages all WIN. With the production order, the losing first ticket
12427    // burns the ATTEMPT window and every later winner in the same window is
12428    // blocked, so there are 0 audits this window. If the gates were flipped,
12429    // the second message's winning ticket would slip through. The window only
12430    // reopens after it elapses.
12431    //
12432    // FLIPS IF: the lottery is sampled before the attempt-window
12433    // check-and-stamp (a losing ticket no longer consumes the window),
12434    // re-enabling a flood-amplified audit storm.
12435    #[test]
12436    fn losing_lottery_still_consumes_attempt_window() {
12437        // Calls the SHIPPED `audit_launch_decision` (the same function
12438        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
12439        // production fails this test — not a local reimplementation.
12440        let peer = strike_peer(3);
12441        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12442        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12443        let t0 = Instant::now();
12444
12445        // First flooded message at t0 LOSES the lottery, but the attempt window
12446        // is stamped BEFORE the lottery is consulted, so the window is consumed.
12447        assert!(
12448            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12449            "a losing ticket launches no audit"
12450        );
12451
12452        // 99 more flooded messages at the same instant would all WIN the lottery,
12453        // yet every one must be blocked by the attempt window the loser stamped.
12454        // (If production sampled the lottery FIRST, these would each get a fresh
12455        // roll and audits would multiply — this assertion catches that reorder.)
12456        let mut audits = 0;
12457        for _ in 0..99 {
12458            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12459                audits += 1;
12460            }
12461        }
12462        assert_eq!(
12463            audits, 0,
12464            "a losing first ticket must consume the attempt window so no later \
12465             flooded message in the same window can audit"
12466        );
12467
12468        // The window only reopens after it elapses; the next winning ticket
12469        // then launches exactly one audit and stamps the SHARED cooldown.
12470        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12471        assert!(
12472            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12473            "after the window a winning ticket audits again"
12474        );
12475        assert!(
12476            launched.contains_key(&peer),
12477            "a real launch stamps the shared cooldown"
12478        );
12479    }
12480
12481    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
12482    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
12483    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
12484    /// first audit deferred until its answerability window expires.
12485    ///
12486    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
12487    /// loss (the pre-split behavior, where both paths shared one map).
12488    #[test]
12489    fn losing_lottery_does_not_suppress_monetized_first_audit() {
12490        let peer = strike_peer(4);
12491        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12492        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12493        let t0 = Instant::now();
12494
12495        // A losing ticket consumes the gossip attempt window...
12496        assert!(!audit_launch_decision(
12497            &mut attempts,
12498            &mut launched,
12499            &peer,
12500            t0,
12501            false
12502        ));
12503        // ...but leaves the shared map untouched, so the first-audit reserve
12504        // gate (read-only) and the authoritative promotion check-and-stamp both
12505        // still allow the paid audit to launch immediately.
12506        assert!(
12507            cooldown_would_allow(&launched, &peer, t0),
12508            "reserve gate must not see a losing ticket as audit coverage"
12509        );
12510        assert!(
12511            cooldown_allows_audit(&mut launched, &peer, t0),
12512            "promotion must not be deferred by a losing ticket"
12513        );
12514
12515        // Conversely a WINNING ticket (real audit sent) does suppress the
12516        // first audit for the window, which is the intended shared semantics.
12517        let peer_won = strike_peer(5);
12518        assert!(audit_launch_decision(
12519            &mut attempts,
12520            &mut launched,
12521            &peer_won,
12522            t0,
12523            true
12524        ));
12525        assert!(
12526            !cooldown_would_allow(&launched, &peer_won, t0),
12527            "a real gossip audit still covers the peer for the window"
12528        );
12529    }
12530
12531    #[test]
12532    fn cooldown_lets_audit_through_after_the_window() {
12533        let peer = strike_peer(2);
12534        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12535        let t0 = Instant::now();
12536        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12537        // Within the window: suppressed.
12538        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12539        assert!(!cooldown_allows_audit(&mut map, &peer, within));
12540        // Past the window: allowed again.
12541        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12542        assert!(cooldown_allows_audit(&mut map, &peer, after));
12543    }
12544
12545    #[test]
12546    fn cooldown_is_per_peer_independent() {
12547        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12548        let t0 = Instant::now();
12549        // Different peers each get their own first-audit pass at the same instant.
12550        for i in 0..20u8 {
12551            assert!(
12552                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12553                "peer {i} should be auditable independently"
12554            );
12555        }
12556    }
12557
12558    #[test]
12559    fn audit_on_gossip_constants_match_adr() {
12560        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
12561        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
12562        // values above 5 would silently never be requested).
12563        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12564        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12565        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12566    }
12567
12568    // (d) A confirmed storage-integrity failure penalizes immediately and
12569    // revokes credit; it is not a timeout.
12570    #[test]
12571    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12572        assert!(audit_failure_clears_bootstrap_claim(
12573            &AuditFailureReason::DigestMismatch
12574        ));
12575        assert!(audit_failure_revokes_holder_credit(
12576            &AuditFailureReason::DigestMismatch
12577        ));
12578    }
12579
12580    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
12581    /// uses: confirmed failures revoke credit, `Timeout` does not.
12582    #[test]
12583    fn confirmed_failures_revoke_credit_timeout_does_not() {
12584        for reason in [
12585            AuditFailureReason::MalformedResponse,
12586            AuditFailureReason::DigestMismatch,
12587            AuditFailureReason::KeyAbsent,
12588            AuditFailureReason::Rejected,
12589        ] {
12590            assert!(
12591                audit_failure_revokes_holder_credit(&reason),
12592                "confirmed failure {reason:?} must revoke holder credit"
12593            );
12594        }
12595        assert!(
12596            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12597            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12598        );
12599    }
12600
12601    /// Wiring test for the security fix: the helper the handler calls
12602    /// actually strips a credited peer on a confirmed failure
12603    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
12604    /// Records genuine credit first so neither assertion is vacuous;
12605    /// this fails if `forget_peer` stops being called, or if the
12606    /// `Timeout` exclusion is dropped (both verified by mutation).
12607    #[test]
12608    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12609        let peer = test_peer(0xAB);
12610        let key = test_key(1);
12611        let hash = [0xCD; 32];
12612
12613        // Confirmed failure -> credit revoked.
12614        let mut provers = RecentProvers::new();
12615        provers.record_proof(key, peer, hash, Instant::now());
12616        assert!(
12617            provers.is_credited_holder(&key, &peer, &hash),
12618            "precondition: peer credited before failure"
12619        );
12620        apply_audit_failure_credit_revocation(
12621            &mut provers,
12622            &peer,
12623            &AuditFailureReason::DigestMismatch,
12624        );
12625        assert!(
12626            !provers.is_credited_holder(&key, &peer, &hash),
12627            "DigestMismatch must strip the peer's holder credit"
12628        );
12629
12630        // Timeout -> credit retained.
12631        let mut provers_timeout = RecentProvers::new();
12632        provers_timeout.record_proof(key, peer, hash, Instant::now());
12633        apply_audit_failure_credit_revocation(
12634            &mut provers_timeout,
12635            &peer,
12636            &AuditFailureReason::Timeout,
12637        );
12638        assert!(
12639            provers_timeout.is_credited_holder(&key, &peer, &hash),
12640            "Timeout must retain holder credit (deliberate liveness cushion)"
12641        );
12642    }
12643
12644    #[test]
12645    fn decoded_audit_failures_clear_active_bootstrap_claim() {
12646        for reason in [
12647            AuditFailureReason::MalformedResponse,
12648            AuditFailureReason::DigestMismatch,
12649            AuditFailureReason::KeyAbsent,
12650            AuditFailureReason::Rejected,
12651        ] {
12652            assert!(
12653                audit_failure_clears_bootstrap_claim(&reason),
12654                "decoded non-bootstrap failure {reason:?} should clear active claim"
12655            );
12656        }
12657    }
12658
12659    #[test]
12660    fn first_failed_key_label_truncates_to_16_hex_chars() {
12661        // The high-order 8 bytes of the XorName determine the label so an
12662        // operator can group audit-failures on the same chunk prefix.
12663        let mut key = [0u8; 32];
12664        key[0] = 0x18;
12665        key[7] = 0xff;
12666        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
12667        // to verify they are NOT included in the label.
12668        for byte in &mut key[8..] {
12669            *byte = 0xAA;
12670        }
12671        let label = first_failed_key_label(&[key]);
12672        // Only the first 8 bytes are encoded, low-order bytes are dropped.
12673        assert_eq!(label, "0x18000000000000ff");
12674        assert_eq!(label.len(), "0x".len() + 16);
12675    }
12676
12677    #[test]
12678    fn first_failed_key_label_falls_back_when_empty() {
12679        // Should never happen in production (audit failure handling rejects
12680        // empty sets), but the formatter must still produce a valid label
12681        // so the log line doesn't contain a misleading default.
12682        assert_eq!(first_failed_key_label(&[]), "0x");
12683    }
12684
12685    #[test]
12686    fn first_failed_key_label_uses_first_key_only() {
12687        let first = [0x11u8; 32];
12688        let second = [0x22u8; 32];
12689        assert_eq!(
12690            first_failed_key_label(&[first, second]),
12691            format!("0x{}", hex::encode(&first[..8]))
12692        );
12693    }
12694
12695    // -- apply_fetch_result --------------------------------------------------
12696    //
12697    // The worker's disposition of a fetch outcome. Note there is no trust
12698    // handle in `apply_fetch_result`'s signature: the worker cannot report a
12699    // trust event for ANY outcome, and `execute_single_fetch` returns
12700    // `NoLongerResponsible` before its trust-reporting paths — the source did
12701    // nothing wrong when this node's own responsibility lapsed.
12702
12703    /// Route `key` through the real pipeline stages (pending → promoted →
12704    /// dequeued → in-flight) so it carries a verification retry-slot
12705    /// reservation, exactly as a worker-dequeued key does. Returns the
12706    /// in-flight source.
12707    fn drive_key_in_flight(
12708        q: &mut ReplicationQueues,
12709        key: XorName,
12710        sources: Vec<PeerId>,
12711    ) -> PeerId {
12712        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
12713        let now = Instant::now();
12714        let entry = VerificationEntry {
12715            state: VerificationState::PendingVerify,
12716            verified_sources: Vec::new(),
12717            tried_sources: HashSet::new(),
12718            created_at: now,
12719            next_verify_at: now,
12720            hint_sources: HashSet::from([hinter]),
12721            replica_hint_sources: HashSet::from([hinter]),
12722        };
12723        assert!(q.add_pending_verify(key, entry).admitted());
12724        assert!(q.promote_pending_to_fetch(key, key, sources));
12725        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
12726        let source = *candidate.sources.first().expect("candidate has a source");
12727        q.start_dequeued_fetch(candidate, source);
12728        source
12729    }
12730
12731    #[test]
12732    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
12733        const RETRY_AFTER: Duration = Duration::from_secs(60);
12734
12735        let mut q = ReplicationQueues::new();
12736        let key = test_key(0xAB);
12737        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
12738        assert_eq!(q.retry_reserved_slot_count(), 1);
12739
12740        let follow_up =
12741            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
12742
12743        assert_eq!(
12744            follow_up,
12745            FetchFollowUp::Terminal,
12746            "lapsed responsibility must run the caller's terminal bootstrap accounting"
12747        );
12748        assert!(
12749            !q.contains_key(&key),
12750            "the key must leave every pipeline stage — alternate sources included"
12751        );
12752        assert_eq!(
12753            q.pending_count(),
12754            0,
12755            "a lapsed-responsibility key must not be requeued for verification"
12756        );
12757        assert_eq!(
12758            q.retry_reserved_slot_count(),
12759            0,
12760            "terminal exit must release the verification retry-slot reservation"
12761        );
12762    }
12763
12764    #[test]
12765    fn no_longer_responsible_shares_the_stored_terminal_path() {
12766        const RETRY_AFTER: Duration = Duration::from_secs(60);
12767
12768        // Both variants must walk the identical terminal gate so the
12769        // battle-tested Stored accounting (retry-slot release + bootstrap
12770        // pending-set shrink in the caller) covers lapsed responsibility too.
12771        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
12772            let mut q = ReplicationQueues::new();
12773            let key = test_key(0xCD);
12774            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
12775
12776            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
12777
12778            assert_eq!(follow_up, FetchFollowUp::Terminal);
12779            assert!(!q.contains_key(&key));
12780            assert_eq!(q.retry_reserved_slot_count(), 0);
12781        }
12782    }
12783
12784    #[test]
12785    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
12786        const RETRY_AFTER: Duration = Duration::from_secs(60);
12787
12788        let mut q = ReplicationQueues::new();
12789        let key = test_key(0xEF);
12790        let first = test_peer(0x04);
12791        let second = test_peer(0x05);
12792        drive_key_in_flight(&mut q, key, vec![first, second]);
12793
12794        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12795        assert_eq!(
12796            follow_up,
12797            FetchFollowUp::RetryFrom(second),
12798            "a failed source must not abandon the remaining verified sources"
12799        );
12800        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
12801
12802        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12803        assert_eq!(
12804            follow_up,
12805            FetchFollowUp::RequeuedForVerification,
12806            "exhausted sources must restore the reserved verification entry"
12807        );
12808        assert_eq!(q.pending_count(), 1);
12809        assert_eq!(
12810            q.retry_reserved_slot_count(),
12811            0,
12812            "the reservation converts back into the pending entry itself"
12813        );
12814    }
12815
12816    #[test]
12817    fn source_failure_without_retry_metadata_is_terminal() {
12818        const RETRY_AFTER: Duration = Duration::from_secs(60);
12819
12820        // Direct enqueue (no pending entry) models a fetch with no
12821        // verification retry reservation to restore.
12822        let mut q = ReplicationQueues::new();
12823        let key = test_key(0x1F);
12824        let source = test_peer(0x06);
12825        assert!(q.enqueue_fetch(key, key, vec![source]));
12826        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12827        q.start_dequeued_fetch(candidate, source);
12828
12829        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12830
12831        assert_eq!(follow_up, FetchFollowUp::Terminal);
12832        assert!(!q.contains_key(&key));
12833    }
12834}