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    /// This node could not write the chunk locally: the capacity pre-check
8248    /// refused before the dial, or `put` failed after the bytes arrived.
8249    ///
8250    /// Distinct from [`Self::SourceFailed`] because nothing about the source
8251    /// is implicated, and because the remedy is the opposite one. A source
8252    /// failure should move on to the next holder; a local write failure must
8253    /// not — every remaining source would send the same chunk into the same
8254    /// full disk. The key returns to verification instead, so a later cycle
8255    /// retries it once local capacity allows. That is a retry path, not a
8256    /// liveness guarantee: `evict_stale` still expires the entry at
8257    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8258    /// which re-acquisition depends on a fresh hint.
8259    LocalWriteFailed,
8260    /// This node already holds the key, so there is nothing to fetch —
8261    /// terminal, exactly like [`Self::Stored`], because the duty is already
8262    /// discharged.
8263    ///
8264    /// Responsibility is rechecked at download time; possession has to be too.
8265    /// The earlier gates already drop held keys out of the fetch pipeline —
8266    /// `queue_admitted_hints` skips them, and the promotion-time
8267    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8268    /// them. (`is_relevant` is not one of them: possession there makes a key
8269    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8270    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8271    /// client PUT, or another source landing first. The nearest-first fetch
8272    /// queue is deep enough for that window to be real.
8273    ///
8274    /// This check must also precede the capacity pre-check below, because
8275    /// `LmdbStorage::put` tests `exists` *before* it tests disk space: without
8276    /// it, a full node would decline a key it already holds, which `put` would
8277    /// have accepted as a duplicate.
8278    AlreadyHeld,
8279    /// Live routing state no longer places this node in the storage-admission
8280    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8281    /// the fetch was serving has lapsed, so no alternate source is tried and
8282    /// no trust event is reported: the source did nothing wrong.
8283    NoLongerResponsible,
8284}
8285
8286/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8287/// worker loop to update queue state.
8288struct FetchOutcome {
8289    key: XorName,
8290    result: FetchResult,
8291}
8292
8293/// What the fetch worker must do next for a key whose fetch attempt resolved.
8294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8295enum FetchFollowUp {
8296    /// The key terminally left the fetch pipeline (its in-flight entry is
8297    /// removed and any verification retry-slot reservation released); the
8298    /// caller must run bootstrap accounting for it.
8299    Terminal,
8300    /// The key returned to `pending_verify` for a later verification round.
8301    RequeuedForVerification,
8302    /// Retry immediately from this next untried verified source.
8303    RetryFrom(PeerId),
8304}
8305
8306/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8307///
8308/// Split out of the fetch-worker loop so the per-variant queue transitions
8309/// are unit-testable without a live network. The caller holds the queues
8310/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8311/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8312/// retry-slot reservation, and the caller's terminal handling shrinks the
8313/// bootstrap pending set — dropping the key without that accounting would
8314/// stall bootstrap drain forever.
8315///
8316/// The nursery `option_if_let_else` rewrite is impossible here: both
8317/// `map_or_else` closures would need `&mut *q` simultaneously.
8318#[allow(clippy::option_if_let_else)]
8319fn apply_fetch_result(
8320    q: &mut ReplicationQueues,
8321    key: &XorName,
8322    result: &FetchResult,
8323    verification_retry_after: Duration,
8324) -> FetchFollowUp {
8325    match result {
8326        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8327            q.complete_fetch(key);
8328            FetchFollowUp::Terminal
8329        }
8330        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8331            if let Some(next_peer) = q.retry_fetch(key) {
8332                FetchFollowUp::RetryFrom(next_peer)
8333            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8334                FetchFollowUp::RequeuedForVerification
8335            } else {
8336                FetchFollowUp::Terminal
8337            }
8338        }
8339        // No `retry_fetch`: the local write is what failed, so every other
8340        // source would be asked to send the same chunk into the same full
8341        // disk. Requeueing for verification is what keeps the key from being
8342        // stranded — it comes back once capacity allows — and the fallthrough
8343        // to `Terminal` when there is no retry metadata is what keeps
8344        // bootstrap drain accounting correct, exactly as for a source failure.
8345        FetchResult::LocalWriteFailed => {
8346            if q.requeue_fetch_for_verification(key, verification_retry_after) {
8347                FetchFollowUp::RequeuedForVerification
8348            } else {
8349                FetchFollowUp::Terminal
8350            }
8351        }
8352    }
8353}
8354
8355/// Whether this node currently sits inside the storage-admission group for
8356/// `key`, per live local routing state.
8357///
8358/// This is the one question every storage decision in this module asks; see
8359/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8360/// network I/O — but it awaits into the DHT manager, so callers must not
8361/// hold the queues lock across it.
8362async fn is_storage_admitted(
8363    self_id: &PeerId,
8364    key: &XorName,
8365    p2p_node: &Arc<P2PNode>,
8366    config: &ReplicationConfig,
8367) -> bool {
8368    admission::is_responsible(
8369        self_id,
8370        key,
8371        p2p_node,
8372        storage_admission_width(config.close_group_size),
8373    )
8374    .await
8375}
8376
8377#[allow(clippy::too_many_lines)]
8378/// Execute a single fetch request against `source` for `key`.
8379///
8380/// Handles encoding, network I/O, integrity checking, storage, and trust
8381/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8382/// queue state without holding any locks during the network round-trip.
8383///
8384/// This is the authoritative storage-responsibility gate: each attempt —
8385/// including every per-source retry, which re-enters here — rechecks live
8386/// routing state before spending bandwidth, and once more before writing
8387/// bytes that arrived after a round-trip. The verification-time check that
8388/// promoted the key into the fetch queue is only a pre-filter; the queue is
8389/// nearest-first and deep, so a promotion decision can go stale under
8390/// topology churn before the key is ever dequeued.
8391async fn execute_single_fetch(
8392    p2p_node: Arc<P2PNode>,
8393    storage: Arc<LmdbStorage>,
8394    config: Arc<ReplicationConfig>,
8395    key: XorName,
8396    source: PeerId,
8397) -> FetchOutcome {
8398    let self_id = *p2p_node.peer_id();
8399    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8400        debug!(
8401            "Skipping fetch for {}: no longer in the storage-admission group",
8402            hex::encode(key)
8403        );
8404        return FetchOutcome {
8405            key,
8406            result: FetchResult::NoLongerResponsible,
8407        };
8408    }
8409
8410    // Possession, then capacity — both before the dial, and in that order.
8411    //
8412    // `LmdbStorage::put` tests `exists` before it tests disk space, so a full
8413    // node still accepts a key it already holds. Checking possession first is
8414    // what keeps this pair of gates from declining work `put` would have
8415    // taken.
8416    if storage.exists(&key).unwrap_or(false) {
8417        debug!(
8418            "Skipping fetch for {}: already held locally",
8419            hex::encode(key)
8420        );
8421        return FetchOutcome {
8422            key,
8423            result: FetchResult::AlreadyHeld,
8424        };
8425    }
8426
8427    // Capacity is checked before the dial rather than after the bytes arrive.
8428    // `put` runs this same check on every write of a key it does not already
8429    // hold, so this reaches the same verdict `put` would reach *at this
8430    // instant*. It is not a guarantee about the later write: both answers can
8431    // change across the round trip. Space freed in between would have let a
8432    // post-download `put` succeed, so a refusal here can cost a fleeting
8433    // acquisition and one retry cycle of delay; space lost in between is why
8434    // the check inside `put` still has to stay.
8435    //
8436    // What it buys is that the refusal costs no bandwidth. Without it a
8437    // disk-full node pulls the whole chunk over the network first, and the
8438    // failure is then classified as the source's — no trust event, but the
8439    // worker walks to every remaining holder, and each re-uploads the same
8440    // chunk into the same full disk.
8441    if let Err(e) = storage.check_capacity() {
8442        debug!(
8443            "Skipping fetch for {}: local storage cannot accept a write: {e}",
8444            hex::encode(key)
8445        );
8446        return FetchOutcome {
8447            key,
8448            result: FetchResult::LocalWriteFailed,
8449        };
8450    }
8451
8452    let request = protocol::FetchRequest { key };
8453    let msg = ReplicationMessage {
8454        request_id: rand::thread_rng().gen::<u64>(),
8455        body: ReplicationMessageBody::FetchRequest(request),
8456    };
8457
8458    let encoded = match msg.encode() {
8459        Ok(data) => data,
8460        Err(e) => {
8461            warn!("Failed to encode fetch request: {e}");
8462            return FetchOutcome {
8463                key,
8464                result: FetchResult::SourceFailed,
8465            };
8466        }
8467    };
8468
8469    let result = p2p_node
8470        .send_request(
8471            &source,
8472            REPLICATION_PROTOCOL_ID,
8473            encoded,
8474            config.fetch_request_timeout,
8475        )
8476        .await;
8477
8478    match result {
8479        Ok(response) => {
8480            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8481                p2p_node
8482                    .report_trust_event(
8483                        &source,
8484                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8485                    )
8486                    .await;
8487                return FetchOutcome {
8488                    key,
8489                    result: FetchResult::SourceFailed,
8490                };
8491            };
8492
8493            match resp_msg.body {
8494                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8495                    key: resp_key,
8496                    data,
8497                }) => {
8498                    // Validate the response key matches the requested key.
8499                    // A malicious peer could serve valid data for a different
8500                    // key, passing integrity checks while the requested key
8501                    // is falsely marked as fetched.
8502                    if resp_key != key {
8503                        warn!(
8504                            "Fetch response key mismatch: requested {}, got {}",
8505                            hex::encode(key),
8506                            hex::encode(resp_key)
8507                        );
8508                        p2p_node
8509                            .report_trust_event(
8510                                &source,
8511                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8512                            )
8513                            .await;
8514                        return FetchOutcome {
8515                            key,
8516                            result: FetchResult::IntegrityFailed,
8517                        };
8518                    }
8519
8520                    // Enforce chunk size invariant on fetched data.
8521                    // Checked before the content-address hash to avoid
8522                    // hashing up to 10 MiB of oversized junk data.
8523                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8524                        warn!(
8525                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8526                            hex::encode(resp_key),
8527                            data.len(),
8528                            crate::ant_protocol::MAX_CHUNK_SIZE,
8529                        );
8530                        p2p_node
8531                            .report_trust_event(
8532                                &source,
8533                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8534                            )
8535                            .await;
8536                        return FetchOutcome {
8537                            key,
8538                            result: FetchResult::IntegrityFailed,
8539                        };
8540                    }
8541
8542                    // Content-address integrity check.
8543                    let computed = crate::client::compute_address(&data);
8544                    if computed != resp_key {
8545                        warn!(
8546                            "Fetched record integrity check failed: expected {}, got {}",
8547                            hex::encode(resp_key),
8548                            hex::encode(computed)
8549                        );
8550                        p2p_node
8551                            .report_trust_event(
8552                                &source,
8553                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8554                            )
8555                            .await;
8556                        return FetchOutcome {
8557                            key,
8558                            result: FetchResult::IntegrityFailed,
8559                        };
8560                    }
8561
8562                    // Responsibility can lapse during the network round-trip.
8563                    // The bandwidth is already spent; declining the write is
8564                    // what still avoids the disk write and the later
8565                    // fetch→store→prune churn. Edge flapping is dampened by
8566                    // the margin `storage_admission_width` adds over
8567                    // `close_group_size`.
8568                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8569                        debug!(
8570                            "Fetched {} but responsibility lapsed in transit; not storing",
8571                            hex::encode(key)
8572                        );
8573                        return FetchOutcome {
8574                            key,
8575                            result: FetchResult::NoLongerResponsible,
8576                        };
8577                    }
8578
8579                    if let Err(e) = storage.put(&resp_key, &data).await {
8580                        // The bytes arrived and passed the content-address
8581                        // check, so the source did its job; the failure is
8582                        // entirely local (disk-full, or an LMDB error). Any
8583                        // valid source must serve identical content, so trying
8584                        // the next one cannot cure a local error — it only
8585                        // re-downloads the same chunk into the same store.
8586                        warn!(
8587                            "Failed to store fetched record {}: {e}",
8588                            hex::encode(resp_key)
8589                        );
8590                        return FetchOutcome {
8591                            key,
8592                            result: FetchResult::LocalWriteFailed,
8593                        };
8594                    }
8595
8596                    FetchOutcome {
8597                        key,
8598                        result: FetchResult::Stored,
8599                    }
8600                }
8601                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8602                    ..
8603                }) => {
8604                    // This peer was selected as a fetch source because it
8605                    // recently answered `Present` during verification. A
8606                    // subsequent NotFound is evidence of a stale/false claim
8607                    // or chunk wiping, so penalize lightly and try another
8608                    // verified source.
8609                    warn!(
8610                        "Fetch: verified source {source} returned NotFound for {}",
8611                        hex::encode(key)
8612                    );
8613                    p2p_node
8614                        .report_trust_event(
8615                            &source,
8616                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8617                        )
8618                        .await;
8619                    FetchOutcome {
8620                        key,
8621                        result: FetchResult::SourceFailed,
8622                    }
8623                }
8624                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8625                    reason,
8626                    ..
8627                }) => {
8628                    warn!(
8629                        "Fetch: peer {source} returned error for {}: {reason}",
8630                        hex::encode(key)
8631                    );
8632                    p2p_node
8633                        .report_trust_event(
8634                            &source,
8635                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8636                        )
8637                        .await;
8638                    FetchOutcome {
8639                        key,
8640                        result: FetchResult::SourceFailed,
8641                    }
8642                }
8643                _ => {
8644                    // Unexpected message type — treat as malformed.
8645                    p2p_node
8646                        .report_trust_event(
8647                            &source,
8648                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8649                        )
8650                        .await;
8651                    FetchOutcome {
8652                        key,
8653                        result: FetchResult::SourceFailed,
8654                    }
8655                }
8656            }
8657        }
8658        Err(e) => {
8659            debug!("Fetch request to {source} failed: {e}");
8660            // No ApplicationFailure here — P2PNode::send_request() already
8661            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
8662            FetchOutcome {
8663                key,
8664                result: FetchResult::SourceFailed,
8665            }
8666        }
8667    }
8668}
8669
8670// ---------------------------------------------------------------------------
8671// Audit result handler
8672// ---------------------------------------------------------------------------
8673
8674/// Format the first confirmed-failed key as a 16-hex-char label.
8675///
8676/// Pairs with `challenged_peer` to form a stable cross-host correlation
8677/// handle in the audit-failure log line, e.g.
8678///
8679/// ```text
8680/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
8681/// ```
8682///
8683/// Falls back to `"0x"` when the list is empty so the log line never
8684/// contains a misleading default.
8685fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8686    confirmed_failed_keys.first().map_or_else(
8687        || "0x".to_string(),
8688        |k| format!("0x{}", hex::encode(&k[..8])),
8689    )
8690}
8691
8692/// Execute the side effects for a subtree storage-commitment audit failure.
8693///
8694/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
8695/// legitimately time out on slow or loaded honest peers, so it never touches the
8696/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
8697/// failures still penalise immediately and revoke holder credit.
8698async fn handle_subtree_failed_audit(
8699    challenged_peer: &PeerId,
8700    confirmed_failed_key_count: usize,
8701    reason: &AuditFailureReason,
8702    p2p_node: &Arc<P2PNode>,
8703    sync_state: &Arc<RwLock<NeighborSyncState>>,
8704    recent_provers: &Arc<RwLock<RecentProvers>>,
8705) {
8706    if matches!(reason, AuditFailureReason::Timeout) {
8707        debug!(
8708            "Audit timeout for {challenged_peer} fully graced \
8709             (subtree audit does not evict on timeout)"
8710        );
8711        return;
8712    }
8713
8714    // The caller already logged the rich failure line with reason + per-category
8715    // summary; avoid a redundant second error log here.
8716    let _ = confirmed_failed_key_count;
8717    {
8718        let mut state = sync_state.write().await;
8719        state.clear_active_bootstrap_claim(challenged_peer);
8720    }
8721    {
8722        let mut provers_guard = recent_provers.write().await;
8723        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8724    }
8725    p2p_node
8726        .report_trust_event(
8727            challenged_peer,
8728            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8729        )
8730        .await;
8731}
8732
8733/// Handle audit result: log findings and emit trust events.
8734async fn handle_subtree_audit_result(
8735    result: &AuditTickResult,
8736    p2p_node: &Arc<P2PNode>,
8737    sync_state: &Arc<RwLock<NeighborSyncState>>,
8738    recent_provers: &Arc<RwLock<RecentProvers>>,
8739    config: &ReplicationConfig,
8740) {
8741    match result {
8742        AuditTickResult::Passed {
8743            challenged_peer,
8744            keys_checked,
8745        } => {
8746            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8747            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8748            // Peer responded normally — clear the active bootstrap claim while
8749            // retaining history so a later claim is treated as repeated abuse.
8750            {
8751                let mut state = sync_state.write().await;
8752                state.clear_active_bootstrap_claim(challenged_peer);
8753            }
8754            p2p_node
8755                .report_trust_event(
8756                    challenged_peer,
8757                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8758                )
8759                .await;
8760        }
8761        AuditTickResult::Failed {
8762            evidence,
8763            no_response_class,
8764        } => {
8765            if let FailureEvidence::AuditFailure {
8766                challenged_peer,
8767                confirmed_failed_keys,
8768                summary,
8769                reason,
8770                ..
8771            } = evidence
8772            {
8773                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
8774                // Rich diagnostics (from main's audit-failure logging) + the
8775                // first-failed-key correlation handle.
8776                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8777                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8778                error!(
8779                    "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}",
8780                    audit_failure_class,
8781                    confirmed_failed_keys.len(),
8782                    summary.challenged_keys,
8783                    summary.absent_keys,
8784                    summary.digest_mismatch_keys,
8785                );
8786                // Route the side effects through the subtree-only failure path.
8787                // Responsible-chunk `AuditChallenge` handling intentionally uses
8788                // its own old immediate-penalty handler below.
8789                handle_subtree_failed_audit(
8790                    challenged_peer,
8791                    confirmed_failed_keys.len(),
8792                    reason,
8793                    p2p_node,
8794                    sync_state,
8795                    recent_provers,
8796                )
8797                .await;
8798            }
8799        }
8800        AuditTickResult::BootstrapClaim { peer } => {
8801            // Gap 6: BootstrapClaimAbuse grace period in audit path.
8802            // Separate state mutation from network I/O to avoid holding the
8803            // write lock across report_trust_event.
8804            let should_report = {
8805                let now = Instant::now();
8806                let mut state = sync_state.write().await;
8807                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8808                {
8809                    BootstrapClaimObservation::WithinGrace { .. } => {
8810                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8811                        false
8812                    }
8813                    BootstrapClaimObservation::PastGrace { first_seen } => {
8814                        warn!(
8815                            "Audit: peer {peer} claiming bootstrap past grace period \
8816                             ({:?} > {:?}), reporting abuse",
8817                            now.duration_since(first_seen),
8818                            config.bootstrap_claim_grace_period,
8819                        );
8820                        true
8821                    }
8822                    BootstrapClaimObservation::Repeated { first_seen } => {
8823                        warn!(
8824                            "Audit: peer {peer} repeated bootstrap claim after previously \
8825                             stopping; first claim was {:?} ago, reporting abuse",
8826                            now.duration_since(first_seen),
8827                        );
8828                        true
8829                    }
8830                }
8831            };
8832            if should_report {
8833                p2p_node
8834                    .report_trust_event(
8835                        peer,
8836                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8837                    )
8838                    .await;
8839            }
8840        }
8841        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8842    }
8843}
8844
8845/// Whether a confirmed audit failure with this reason clears the peer's active
8846/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
8847/// bootstrapping); every confirmed storage-integrity reason does.
8848///
8849/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
8850/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
8851/// still reports the normal audit trust penalty.
8852fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
8853    !matches!(reason, AuditFailureReason::Timeout)
8854}
8855
8856/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
8857/// events and manage bootstrap-claim state.
8858///
8859/// This is intentionally separate from the subtree audit result handler. A
8860/// responsible-chunk `AuditChallenge` `Failed` result reports
8861/// `ApplicationFailure` immediately for every reason, including `Timeout`,
8862/// restoring the pre-ADR-0002 behaviour.
8863#[allow(clippy::too_many_lines)]
8864async fn handle_audit_result(
8865    result: &AuditTickResult,
8866    p2p_node: &Arc<P2PNode>,
8867    sync_state: &Arc<RwLock<NeighborSyncState>>,
8868    config: &ReplicationConfig,
8869) {
8870    match result {
8871        AuditTickResult::Passed {
8872            challenged_peer,
8873            keys_checked,
8874        } => {
8875            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
8876            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8877            {
8878                let mut state = sync_state.write().await;
8879                state.clear_active_bootstrap_claim(challenged_peer);
8880            }
8881            p2p_node
8882                .report_trust_event(
8883                    challenged_peer,
8884                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8885                )
8886                .await;
8887        }
8888        AuditTickResult::Failed {
8889            evidence,
8890            no_response_class,
8891        } => {
8892            if let FailureEvidence::AuditFailure {
8893                challenged_peer,
8894                confirmed_failed_keys,
8895                summary,
8896                reason,
8897                ..
8898            } = evidence
8899            {
8900                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
8901                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8902                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8903                error!(
8904                    "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}",
8905                    audit_failure_class,
8906                    confirmed_failed_keys.len(),
8907                    summary.challenged_keys,
8908                    summary.absent_keys,
8909                    summary.digest_mismatch_keys,
8910                );
8911                if audit_failure_clears_bootstrap_claim(reason) {
8912                    let mut state = sync_state.write().await;
8913                    state.clear_active_bootstrap_claim(challenged_peer);
8914                } else {
8915                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
8916                }
8917                p2p_node
8918                    .report_trust_event(
8919                        challenged_peer,
8920                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8921                    )
8922                    .await;
8923            }
8924        }
8925        AuditTickResult::BootstrapClaim { peer } => {
8926            let should_report = {
8927                let now = Instant::now();
8928                let mut state = sync_state.write().await;
8929                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8930                {
8931                    BootstrapClaimObservation::WithinGrace { .. } => {
8932                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8933                        false
8934                    }
8935                    BootstrapClaimObservation::PastGrace { first_seen } => {
8936                        warn!(
8937                            "Audit: peer {peer} claiming bootstrap past grace period \
8938                             ({:?} > {:?}), reporting abuse",
8939                            now.duration_since(first_seen),
8940                            config.bootstrap_claim_grace_period,
8941                        );
8942                        true
8943                    }
8944                    BootstrapClaimObservation::Repeated { first_seen } => {
8945                        warn!(
8946                            "Audit: peer {peer} repeated bootstrap claim after previously \
8947                             stopping; first claim was {:?} ago, reporting abuse",
8948                            now.duration_since(first_seen),
8949                        );
8950                        true
8951                    }
8952                }
8953            };
8954            if should_report {
8955                p2p_node
8956                    .report_trust_event(
8957                        peer,
8958                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8959                    )
8960                    .await;
8961            }
8962        }
8963        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8964    }
8965}
8966
8967/// Whether a confirmed audit failure with this reason should revoke the
8968/// peer's `recent_provers` holder credit immediately (v12 §6).
8969///
8970/// `true` for any reason where the peer actually answered (or admitted
8971/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
8972/// bytes for committed key"), `MalformedResponse` — these prove the
8973/// peer no longer holds what it committed to, so it must not keep
8974/// holder credit for the proof TTL. `false` for `Timeout`: a single
8975/// dropped packet must not strip an honest peer; the 40-min TTL is the
8976/// deliberate liveness cushion there.
8977fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
8978    !matches!(reason, AuditFailureReason::Timeout)
8979}
8980
8981/// Apply the holder-credit revocation decision for a confirmed audit
8982/// failure. Pure over `RecentProvers` so the handler wiring is unit-
8983/// testable without a live `P2PNode`: the production `Failed` arm of
8984/// `handle_subtree_audit_result` calls exactly this.
8985fn apply_audit_failure_credit_revocation(
8986    provers: &mut RecentProvers,
8987    challenged_peer: &PeerId,
8988    reason: &AuditFailureReason,
8989) {
8990    if audit_failure_revokes_holder_credit(reason) {
8991        provers.forget_peer(challenged_peer);
8992    }
8993}
8994
8995// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
8996
8997// ---------------------------------------------------------------------------
8998// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
8999// ---------------------------------------------------------------------------
9000
9001/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9002/// message handler passes one value instead of a long argument list; all
9003/// fields are cheap `Arc` clones.
9004#[derive(Clone)]
9005struct GossipAuditTrigger {
9006    p2p_node: Arc<P2PNode>,
9007    config: Arc<ReplicationConfig>,
9008    recent_provers: Arc<RwLock<RecentProvers>>,
9009    sync_state: Arc<RwLock<NeighborSyncState>>,
9010    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9011    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9012    /// only when a real audit is about to be sent — never by a losing lottery
9013    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9014    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9015    detached_task_tracker: TaskTracker,
9016    /// Gossip-private lottery attempt window: stamped on every roll (win or
9017    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9018    /// The first-audit scheduler never reads this map.
9019    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9020}
9021
9022/// What a gossip ingest yields for the audit trigger: the commitment hash to
9023/// pin and the `key_count` needed to size the response deadline from the actual
9024/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9025/// or not) so a stable-keyset node stays auditable — not just on its first
9026/// commitment.
9027#[derive(Debug, Clone, Copy)]
9028struct AuditTarget {
9029    pin_hash: [u8; 32],
9030    key_count: u32,
9031}
9032
9033/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9034/// verifier's cross-check so it can receive a **deterministic first audit**.
9035///
9036/// Sent from the verifier to the replication engine's first-audit drainer. The
9037/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9038/// audits of the same peer revert to the gossip lottery), orders most-recently-
9039/// monetized first, and runs the same `run_subtree_audit` under the same
9040/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9041#[derive(Debug, Clone, Copy)]
9042pub struct MonetizedPinEvent {
9043    /// The peer whose commitment backed the payment.
9044    pub peer: PeerId,
9045    /// The pinned commitment hash.
9046    pub pin: [u8; 32],
9047    /// The committed key count (sizes the audit deadline).
9048    pub key_count: u32,
9049    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9050    /// pin whose quote is older than the answerability window (ADR-0004 A1
9051    /// guardrail A): with grace removed, challenging an aged-out pin would
9052    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9053    pub quote_ts: SystemTime,
9054}
9055
9056/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9057/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9058/// stamps `now`), `false` if it was audited within
9059/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9060/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9061/// without a live node: a burst of gossips from one peer yields at most one
9062/// `true` per cooldown window.
9063fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9064    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9065    let known = match map.get(peer) {
9066        Some(&last) => {
9067            if now.saturating_duration_since(last) < cooldown {
9068                return false;
9069            }
9070            true
9071        }
9072        None => false,
9073    };
9074    // Bound the map under churn like its siblings (drop the oldest stamp) before
9075    // admitting a brand-new peer.
9076    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9077        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9078            map.remove(&victim);
9079        }
9080    }
9081    map.insert(*peer, now);
9082    true
9083}
9084
9085/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9086/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9087/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9088/// already covered; the authoritative check-and-stamp still runs at promotion,
9089/// so this is only an optimization and never the security boundary.
9090fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9091    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9092    map.get(peer).map_or(true, |&last| {
9093        now.saturating_duration_since(last) >= cooldown
9094    })
9095}
9096
9097/// The gossip-audit launch decision in ONE place so the ordering is shared
9098/// between production and its test (ADR-0002 "occasional surprise exams").
9099///
9100/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9101/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9102/// sampled first, a gossip flood would re-roll it on every message until one
9103/// won, multiplying audits, so each peer gets at most one lottery roll per
9104/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9105/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9106/// also consults — only after a WIN, i.e. only when a real audit is about to be
9107/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9108/// wire, so it must not defer a paid first audit (repeatable losses could
9109/// otherwise hold a monetized pin past its answerability window). Production
9110/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9111/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9112/// here fails the test.
9113fn audit_launch_decision(
9114    attempts: &mut HashMap<PeerId, Instant>,
9115    launched: &mut HashMap<PeerId, Instant>,
9116    peer: &PeerId,
9117    now: Instant,
9118    lottery_wins: bool,
9119) -> bool {
9120    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9121    // window even on a loss; private to the gossip path).
9122    if !cooldown_allows_audit(attempts, peer, now) {
9123        return false;
9124    }
9125    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9126    // shared.
9127    if !lottery_wins {
9128        return false;
9129    }
9130    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9131    // either path still suppresses this launch), stamped only on launch.
9132    cooldown_allows_audit(launched, peer, now)
9133}
9134
9135/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9136/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9137/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9138/// handling is never blocked on a network round-trip.
9139async fn maybe_trigger_gossip_audit(
9140    trigger: &GossipAuditTrigger,
9141    peer: &PeerId,
9142    target: AuditTarget,
9143) {
9144    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9145    // lives in the pure `audit_launch_decision` so the ordering is shared with
9146    // its test. Sample the lottery here, then let the helper apply the gates.
9147    let now = Instant::now();
9148    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9149    {
9150        // Lock order: attempts before the shared cooldown; this is the only
9151        // place both are held together.
9152        let mut attempts = trigger.lottery_attempts.write().await;
9153        let mut launched = trigger.cooldown.write().await;
9154        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9155            return;
9156        }
9157    }
9158
9159    let detached_task_tracker = trigger.detached_task_tracker.clone();
9160    let trigger = trigger.clone();
9161    let peer = *peer;
9162    detached_task_tracker.spawn(async move {
9163        let credit = storage_commitment_audit::AuditCredit {
9164            recent_provers: &trigger.recent_provers,
9165        };
9166        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9167            &trigger.p2p_node,
9168            &trigger.config,
9169            &peer,
9170            target.pin_hash,
9171            target.key_count,
9172            Some(&credit),
9173            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9174        )
9175        .await;
9176        handle_subtree_audit_result(
9177            &result,
9178            &trigger.p2p_node,
9179            &trigger.sync_state,
9180            &trigger.recent_provers,
9181            &trigger.config,
9182        )
9183        .await;
9184    });
9185}
9186
9187/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9188///
9189/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9190/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9191/// of its last attempt. Holds one write lock across the decision so two
9192/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9193/// caller's expensive verify so a slow/failed verify still rate-limits the next
9194/// message. Bounds the map under a flood of distinct peer ids.
9195async fn sig_verify_rate_limit_ok(
9196    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9197    source: &PeerId,
9198    now: Instant,
9199) -> bool {
9200    let mut attempts = sig_verify_attempts.write().await;
9201    if let Some(&last) = attempts.get(source) {
9202        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9203            return false;
9204        }
9205    }
9206    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9207        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9208            attempts.remove(&victim);
9209        }
9210    }
9211    attempts.insert(*source, now);
9212    true
9213}
9214
9215/// Verify + store an inbound commitment from a gossip peer.
9216///
9217/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9218/// the bootstrap-sync loop. Drops the commitment unless all five gates
9219/// pass:
9220///   1. `source` is in our DHT routing table (sybil/churn cap).
9221///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9222///      binding to the authenticated transport peer).
9223///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9224///      (the embedded pubkey actually belongs to the claimed identity —
9225///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9226///   4. `verify_commitment_signature(commitment)` succeeds against the
9227///      embedded public key. The signed payload binds the pubkey, so an
9228///      adversary cannot swap the key while keeping the body.
9229///   5. The cache has room or this is an update for an existing entry
9230///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9231///
9232/// On all-pass, the commitment is stored as the auditor's per-peer
9233/// "last known commitment" for use as `expected_commitment_hash` in
9234/// future audits.
9235///
9236/// Failures (no commitment / mismatched peer id / bad signature) are
9237/// silent drops — gossip is best-effort and a malformed commitment from
9238/// one peer should not affect anything else.
9239///
9240/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9241/// or not its root changed), so the caller can run a probabilistic,
9242/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9243/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9244/// being auditable, so it cannot pass one audit and then delete data while
9245/// re-gossiping the same root forever. The cooldown + probability bound the
9246/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9247/// gate) or there is nothing to pin.
9248///
9249/// Handle a capable peer gossiping `None` (a commitment downgrade).
9250///
9251/// A capable peer that previously gossiped a commitment but now gossips `None`
9252/// is trying to drop off the audit path. Within the answerability window we keep
9253/// the cached commitment pinned AND return it as an audit target so this gossip
9254/// still schedules a subtree audit against the peer's last known commitment — if
9255/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9256/// the trigger MUST fire here or the downgrade is never re-challenged).
9257///
9258/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9259/// honours for its own retired commitment: once that elapses since we last
9260/// received the peer's commitment, an honest peer has legitimately retired that
9261/// root (its responder side `retire_current`s and lets it age out) and can no
9262/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9263/// failure, so we then forget the cached commitment (keeping the sticky
9264/// `commitment_capable` bit) and stop pinning it.
9265async fn handle_commitment_downgrade(
9266    source: &PeerId,
9267    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9268) -> Option<AuditTarget> {
9269    let now = Instant::now();
9270    let cached = {
9271        let map = last_commitment_by_peer.read().await;
9272        map.get(source).and_then(|rec| {
9273            if !rec.commitment_capable {
9274                return None;
9275            }
9276            let last = rec.last_commitment()?;
9277            let pin = rec.commitment_hash()?;
9278            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9279            Some((pin, last.key_count, fresh))
9280        })
9281    };
9282    match cached {
9283        Some((pin, key_count, true)) => {
9284            warn!(
9285                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9286                 (downgrade attempt); auditing against its last cached commitment"
9287            );
9288            Some(AuditTarget {
9289                pin_hash: pin,
9290                key_count,
9291            })
9292        }
9293        Some((_, _, false)) => {
9294            // Cached commitment has aged past the answerability window — forget
9295            // it so we stop pinning a root the peer is no longer obliged to
9296            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9297            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9298            // from this peer may have refreshed `received_at` in the gap between
9299            // our read and write locks; if so, leave its fresh commitment intact.
9300            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9301                let still_stale =
9302                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9303                if still_stale {
9304                    rec.clear_commitment();
9305                    debug!(
9306                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9307                         commitment aged past the answerability TTL; forgetting it"
9308                    );
9309                }
9310            }
9311            None
9312        }
9313        None => None,
9314    }
9315}
9316
9317async fn ingest_peer_commitment(
9318    source: &PeerId,
9319    commitment: Option<&StorageCommitment>,
9320    p2p_node: &Arc<P2PNode>,
9321    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9322    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9323    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9324) -> Option<AuditTarget> {
9325    let Some(c) = commitment else {
9326        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9327    };
9328    // RT-membership gate: only accept commitments from peers in our
9329    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9330    // populate the cache, which closes the hole where a flood of
9331    // off-RT identities could fill the cap and evict honest
9332    // peers. The neighbor-sync request handler applies the same gate
9333    // before admitting inbound replication hints (see neighbor_sync.rs
9334    // `sender_in_rt`); we mirror that policy here for the commitment
9335    // piggyback.
9336    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9337        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9338        return None;
9339    }
9340    // Peer-id binding: the commitment's claimed sender must match the
9341    // authenticated transport peer (`source`). Defeats relay/replay
9342    // and also pins which embedded public key we are about to verify
9343    // against — the verify itself trusts the embedded key, so the
9344    // peer-id binding is the link to a real identity.
9345    if &c.sender_peer_id != source.as_bytes() {
9346        warn!(
9347            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9348             (dropped, possible relay attempt)"
9349        );
9350        return None;
9351    }
9352    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9353    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9354    // with a throwaway key they own and lie about which identity it
9355    // belongs to (the embedded-key signature would verify trivially).
9356    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9357    if derived_peer_id != c.sender_peer_id {
9358        warn!(
9359            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9360             {source} (dropped, throwaway-key attack)"
9361        );
9362        return None;
9363    }
9364    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9365    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9366    // sybil/RT-membership-bypassing peer that flooded valid-looking
9367    // gossip would otherwise burn CPU on every message. The rate
9368    // limit is checked AFTER cheap structural gates (RT, peer-id
9369    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9370    //
9371    // Tracked in `sig_verify_attempts` (separate from
9372    // last_commitment_by_peer) so EVERY attempt — successful or not —
9373    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9374    // would skip the cap for peers we've never successfully verified,
9375    // letting a flood of invalid-but-structurally-plausible gossips
9376    // burn CPU.
9377    let now = Instant::now();
9378    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9379        debug!(
9380            "ingest_peer_commitment: rate-limited sig verify from {source} \
9381             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9382        );
9383        return None;
9384    }
9385    // Signature verify, using the public key embedded in the commitment
9386    // itself. The pubkey is bound by the signature payload (see
9387    // commitment_signed_payload) so an adversary cannot keep the body
9388    // and swap the key to one they hold the secret for.
9389    if !crate::replication::commitment::verify_commitment_signature(c) {
9390        warn!(
9391            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9392             (dropped, forged commitment)"
9393        );
9394        return None;
9395    }
9396    // The new commitment's hash, used to store and to pin for the audit target.
9397    let new_hash = commitment_hash(c);
9398    let mut map = last_commitment_by_peer.write().await;
9399    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9400    // evict an arbitrary existing entry to make room. Updates for peers
9401    // already in the map are always accepted (they replace, not grow).
9402    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9403        // Drop one arbitrary entry. HashMap iter order is random which
9404        // is fine — over time PeerRemoved cleanup keeps the working set
9405        // anchored on the real RT membership; this cap only fires under
9406        // active flooding attempts.
9407        if let Some(victim) = map.keys().next().copied() {
9408            map.remove(&victim);
9409            warn!(
9410                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9411                 evicted {victim} to admit {source}"
9412            );
9413        }
9414    }
9415    // Preserve sticky commitment_capable across updates — once true,
9416    // always true. New entries start with capable = true (we just
9417    // verified a valid commitment from this peer).
9418    map.entry(*source)
9419        .and_modify(|r| {
9420            // set_commitment refreshes the cached hash (§13) alongside the
9421            // commitment + received_at so they never drift.
9422            r.set_commitment(c.clone(), now);
9423            r.last_sig_verify_at = now;
9424            r.commitment_capable = true; // sticky-redundant but explicit
9425        })
9426        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9427    drop(map);
9428    // Record the sticky "ever v12-capable" bit in a set independent of
9429    // `last_commitment_by_peer` (whose entries can be evicted by
9430    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9431    // shield and the §6 holder-eligibility closure consult to decide
9432    // whether the peer is expected to speak v12.
9433    //
9434    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9435    // identity-rotation attacks: once full, new entries are refused.
9436    // Refusal degrades over-cap peers to the behaviour before this set
9437    // existed (treated as legacy on rejoin), which is not a security
9438    // regression and preserves the historic set stable.
9439    {
9440        let mut set = ever_capable_peers.write().await;
9441        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9442            set.insert(*source);
9443        } else {
9444            warn!(
9445                "ingest_peer_commitment: ever_capable_peers at cap \
9446                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9447            );
9448        }
9449    }
9450    // Return an audit target for EVERY valid stored commitment (changed or
9451    // not), so the caller's cooldown+probability-gated trigger keeps a
9452    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9453    // failure (new_hash == None, unreachable for a real commitment) yields None.
9454    new_hash.map(|pin_hash| AuditTarget {
9455        pin_hash,
9456        key_count: c.key_count,
9457    })
9458}
9459
9460// ---------------------------------------------------------------------------
9461// Storage-bound audit (v12) — responder commitment rotation
9462// ---------------------------------------------------------------------------
9463
9464/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9465/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9466/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9467async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9468    let bytes = match tokio::fs::read(path).await {
9469        Ok(b) => b,
9470        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9471            debug!(
9472                "Commitment retention: no snapshot at {} (fresh start)",
9473                path.display()
9474            );
9475            return;
9476        }
9477        Err(e) => {
9478            warn!(
9479                "Commitment retention: failed to read {}: {e}",
9480                path.display()
9481            );
9482            return;
9483        }
9484    };
9485    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9486        state.restore(&persisted);
9487        info!(
9488            "Commitment retention: reloaded {} slot(s) from {}",
9489            state.retained_slot_count(),
9490            path.display()
9491        );
9492    } else {
9493        warn!(
9494            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9495            path.display()
9496        );
9497    }
9498}
9499
9500/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9501/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9502/// needless disk writes on idle nodes. On success updates `last` to the bytes
9503/// written; on a serialization/write error the existing on-disk snapshot is left
9504/// intact (never truncated).
9505async fn persist_retention_if_changed(
9506    state: &ResponderCommitmentState,
9507    path: &Path,
9508    last: &mut Option<Vec<u8>>,
9509) {
9510    let Some(bytes) = state.snapshot().to_bytes() else {
9511        warn!("Commitment retention: serialization failed; keeping previous snapshot");
9512        return;
9513    };
9514    if last.as_deref() == Some(bytes.as_slice()) {
9515        return;
9516    }
9517    if write_retention_atomic(path, bytes.clone()).await {
9518        *last = Some(bytes);
9519    }
9520}
9521
9522/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9523/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9524/// success. Only the retention-persist loop writes this path, so a fixed temp
9525/// name is safe.
9526async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9527    let path = path.to_path_buf();
9528    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9529        let tmp = path.with_extension("tmp");
9530        std::fs::write(&tmp, &bytes)?;
9531        std::fs::File::open(&tmp)?.sync_all()?;
9532        std::fs::rename(&tmp, &path)?;
9533        // Fsync the directory so the rename (the durable-commit point) is not
9534        // lost on a crash right after it. An empty parent (relative filename)
9535        // means the current directory.
9536        let dir = path
9537            .parent()
9538            .filter(|p| !p.as_os_str().is_empty())
9539            .unwrap_or_else(|| Path::new("."));
9540        std::fs::File::open(dir)?.sync_all()?;
9541        Ok(())
9542    })
9543    .await;
9544    match res {
9545        Ok(Ok(())) => true,
9546        Ok(Err(e)) => {
9547            warn!("Commitment retention: persist failed: {e}");
9548            false
9549        }
9550        Err(e) => {
9551            warn!("Commitment retention: persist task join failed: {e}");
9552            false
9553        }
9554    }
9555}
9556
9557/// Read the current LMDB key set, build + sign a fresh
9558/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9559/// The prior `current` is demoted to `previous`; the prior `previous` is
9560/// dropped (per `ResponderCommitmentState::rotate`).
9561///
9562/// For content-addressed chunks (Autonomi's chunk store), `address ==
9563/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9564/// re-read each chunk's bytes to compute the leaf hash.
9565///
9566/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9567/// rotate. The auditor side handles "no commitment for this peer" by
9568/// falling back to the legacy plain-digest audit path.
9569async fn rebuild_and_rotate_commitment(
9570    storage: &Arc<LmdbStorage>,
9571    identity: &Arc<NodeIdentity>,
9572    state: &Arc<ResponderCommitmentState>,
9573    p2p: &Arc<P2PNode>,
9574    config: &Arc<ReplicationConfig>,
9575) -> Result<()> {
9576    let stored_keys = storage
9577        .all_keys()
9578        .await
9579        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9580
9581    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9582    // everything currently on disk ("hold"). This is the half of the retention
9583    // contract that lets out-of-range chunks age out: a key that has left our
9584    // close group is excluded from the NEXT commitment, so once its last gossip
9585    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9586    // set, `ResponderCommitmentState::is_held` goes false,
9587    // and the pruner (which until then vetoes its deletion) reclaims it. Without
9588    // this filter the pruner's reprieve would keep re-committing stale keys
9589    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9590    // re-committed and re-gossiped every rotation — a permanent pin).
9591    let storage_empty = stored_keys.is_empty();
9592    let self_id = *p2p.peer_id();
9593    let mut keys = Vec::with_capacity(stored_keys.len());
9594    for k in stored_keys {
9595        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9596            keys.push(k);
9597        }
9598    }
9599
9600    if keys.is_empty() {
9601        if storage_empty {
9602            // Storage is genuinely empty — there is nothing to answer for, so
9603            // drop the previously advertised commitment immediately. Keeping it
9604            // would leave remote auditors pinning a hash we can never satisfy
9605            // again (the bytes are gone).
9606            if state.retained_slot_count() > 0 {
9607                debug!("Commitment rotation: storage empty, clearing retained slots");
9608                state.clear_all();
9609            }
9610            return Ok(());
9611        }
9612        // Bytes are still on disk but no key is currently in range. We must NOT
9613        // clear retention here: a peer may still be pinning a root we gossiped
9614        // moments ago and could demand its bytes in a round-2 challenge, which
9615        // we can still answer (the bytes are present). But we must STOP
9616        // advertising the stale commitment: retire it so `current()` returns
9617        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
9618        // The retired slot then ages out by its gossip-answerability TTL while
9619        // remaining answerable for in-flight pins until then. Once it ages out,
9620        // `is_held` flips false and the pruner reclaims the now-uncommitted,
9621        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
9622        // pointing at the stale root, which the gossip loop would keep
9623        // re-stamping — pinning its keys forever.)
9624        debug!(
9625            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9626             (stays answerable until its gossip TTL lapses, bytes still on disk)"
9627        );
9628        state.retire_current();
9629        return Ok(());
9630    }
9631
9632    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
9633    // to more than the protocol limit; auditor would reject the
9634    // commitment otherwise).
9635    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9636    if keys.len() > cap {
9637        warn!(
9638            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9639             truncating — investigate as this likely means a misconfiguration",
9640            keys.len(),
9641            cap
9642        );
9643    }
9644
9645    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
9646    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
9647    // full chunk re-read per rotation.
9648    //
9649    // Consequence to be precise about: because the leaf is `(key, key)`,
9650    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
9651    // commitment therefore binds "which keys I claim to hold"; it does NOT
9652    // by itself prove byte possession. Byte possession is enforced by the
9653    // round-2 slice audit: a Bao verified slice decoded against the chunk
9654    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
9655    // nonce, so a responder that holds the key list but dropped the bytes
9656    // cannot answer. This is sound ONLY while keys are content addresses;
9657    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
9658    // (`evaluate_subtree_structure`), so a non-content-addressed
9659    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
9660    // earn credit for `key`. If this module is ever reused for
9661    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
9662    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
9663    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9664
9665    // No-op-rotation guard: compute just the Merkle root from `entries`
9666    // and compare against the currently-advertised commitment's root.
9667    // If they match, the key set is unchanged and a new rotation would
9668    // only swap a randomized ML-DSA signature for a fresh one — same
9669    // content, different commitment_hash. That invalidates every
9670    // outstanding `recent_provers` credit on this node across the
9671    // close group with no security benefit, breaking steady-state
9672    // quorum liveness on large nodes that can't re-audit every key
9673    // every rotation interval. Skip the rotation entirely when the
9674    // tree is unchanged.
9675    // Build the tree ONCE here (moving `entries`): it serves both the no-op
9676    // root check below and, if we proceed, the signed commitment via
9677    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
9678    // inside `BuiltCommitment::build`).
9679    let candidate_tree = commitment::MerkleTree::build(entries)
9680        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9681    let candidate_root = candidate_tree.root();
9682    if let Some(current) = state.current() {
9683        if current.commitment().root == candidate_root {
9684            debug!(
9685                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9686                hex::encode(candidate_root)
9687            );
9688            // Even though we skip re-signing (to avoid invalidating holder
9689            // credit), retention must still advance on the wall clock: a
9690            // previously-gossiped commitment that holds a now-out-of-range key
9691            // must be able to age out of the answerability window even when the
9692            // committed key set is frozen here for many rotations. Without this,
9693            // the no-op guard would pin a stale slot — and its key — forever.
9694            state.age_out();
9695            return Ok(());
9696        }
9697    }
9698
9699    let sk_bytes = identity.secret_key_bytes().to_vec();
9700    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9701        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9702    let pk_bytes = identity.public_key().as_bytes().to_vec();
9703    let peer_id_bytes = *p2p.peer_id().as_bytes();
9704
9705    let built = commitment_state::BuiltCommitment::build_from_tree(
9706        candidate_tree,
9707        &peer_id_bytes,
9708        &sk,
9709        &pk_bytes,
9710    )
9711    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9712
9713    let hash = hex::encode(built.hash());
9714    let key_count = built.commitment().key_count;
9715    state.rotate(built);
9716    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9717    Ok(())
9718}
9719
9720#[cfg(test)]
9721#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9722mod tests {
9723    use super::*;
9724    use super::{
9725        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9726        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9727        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9728        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9729        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9730        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9731        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9732        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9733    };
9734    use crate::payment::VerificationContext;
9735    use crate::replication::audit::AuditTickResult;
9736    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9737    use crate::replication::recent_provers::RecentProvers;
9738    use crate::replication::types::{AuditFailureReason, FailureEvidence};
9739    use lru::LruCache;
9740    use saorsa_core::identity::PeerId;
9741    use std::collections::HashMap;
9742    use std::num::NonZeroUsize;
9743    use std::sync::atomic::Ordering;
9744    use std::sync::Arc;
9745    use std::time::Duration;
9746    use std::time::Instant;
9747    use std::time::SystemTime;
9748
9749    #[test]
9750    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9751        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9752            assert_eq!(match_replication_protocol(id), Some((id, false)));
9753            assert_eq!(
9754                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
9755                Some((id, true))
9756            );
9757        }
9758        assert_eq!(
9759            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
9760            None
9761        );
9762        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
9763        assert_eq!(match_replication_protocol(RR_PREFIX), None);
9764    }
9765
9766    #[test]
9767    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
9768        use crate::replication::protocol::{
9769            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
9770            SubtreeSliceChallenge,
9771        };
9772
9773        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
9774            challenge_id: 1,
9775            nonce: [0u8; 32],
9776            challenged_peer_id: [0u8; 32],
9777            expected_commitment_hash: [0u8; 32],
9778            openings: vec![],
9779        });
9780        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
9781            challenge_id: 1,
9782            nonce: [0u8; 32],
9783            challenged_peer_id: [0u8; 32],
9784            keys: vec![[0u8; 32]],
9785        });
9786        let digest_response =
9787            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
9788        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
9789            key: [0u8; 32],
9790            data: vec![],
9791            proof_of_payment: vec![],
9792        });
9793
9794        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
9795        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
9796
9797        for body in [&digest_challenge, &digest_response, &core] {
9798            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
9799            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
9800        }
9801
9802        for body in [&subtree, &digest_challenge, &digest_response, &core] {
9803            assert!(body_matches_protocol(body, response_protocol_for(body)));
9804        }
9805    }
9806
9807    fn test_peer(b: u8) -> PeerId {
9808        let mut bytes = [0u8; 32];
9809        bytes[0] = b;
9810        PeerId::from_bytes(bytes)
9811    }
9812
9813    /// A structurally valid offer for `data`: real content address, a proof of
9814    /// the minimum accepted size, distinguished by `proof_marker` so a test can
9815    /// tell whose proof came back out of the queue.
9816    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
9817        protocol::FreshReplicationOffer {
9818            key: crate::client::compute_address(&data),
9819            data,
9820            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
9821        }
9822    }
9823
9824    fn admit_test_offer(
9825        in_flight: &FreshOfferInFlight,
9826        offer: protocol::FreshReplicationOffer,
9827        source: PeerId,
9828    ) -> FreshOfferAdmission {
9829        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
9830    }
9831
9832    #[test]
9833    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
9834        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9835        let data = vec![0x11u8; 64];
9836
9837        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
9838        let FreshOfferAdmission::Opened(entry) = opened else {
9839            panic!("first offer for a key should open the entry")
9840        };
9841
9842        // A second sender contributes its proof instead of being turned away:
9843        // its bytes are provably the same, so only the proof is worth keeping.
9844        assert!(
9845            matches!(
9846                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
9847                FreshOfferAdmission::Joined
9848            ),
9849            "a duplicate from a new source should queue its proof"
9850        );
9851        // The same peer twice is not extra evidence, just extra work.
9852        assert!(
9853            matches!(
9854                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
9855                FreshOfferAdmission::DuplicateSource
9856            ),
9857            "one source should hold at most one queued proof per key"
9858        );
9859
9860        // An entry that outlived its handler would bar the key forever.
9861        drop(entry);
9862        assert!(
9863            matches!(
9864                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
9865                FreshOfferAdmission::Opened(_)
9866            ),
9867            "a released key should be openable again"
9868        );
9869    }
9870
9871    #[test]
9872    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
9873        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9874
9875        // A node only receives offers for keys close to its own ID, so accepted
9876        // keys share a long prefix. Any prefix-derived shard index would have
9877        // funnelled these two onto one lock and serialized them.
9878        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
9879        assert!(
9880            matches!(
9881                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
9882                FreshOfferAdmission::Opened(_)
9883            ),
9884            "distinct keys should never block each other"
9885        );
9886    }
9887
9888    /// The regression that motivated queueing proofs at all.
9889    ///
9890    /// A sender whose proof does not verify must cost the network its own
9891    /// attempt and nothing more. Refusing every later offer outright made the
9892    /// first arrival the only arrival, so one bad proof lost the record — and
9893    /// the delayed possession check then charged that absence to this node.
9894    #[test]
9895    fn a_failing_proof_hands_the_key_to_the_next_sender() {
9896        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9897        let data = vec![0x5Au8; 128];
9898        let forger = test_peer(0xF0);
9899        let genuine = test_peer(0x0F);
9900
9901        let FreshOfferAdmission::Opened(mut entry) =
9902            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
9903        else {
9904            panic!("the first offer should open the entry");
9905        };
9906        assert!(
9907            matches!(
9908                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
9909                FreshOfferAdmission::Joined
9910            ),
9911            "the genuine sender must not be turned away by the forger"
9912        );
9913
9914        let first = entry
9915            .next_attempt()
9916            .expect("the opener's proof comes first");
9917        assert_eq!(first.source, forger);
9918
9919        // Treat the forger's proof as failed: the next one is still reachable,
9920        // and it is tried against the bytes already held rather than a refetch.
9921        let second = entry
9922            .next_attempt()
9923            .expect("a failed proof must not consume the key");
9924        assert_eq!(second.source, genuine);
9925        assert_eq!(
9926            second.proof_of_payment,
9927            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
9928        );
9929        assert_eq!(
9930            entry.data(),
9931            data.as_slice(),
9932            "every proof is tried against the one copy of the bytes"
9933        );
9934
9935        // Draining the queue releases the key rather than stranding it.
9936        assert!(entry.next_attempt().is_none());
9937        assert!(
9938            matches!(
9939                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
9940                FreshOfferAdmission::Opened(_)
9941            ),
9942            "an exhausted entry should release its key"
9943        );
9944    }
9945
9946    /// The cap has to be a lifetime budget, not a queue depth.
9947    ///
9948    /// The handler pops a proof before verifying it, so gating admission on the
9949    /// *instantaneous* queue length lets a fresh source refill the slot that pop
9950    /// just freed. Each refill is another on-chain payment verification, run
9951    /// sequentially while the entry holds its admission permit and a worker
9952    /// slot, so a stream of distinct sources could keep one key's handler — and
9953    /// one of only four workers — busy indefinitely.
9954    #[test]
9955    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
9956        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9957        let data = vec![0x3Du8; 32];
9958
9959        let FreshOfferAdmission::Opened(mut entry) =
9960            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
9961        else {
9962            panic!("the first offer should open the entry")
9963        };
9964
9965        // Drive pop-then-admit with a fresh source every time, exactly as a
9966        // sybil stream would. The budget must be spent by admissions, not
9967        // returned by pops.
9968        let mut admitted = 1;
9969        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
9970            let _ = entry.next_attempt();
9971            if matches!(
9972                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
9973                FreshOfferAdmission::Joined
9974            ) {
9975                admitted += 1;
9976            }
9977        }
9978
9979        assert!(
9980            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
9981            "a key accepted {admitted} proofs over its lifetime, but the budget is \
9982             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
9983        );
9984    }
9985
9986    #[test]
9987    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
9988        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9989        let data = vec![0x2Cu8; 32];
9990
9991        // The opener occupies the first slot, so the cap is reached after
9992        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
9993        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
9994        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
9995            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
9996            assert!(
9997                matches!(
9998                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
9999                    FreshOfferAdmission::Joined
10000                ),
10001                "sender {i} is within the legitimate close-group fan-out"
10002            );
10003        }
10004
10005        let surplus = test_peer(0xEE);
10006        assert!(
10007            matches!(
10008                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10009                FreshOfferAdmission::Full
10010            ),
10011            "past the cap a proof is surplus: enough are already queued to place the record"
10012        );
10013    }
10014
10015    #[test]
10016    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10017        assert!(!verification_request_exceeds_limit(
10018            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10019        ));
10020        assert!(verification_request_exceeds_limit(
10021            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10022        ));
10023    }
10024
10025    // The heavy round-1 limiter enforces the per-peer rate cooldown
10026    // and single-use round-1 → round-2 sessions.
10027    #[tokio::test]
10028    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10029        let limiter = SubtreeRound1Limiter::new(
10030            Duration::from_secs(3600),
10031            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10032        );
10033        let peer = test_peer(1);
10034
10035        // First round-1 is admitted; drop the guard so concurrency is free again.
10036        let guard = limiter.admit(&peer).await;
10037        assert!(guard.is_some(), "first round-1 admitted");
10038        drop(guard);
10039        // A second round-1 within the cooldown is dropped even though the heavy
10040        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10041        assert!(
10042            limiter.admit(&peer).await.is_none(),
10043            "second round-1 within cooldown is rate-dropped"
10044        );
10045        // A different peer has its own cooldown.
10046        assert!(limiter.admit(&test_peer(2)).await.is_some());
10047
10048        // Session: opened by round 1, consumed exactly once by the matching round 2.
10049        let hash = [7u8; 32];
10050        let nonce = [9u8; 32];
10051        limiter.open_session(peer, 42, hash, nonce).await;
10052        // Wrong nonce / commitment does not match.
10053        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10054        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10055        // A round 2 with no prior round 1 (wrong challenge_id) misses.
10056        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10057        // The matching round 2 consumes it — and only once (single-use).
10058        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10059        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10060    }
10061
10062    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10063    // so a party holding several identities refills its allowance by rotating
10064    // between them and can keep the heavy pool busy indefinitely. The work
10065    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10066    // so a fresh identity is refused exactly like a repeat caller once it is
10067    // spent. That is the difference between bounding concurrency and bounding
10068    // sustained work.
10069    #[tokio::test]
10070    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10071        // Cooldown disabled so only the work budget can refuse anything.
10072        let limiter =
10073            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10074        assert!(
10075            limiter.admit(&test_peer(1)).await.is_some(),
10076            "a node starts with budget in hand so it can serve audits at once"
10077        );
10078
10079        // Serve enough proof work to run the balance into debt. Charging exactly
10080        // the burst would leave it at zero, which the next nanosecond of refill
10081        // lifts back above the line — the debt is the point.
10082        limiter
10083            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10084            .await;
10085
10086        for id in 2..8u8 {
10087            assert!(
10088                limiter.admit(&test_peer(id)).await.is_none(),
10089                "a never-seen peer must still be refused while the budget is spent"
10090            );
10091        }
10092    }
10093
10094    // The budget is a rate, not a quota: it comes back on its own, so an honest
10095    // auditor blocked by a flood is only delayed. Carrying the debt is what
10096    // prices an expensive proof above a cheap one — without it, a proof reading
10097    // a maximal subtree would cost no more of the next caller's wait than a
10098    // one-leaf proof.
10099    #[test]
10100    fn round1_work_budget_carries_debt_and_refills_over_time() {
10101        let now = Instant::now();
10102        let at = |secs: u64| {
10103            now.checked_add(Duration::from_secs(secs))
10104                .unwrap_or_else(Instant::now)
10105        };
10106        let mut budget = Round1WorkBudget {
10107            balance: 0,
10108            last_refill: now,
10109        };
10110        assert!(!budget.has_budget(now), "empty means empty");
10111
10112        // A proof costing four seconds' worth of refill leaves four seconds of
10113        // debt, so the wait scales with what was actually served.
10114        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10115        assert!(
10116            !budget.has_budget(at(3)),
10117            "still in debt three seconds after an over-large proof"
10118        );
10119        assert!(
10120            budget.has_budget(at(5)),
10121            "the debt is worked off at the refill rate"
10122        );
10123
10124        // Idle time does not bank unbounded credit for a later flood.
10125        budget.refill(at(24 * 60 * 60));
10126        assert_eq!(
10127            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10128            "refill is capped at the burst size"
10129        );
10130    }
10131
10132    // The heavy round-1 pool size is the tightest bound the responder applies and
10133    // the one least backed by fleet measurement, so it is read from config rather
10134    // than baked into the binary: a fleet that lands on the wrong number retunes
10135    // instead of waiting for a release. These pin that the configured value is
10136    // what actually gates admission, and that a 0 degrades to slow, not to off —
10137    // a wedged-shut responder would read on every auditor as a graced timeout,
10138    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10139    #[tokio::test]
10140    async fn round1_pool_size_comes_from_config() {
10141        // Cooldown disabled so only concurrency can refuse anything.
10142        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10143        let held = limiter.admit(&test_peer(1)).await;
10144        assert!(held.is_some(), "the single configured slot is admitted");
10145        assert!(
10146            limiter.admit(&test_peer(2)).await.is_none(),
10147            "a second concurrent round 1 is refused at a configured pool of 1, \
10148             proving admission follows config rather than the compiled-in default"
10149        );
10150        drop(held);
10151        assert!(
10152            limiter.admit(&test_peer(2)).await.is_some(),
10153            "the slot is reusable once the first proof completes"
10154        );
10155    }
10156
10157    #[tokio::test]
10158    async fn round1_pool_size_of_zero_is_clamped_to_one() {
10159        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10160        assert!(
10161            limiter.admit(&test_peer(1)).await.is_some(),
10162            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10163        );
10164    }
10165
10166    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10167        let mut k = [0u8; 32];
10168        k[0] = b;
10169        k
10170    }
10171
10172    #[test]
10173    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10174        let source = test_peer(0x91);
10175        let corroborator = test_peer(0x92);
10176        let mut evidence = types::KeyVerificationEvidence {
10177            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10178            paid_list: HashMap::new(),
10179        };
10180        let failed = KeyVerificationOutcome::QuorumFailed;
10181
10182        assert_eq!(
10183            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10184            Some(source)
10185        );
10186        assert_eq!(
10187            punishable_singleton_replica_hint_source(
10188                &HashSet::from([source, corroborator]),
10189                &failed,
10190                &evidence,
10191            ),
10192            None,
10193            "corroborated hints must not use the sole-source penalty lane"
10194        );
10195        assert_eq!(
10196            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10197            None,
10198            "paid-list advertisements do not claim possession, so they leave the \
10199             replica-hint source set empty and cannot be penalized"
10200        );
10201
10202        evidence
10203            .presence
10204            .insert(source, PresenceEvidence::Unresolved);
10205        assert_eq!(
10206            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10207            Some(source),
10208            "definitive close-group rejection is punishable without direct contradiction"
10209        );
10210        assert_eq!(
10211            punishable_singleton_replica_hint_source(
10212                &HashSet::from([source]),
10213                &KeyVerificationOutcome::QuorumInconclusive,
10214                &evidence,
10215            ),
10216            None,
10217            "timeouts and inconclusive evidence are neutral"
10218        );
10219
10220        evidence.presence.insert(source, PresenceEvidence::Absent);
10221        assert_eq!(
10222            punishable_singleton_replica_hint_source(
10223                &HashSet::from([source]),
10224                &KeyVerificationOutcome::QuorumVerified {
10225                    sources: vec![corroborator],
10226                },
10227                &evidence,
10228            ),
10229            Some(source),
10230            "an explicit denial is punishable regardless of the overall outcome"
10231        );
10232    }
10233
10234    /// Build a round-2 slice challenge matching an open session. `openings` is
10235    /// empty: these tests exercise admission and session handling only, which
10236    /// run before any block is opened.
10237    fn slice_challenge(
10238        challenge_id: u64,
10239        commitment_hash: [u8; 32],
10240        nonce: [u8; 32],
10241    ) -> protocol::SubtreeSliceChallenge {
10242        protocol::SubtreeSliceChallenge {
10243            challenge_id,
10244            nonce,
10245            challenged_peer_id: [0u8; 32],
10246            expected_commitment_hash: commitment_hash,
10247            openings: Vec::new(),
10248        }
10249    }
10250
10251    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10252    // responder caps MUST NOT burn the single-use round-1 session.
10253    //
10254    // The handler used to consume the session first and admit second, so a
10255    // transient local capacity drop permanently destroyed that audit exchange —
10256    // every retry hit the `no live round-1 session` path and got `Transient`,
10257    // even after load cleared. Turning momentary local load into a deterministic
10258    // round-2 miss costs the responder its whole-slice credit for that round.
10259    #[tokio::test]
10260    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10261        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10262        let inflight = Arc::new(RwLock::new(HashMap::new()));
10263        let round1 =
10264            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10265        let peer = test_peer(0xB1);
10266        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10267        let challenge = slice_challenge(id, hash, nonce);
10268
10269        round1.open_session(peer, id, hash, nonce).await;
10270
10271        // Saturate this peer's share so the next admission must be refused.
10272        let mut hold = Vec::new();
10273        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10274            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10275                .await
10276            {
10277                Ok(guard) => hold.push(guard),
10278                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10279            }
10280        }
10281
10282        let refused =
10283            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10284        assert!(
10285            matches!(refused, SliceAdmission::Capacity(_)),
10286            "a saturated peer share must refuse on capacity, not on session"
10287        );
10288
10289        // Load clears. The session must have survived the refusal.
10290        drop(hold);
10291        let retried =
10292            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10293        assert!(
10294            matches!(retried, SliceAdmission::Admitted(_)),
10295            "the round-1 session must survive a capacity refusal so the retry succeeds"
10296        );
10297
10298        // Still single-use: the successful admission consumed it exactly once.
10299        drop(retried);
10300        let replayed =
10301            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10302        assert!(
10303            matches!(replayed, SliceAdmission::NoSession),
10304            "a consumed session must not be replayable"
10305        );
10306    }
10307
10308    // The permit taken for the session probe is released when the probe misses,
10309    // so an unsessioned flood cannot pin the responder pool shut.
10310    #[tokio::test]
10311    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10312        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10313        let inflight = Arc::new(RwLock::new(HashMap::new()));
10314        let round1 =
10315            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10316        let peer = test_peer(0xB2);
10317        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10318
10319        // Far more unsessioned challenges than the per-peer cap would allow if
10320        // the slot leaked on the miss path.
10321        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10322            let outcome =
10323                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10324            assert!(
10325                matches!(outcome, SliceAdmission::NoSession),
10326                "no session was ever opened, so every attempt must miss"
10327            );
10328        }
10329
10330        assert_eq!(
10331            semaphore.available_permits(),
10332            MAX_CONCURRENT_AUDIT_RESPONSES,
10333            "every global permit must be returned"
10334        );
10335        assert!(
10336            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10337            "no per-peer slot may be left occupied"
10338        );
10339    }
10340
10341    #[test]
10342    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10343        assert!(!audit_failure_revokes_holder_credit(
10344            &AuditFailureReason::Timeout
10345        ));
10346        assert!(audit_failure_revokes_holder_credit(
10347            &AuditFailureReason::DigestMismatch
10348        ));
10349    }
10350
10351    #[tokio::test]
10352    async fn audit_responder_admission_reports_per_peer_cap_full() {
10353        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10354        let inflight = Arc::new(RwLock::new(HashMap::new()));
10355        let peer = test_peer(0xA1);
10356
10357        let mut guards = Vec::new();
10358        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10359            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10360                .await
10361            {
10362                Ok(guard) => guards.push(guard),
10363                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10364            }
10365        }
10366
10367        let Err(err) =
10368            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10369        else {
10370            panic!("admission should fail once per-peer cap is full");
10371        };
10372        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10373        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10374        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10375        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10376
10377        drop(guards);
10378    }
10379
10380    #[tokio::test]
10381    async fn audit_responder_admission_reports_global_pool_full() {
10382        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10383        let inflight = Arc::new(RwLock::new(HashMap::new()));
10384        let peer = test_peer(0xA2);
10385
10386        let mut held_global_permits = Vec::new();
10387        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10388            held_global_permits.push(
10389                Arc::clone(&semaphore)
10390                    .try_acquire_owned()
10391                    .expect("test should be able to exhaust the global pool"),
10392            );
10393        }
10394
10395        let Err(err) =
10396            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10397        else {
10398            panic!("admission should fail once global pool is full");
10399        };
10400        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10401        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10402        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10403        assert_eq!(err.peer_inflight, 0);
10404        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10405
10406        drop(held_global_permits);
10407    }
10408
10409    #[tokio::test]
10410    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10411        let semaphore = Arc::new(Semaphore::new(1));
10412        let inflight = Arc::new(RwLock::new(HashMap::new()));
10413        let peer = test_peer(0xA3);
10414
10415        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10416            .await
10417            .expect("first responder should be admitted");
10418        assert_eq!(semaphore.available_permits(), 0);
10419        assert_eq!(inflight.read().await.get(&peer), Some(&1));
10420
10421        drop(guard);
10422        assert_eq!(semaphore.available_permits(), 1);
10423        assert!(!inflight.read().await.contains_key(&peer));
10424    }
10425
10426    #[tokio::test]
10427    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10428        let semaphore = Arc::new(Semaphore::new(1));
10429        let inflight = Arc::new(RwLock::new(HashMap::new()));
10430        let peer = test_peer(0xA4);
10431        let held_map = inflight.write().await;
10432
10433        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10434        assert!(
10435            tokio::time::timeout(Duration::from_millis(10), waiting)
10436                .await
10437                .is_err(),
10438            "admission should still be waiting for the peer map"
10439        );
10440
10441        drop(held_map);
10442        assert_eq!(semaphore.available_permits(), 1);
10443        assert!(!inflight.read().await.contains_key(&peer));
10444    }
10445
10446    #[test]
10447    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10448        let timeout = Duration::from_secs(1);
10449        let old_received_at = Instant::now()
10450            .checked_sub(timeout)
10451            .unwrap_or_else(Instant::now);
10452
10453        assert!(request_is_stale(old_received_at, timeout));
10454        assert!(!request_is_stale(Instant::now(), timeout));
10455    }
10456
10457    #[tokio::test]
10458    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10459        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10460        let inflight = Arc::new(RwLock::new(HashMap::new()));
10461        let first_peer = test_peer(0xB3);
10462        let second_peer = test_peer(0xB4);
10463
10464        let first_guard = admit_bounded_responder(
10465            &semaphore,
10466            &inflight,
10467            &first_peer,
10468            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10469            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10470        )
10471        .await
10472        .expect("first sync from a peer should be admitted");
10473        let duplicate = admit_bounded_responder(
10474            &semaphore,
10475            &inflight,
10476            &first_peer,
10477            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10478            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10479        )
10480        .await;
10481        let other_peer = admit_bounded_responder(
10482            &semaphore,
10483            &inflight,
10484            &second_peer,
10485            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10486            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10487        )
10488        .await;
10489
10490        assert!(matches!(
10491            duplicate,
10492            Err(ResponderAdmissionFailure {
10493                reason: ResponderRejectReason::PerPeerCapFull,
10494                ..
10495            })
10496        ));
10497        assert!(other_peer.is_ok());
10498        drop(first_guard);
10499        drop(other_peer);
10500    }
10501
10502    /// One flooding peer must not be able to hold every fresh-offer slot.
10503    ///
10504    /// This is the eviction primitive the per-peer share closes: with only a
10505    /// global bound, a single source occupies the pool, every honest offer in
10506    /// that window is refused, and because a refusal reads as absence to the
10507    /// sender's delayed possession check those refusals land as
10508    /// audit-severity penalties on *this* node.
10509    #[tokio::test]
10510    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10511        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10512        let inflight = Arc::new(RwLock::new(HashMap::new()));
10513        let flooder = test_peer(0xC1);
10514        let honest = test_peer(0xC2);
10515
10516        let mut held = Vec::new();
10517        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10518            held.push(
10519                admit_bounded_responder(
10520                    &semaphore,
10521                    &inflight,
10522                    &flooder,
10523                    FRESH_OFFER_MAX_OUTSTANDING,
10524                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10525                )
10526                .await
10527                .expect("offers within the per-peer share are admitted"),
10528            );
10529        }
10530
10531        let flooder_excess = admit_bounded_responder(
10532            &semaphore,
10533            &inflight,
10534            &flooder,
10535            FRESH_OFFER_MAX_OUTSTANDING,
10536            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10537        )
10538        .await;
10539        assert!(
10540            matches!(
10541                flooder_excess,
10542                Err(ResponderAdmissionFailure {
10543                    reason: ResponderRejectReason::PerPeerCapFull,
10544                    ..
10545                })
10546            ),
10547            "one source must not exceed its fresh-offer share"
10548        );
10549
10550        let honest_offer = admit_bounded_responder(
10551            &semaphore,
10552            &inflight,
10553            &honest,
10554            FRESH_OFFER_MAX_OUTSTANDING,
10555            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10556        )
10557        .await;
10558        assert!(
10559            honest_offer.is_ok(),
10560            "an honest sender must still be admitted while another peer floods"
10561        );
10562
10563        assert!(
10564            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10565                < FRESH_OFFER_MAX_OUTSTANDING,
10566            "the per-peer share must leave room for other sources"
10567        );
10568
10569        drop(held);
10570        drop(honest_offer);
10571    }
10572
10573    /// Paid notifies get the same per-source treatment as every other class.
10574    #[tokio::test]
10575    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10576        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10577        let inflight = Arc::new(RwLock::new(HashMap::new()));
10578        let flooder = test_peer(0xC3);
10579        let honest = test_peer(0xC4);
10580
10581        let mut held = Vec::new();
10582        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10583            held.push(
10584                admit_bounded_responder(
10585                    &semaphore,
10586                    &inflight,
10587                    &flooder,
10588                    PAID_NOTIFY_MAX_OUTSTANDING,
10589                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10590                )
10591                .await
10592                .expect("notifies within the per-peer share are admitted"),
10593            );
10594        }
10595
10596        assert!(
10597            matches!(
10598                admit_bounded_responder(
10599                    &semaphore,
10600                    &inflight,
10601                    &flooder,
10602                    PAID_NOTIFY_MAX_OUTSTANDING,
10603                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10604                )
10605                .await,
10606                Err(ResponderAdmissionFailure {
10607                    reason: ResponderRejectReason::PerPeerCapFull,
10608                    ..
10609                })
10610            ),
10611            "one source must not exceed its paid-notify share"
10612        );
10613        assert!(
10614            admit_bounded_responder(
10615                &semaphore,
10616                &inflight,
10617                &honest,
10618                PAID_NOTIFY_MAX_OUTSTANDING,
10619                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10620            )
10621            .await
10622            .is_ok(),
10623            "an honest sender must still be admitted while another peer floods"
10624        );
10625
10626        drop(held);
10627    }
10628
10629    /// The fresh-offer per-source bound must guarantee headroom for a peer
10630    /// holding nothing, without throttling a single legitimate fan-out.
10631    ///
10632    /// Sized as a quota rather than a reserve, this bound refused offers during
10633    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
10634    /// refusal is charged to THIS node at audit severity because the sender
10635    /// never reads it.
10636    #[test]
10637    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10638        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10639
10640        assert_eq!(
10641            FRESH_OFFER_MAX_OUTSTANDING - share,
10642            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10643            "a source holding none must always find a free slot"
10644        );
10645        assert!(
10646            share < FRESH_OFFER_MAX_OUTSTANDING,
10647            "one peer must not be able to take the whole pool"
10648        );
10649        // The failure this pins: a share sized like the request/response
10650        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
10651        // one-way bulk traffic.
10652        assert!(
10653            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10654            "fresh offers are one-way bulk, not request/response — their share \
10655             must not be sized like the request classes'"
10656        );
10657    }
10658
10659    /// A malformed offer must be refused before it can occupy an admission
10660    /// slot, so junk cannot hold capacity for the length of a verification.
10661    #[test]
10662    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10663        let key = test_key(0xC5);
10664
10665        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10666
10667        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10668            .expect("an offer with no proof must be refused");
10669        assert!(
10670            rejection.penalise,
10671            "an honest sender always attaches a proof"
10672        );
10673
10674        // A proof is retained per queued sender, so its size has to be bounded
10675        // here rather than at the verifier, which only sees it on a worker.
10676        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10677        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10678            .expect("an undersized proof must be refused");
10679        assert!(
10680            rejection.penalise,
10681            "no honest sender constructs an undersized proof"
10682        );
10683        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10684        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10685            .expect("an oversized proof must be refused");
10686        assert!(
10687            rejection.penalise,
10688            "no honest sender constructs an oversized proof"
10689        );
10690
10691        let rejection = fresh_offer_structural_rejection(
10692            &key,
10693            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10694            &valid_proof,
10695        )
10696        .expect("an oversized offer must be refused");
10697        assert!(
10698            rejection.penalise,
10699            "no honest sender constructs an oversized offer"
10700        );
10701
10702        let data = vec![0u8; 1];
10703        assert!(
10704            fresh_offer_structural_rejection(
10705                &crate::client::compute_address(&data),
10706                &data,
10707                &valid_proof
10708            )
10709            .is_none(),
10710            "a well-formed offer must reach admission"
10711        );
10712    }
10713
10714    /// Knowing a key must not be enough to enter its entry.
10715    ///
10716    /// Opening an entry on an unverified key/bytes association would let a peer
10717    /// that has only *learned* the key — every recipient of its `PaidNotify`,
10718    /// not just the close group that gets the chunk — seize it with junk.
10719    /// Joining one would be worse: the handler tries each queued proof against
10720    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
10721    /// on bytes it never offered.
10722    #[test]
10723    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10724        let genuine_data = vec![0x5Au8; 128];
10725        let key = crate::client::compute_address(&genuine_data);
10726        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10727
10728        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10729            .expect("bytes that do not hash to the advertised key must be refused");
10730        assert!(
10731            rejection.penalise,
10732            "no honest sender offers bytes that do not hash to the advertised key"
10733        );
10734
10735        // Dispatch reaches the entry only past that rejection, so the forged
10736        // offer never touched the key and the genuine one still opens it.
10737        assert!(
10738            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10739            "the offer that actually carries the key's bytes must reach the entry"
10740        );
10741
10742        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10743        assert!(
10744            matches!(
10745                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10746                FreshOfferAdmission::Opened(_)
10747            ),
10748            "an offer refused on payload shape must leave the key openable"
10749        );
10750    }
10751
10752    #[tokio::test]
10753    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
10754        let peer = test_peer(0xA5);
10755        let key = test_key(0xA5);
10756        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10757        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10758        let is_bootstrapping = Arc::new(RwLock::new(true));
10759        let bootstrap_complete_notify = Arc::new(Notify::new());
10760
10761        let now = Instant::now();
10762        queues.write().await.add_pending_verify(
10763            key,
10764            VerificationEntry {
10765                state: VerificationState::PendingVerify,
10766                verified_sources: Vec::new(),
10767                tried_sources: HashSet::new(),
10768                created_at: now,
10769                next_verify_at: now,
10770                hint_sources: HashSet::from([peer]),
10771                replica_hint_sources: HashSet::from([peer]),
10772            },
10773        );
10774        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
10775        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10776        {
10777            let q = queues.read().await;
10778            assert!(
10779                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
10780                "capacity rejection should initially block bootstrap drain"
10781            );
10782        }
10783
10784        update_bootstrap_after_peer_removed(
10785            &peer,
10786            &bootstrap_state,
10787            &queues,
10788            &is_bootstrapping,
10789            &bootstrap_complete_notify,
10790        )
10791        .await;
10792
10793        let state = bootstrap_state.read().await;
10794        assert!(state.capacity_rejected_sources.is_empty());
10795        assert!(state.pending_keys.is_empty());
10796        assert!(state.is_drained());
10797        drop(state);
10798        assert!(!*is_bootstrapping.read().await);
10799    }
10800
10801    /// A fairness displacement forfeits the key but must not stamp its former
10802    /// owner: the owner did nothing wrong, and stamping it lets a flooding
10803    /// source block bootstrap drain through an unrelated honest peer.
10804    #[tokio::test]
10805    async fn fairness_displacement_does_not_stamp_its_victim() {
10806        let displaced_owner = test_peer(0xB1);
10807        let incoming_source = test_peer(0xB2);
10808        let displaced_key = test_key(0xB1);
10809        let admitted_key = test_key(0xB2);
10810        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10811        {
10812            let mut state = bootstrap_state.write().await;
10813            state.pending_keys.insert(displaced_key);
10814            state
10815                .capacity_rejected_sources
10816                .insert(incoming_source, Instant::now());
10817        }
10818        let outcomes = [(
10819            incoming_source,
10820            AdmissionOutcome {
10821                discovered: HashSet::from([admitted_key]),
10822                capacity_rejected_count: 0,
10823                displaced: vec![CapacityDisplacement {
10824                    key: displaced_key,
10825                    owner: displaced_owner,
10826                }],
10827            },
10828        )];
10829
10830        publish_bootstrap_admission_outcomes(
10831            &bootstrap_state,
10832            &outcomes,
10833            &HashSet::from([admitted_key]),
10834        )
10835        .await;
10836
10837        let state = bootstrap_state.read().await;
10838        assert!(!state.pending_keys.contains(&displaced_key));
10839        assert!(state.pending_keys.contains(&admitted_key));
10840        assert!(
10841            !state
10842                .capacity_rejected_sources
10843                .contains_key(&displaced_owner),
10844            "the displaced owner must not be charged for our own fairness reclaim"
10845        );
10846        assert!(!state
10847            .capacity_rejected_sources
10848            .contains_key(&incoming_source));
10849    }
10850
10851    /// A source that keeps overflowing us must not keep its own record fresh.
10852    ///
10853    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
10854    /// rejection the debt could never age out, so `check_bootstrap_drained`
10855    /// stayed false forever and auditing never started (Invariant 19).
10856    #[tokio::test]
10857    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
10858        const REJECTION_ROUNDS: usize = 5;
10859
10860        let source = test_peer(0xB3);
10861        let key = test_key(0xB3);
10862        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10863
10864        let first_seen = {
10865            let outcomes = [(
10866                source,
10867                AdmissionOutcome {
10868                    discovered: HashSet::new(),
10869                    capacity_rejected_count: 1,
10870                    displaced: Vec::new(),
10871                },
10872            )];
10873            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
10874                .await;
10875            bootstrap_state
10876                .read()
10877                .await
10878                .capacity_rejected_sources
10879                .get(&source)
10880                .copied()
10881                .expect("first rejection recorded")
10882        };
10883
10884        for _ in 0..REJECTION_ROUNDS {
10885            let outcomes = [(
10886                source,
10887                AdmissionOutcome {
10888                    discovered: HashSet::from([key]),
10889                    capacity_rejected_count: 1,
10890                    displaced: Vec::new(),
10891                },
10892            )];
10893            publish_bootstrap_admission_outcomes(
10894                &bootstrap_state,
10895                &outcomes,
10896                &HashSet::from([key]),
10897            )
10898            .await;
10899        }
10900
10901        let recorded = bootstrap_state
10902            .read()
10903            .await
10904            .capacity_rejected_sources
10905            .get(&source)
10906            .copied()
10907            .expect("debt still outstanding");
10908        assert_eq!(
10909            recorded, first_seen,
10910            "repeat rejections must not restart the expiry clock"
10911        );
10912    }
10913
10914    /// The verification-worker tick's self-heal path: a capacity rejection
10915    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
10916    /// blocks drain until the TTL expires it, at which point the same tick
10917    /// completes bootstrap without any external event.
10918    #[tokio::test]
10919    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
10920        let peer = test_peer(0xA6);
10921        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10922        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10923        let is_bootstrapping = Arc::new(RwLock::new(true));
10924        let bootstrap_complete_notify = Arc::new(Notify::new());
10925
10926        // PeerRemoved was fully processed before the rejection landed, so no
10927        // future event will ever clear this entry.
10928        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10929
10930        // Within the TTL the tick keeps waiting for re-delivery.
10931        expire_and_recheck_bootstrap_drain(
10932            &bootstrap_state,
10933            &queues,
10934            &is_bootstrapping,
10935            &bootstrap_complete_notify,
10936            ReplicationConfig::default().capacity_rejected_max_age(),
10937        )
10938        .await;
10939        assert!(!bootstrap_state.read().await.is_drained());
10940        assert!(*is_bootstrapping.read().await);
10941
10942        // Past the TTL the tick expires the orphan and completes bootstrap.
10943        expire_and_recheck_bootstrap_drain(
10944            &bootstrap_state,
10945            &queues,
10946            &is_bootstrapping,
10947            &bootstrap_complete_notify,
10948            Duration::ZERO,
10949        )
10950        .await;
10951        assert!(bootstrap_state.read().await.is_drained());
10952        assert!(!*is_bootstrapping.read().await);
10953    }
10954
10955    #[test]
10956    fn first_audit_terminal_outcomes_are_stable() {
10957        let peer = test_peer(1);
10958        let passed = AuditTickResult::Passed {
10959            challenged_peer: peer,
10960            keys_checked: 1,
10961        };
10962        let timed_out = AuditTickResult::Failed {
10963            evidence: FailureEvidence::AuditFailure {
10964                challenge_id: 1,
10965                challenged_peer: peer,
10966                confirmed_failed_keys: vec![test_key(1)],
10967                summary: crate::replication::types::AuditFailureSummary::default(),
10968                reason: AuditFailureReason::Timeout,
10969            },
10970            no_response_class: Some("timeout"),
10971        };
10972
10973        assert_eq!(
10974            first_audit_terminal_outcome(&passed),
10975            FirstAuditTerminalOutcome::Passed
10976        );
10977        assert_eq!(
10978            first_audit_terminal_outcome(&timed_out),
10979            FirstAuditTerminalOutcome::Timeout
10980        );
10981        assert_eq!(
10982            first_audit_terminal_outcome(&AuditTickResult::Idle),
10983            FirstAuditTerminalOutcome::Idle
10984        );
10985        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
10986        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
10987        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
10988        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
10989        assert_eq!(
10990            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
10991            "insufficient_keys"
10992        );
10993        assert_eq!(
10994            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
10995            "bootstrap_claim"
10996        );
10997    }
10998
10999    #[test]
11000    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11001        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11002        let mut rng = StdRng::seed_from_u64(7);
11003        let peer = test_peer(1);
11004        let base = MonetizedPinEvent {
11005            peer,
11006            pin: [1; 32],
11007            key_count: 100,
11008            quote_ts: SystemTime::now(),
11009        };
11010
11011        // First insert into an empty slot: Queued.
11012        assert_eq!(
11013            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11014            FirstAuditQueueOutcome::Queued
11015        );
11016
11017        // A strictly LOWER-count same-peer nomination must NOT displace it.
11018        let lower = MonetizedPinEvent {
11019            pin: [2; 32],
11020            key_count: 50,
11021            ..base
11022        };
11023        assert_eq!(
11024            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11025            FirstAuditQueueOutcome::SuppressedLower
11026        );
11027        assert_eq!(
11028            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11029            Some(([1; 32], 100)),
11030            "the higher-count pin is retained"
11031        );
11032
11033        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11034        let higher = MonetizedPinEvent {
11035            pin: [3; 32],
11036            key_count: 400,
11037            ..base
11038        };
11039        assert_eq!(
11040            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11041            FirstAuditQueueOutcome::Coalesced
11042        );
11043        assert_eq!(
11044            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11045            Some(([3; 32], 400))
11046        );
11047
11048        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11049        let equal_newer = MonetizedPinEvent {
11050            pin: [4; 32],
11051            key_count: 400,
11052            ..base
11053        };
11054        assert_eq!(
11055            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11056            FirstAuditQueueOutcome::Coalesced
11057        );
11058        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11059        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11060        let equal_older = MonetizedPinEvent {
11061            pin: [5; 32],
11062            key_count: 400,
11063            ..base
11064        };
11065        assert_eq!(
11066            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11067            FirstAuditQueueOutcome::RetainedOnTie
11068        );
11069        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11070
11071        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11072        let other_peer = MonetizedPinEvent {
11073            peer: test_peer(2),
11074            pin: [6; 32],
11075            key_count: 100,
11076            ..base
11077        };
11078        assert_eq!(
11079            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11080            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11081        );
11082        assert_eq!(pending.len(), 1);
11083        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11084    }
11085
11086    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11087
11088    #[test]
11089    fn first_audit_limiter_enforces_burst_then_refills() {
11090        let base = Instant::now();
11091        let mut limiter = FirstAuditLimiter::new(base);
11092        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11093
11094        // The full burst is admitted back-to-back (distinct peers).
11095        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11096            let peer = test_peer(u8::try_from(i).expect("small burst"));
11097            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11098            limiter.commit_launch(peer, 10, base);
11099        }
11100        // Bucket empty: the next distinct peer is deferred, never dropped.
11101        let extra = test_peer(0xEE);
11102        assert_eq!(
11103            limiter.assess(&extra, 10, base, 0),
11104            LimiterVerdict::RateDeferred
11105        );
11106
11107        // One full interval later exactly one token is available again.
11108        let later = base + interval;
11109        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11110        limiter.commit_launch(extra, 10, later);
11111        let extra2 = test_peer(0xEF);
11112        assert_eq!(
11113            limiter.assess(&extra2, 10, later, 0),
11114            LimiterVerdict::RateDeferred
11115        );
11116    }
11117
11118    #[test]
11119    fn first_audit_limiter_refill_keeps_fractional_remainder() {
11120        let base = Instant::now();
11121        let mut limiter = FirstAuditLimiter::new(base);
11122        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11123        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11124            let peer = test_peer(u8::try_from(i).expect("small burst"));
11125            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11126            limiter.commit_launch(peer, 1, base);
11127        }
11128        // 1.5 intervals later one token is earned and the half interval is
11129        // NOT lost to drift...
11130        let at_1_5 = base + interval + interval / 2;
11131        let p = test_peer(0xAA);
11132        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11133        limiter.commit_launch(p, 1, at_1_5);
11134        // ...so the next token arrives at 2.0 intervals, not 2.5.
11135        let at_2_0 = base + interval * 2;
11136        let q = test_peer(0xAB);
11137        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11138    }
11139
11140    #[test]
11141    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11142        let base = Instant::now();
11143        let mut limiter = FirstAuditLimiter::new(base);
11144        let peer = test_peer(1);
11145        assert_eq!(
11146            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11147            LimiterVerdict::RateDeferred
11148        );
11149        // A freed slot admits without any clock movement.
11150        assert_eq!(
11151            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11152            LimiterVerdict::Admit
11153        );
11154    }
11155
11156    #[test]
11157    fn first_audit_limiter_assess_consumes_nothing() {
11158        let base = Instant::now();
11159        let mut limiter = FirstAuditLimiter::new(base);
11160        let peer = test_peer(3);
11161        // Repeated assessment must not burn budget or stamp the window: only
11162        // `commit_launch` consumes (the cooldown gate between assess and
11163        // commit can defer, and that deferral must be free).
11164        for _ in 0..10 {
11165            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11166        }
11167        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11168            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11169            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11170            limiter.commit_launch(p, 5, base);
11171        }
11172    }
11173
11174    #[test]
11175    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11176        let base = Instant::now();
11177        let mut limiter = FirstAuditLimiter::new(base);
11178        let peer = test_peer(7);
11179        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11180        limiter.commit_launch(peer, 100, base);
11181
11182        // A rotated pin with a similar count inside the window is dropped...
11183        let soon = base + Duration::from_secs(60);
11184        assert_eq!(
11185            limiter.assess(&peer, 100, soon, 0),
11186            LimiterVerdict::WindowDeduped
11187        );
11188        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11189        assert_eq!(
11190            limiter.assess(&peer, 150, soon, 0),
11191            LimiterVerdict::WindowDeduped
11192        );
11193        // ...but a >1.5x committed-count jump re-nominates immediately (an
11194        // inflated sidecar-only pin is invisible to the gossip lottery, so
11195        // the window must not shield it).
11196        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11197
11198        // Window expiry re-admits an unchanged count.
11199        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11200        assert_eq!(
11201            limiter.assess(&peer, 100, expired, 0),
11202            LimiterVerdict::Admit
11203        );
11204    }
11205
11206    #[test]
11207    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11208        // A window-deduped nomination must be DROPPED, not kept pending as
11209        // rate-deferred, even when the bucket is also empty: re-queuing a
11210        // suppressed rotation would hold a pending slot for two hours.
11211        let base = Instant::now();
11212        let mut limiter = FirstAuditLimiter::new(base);
11213        let peer = test_peer(9);
11214        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11215        limiter.commit_launch(peer, 10, base);
11216        let other = test_peer(10);
11217        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11218        limiter.commit_launch(other, 10, base);
11219        assert_eq!(
11220            limiter.assess(&peer, 10, base, 0),
11221            LimiterVerdict::WindowDeduped
11222        );
11223    }
11224
11225    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11226    /// is answerable now but would age out of the answerability window during
11227    /// the launch jitter, so scheduling state is only ever committed for a pin
11228    /// that can still be challenged when it actually sends.
11229    #[test]
11230    fn first_audit_horizon_prefilter_boundary() {
11231        let now = SystemTime::now();
11232        // C = the too-old cutoff; H = the worst-case send horizon.
11233        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11234        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11235        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11236        let boundary = now
11237            .checked_add(h)
11238            .and_then(|t| t.checked_sub(c))
11239            .expect("boundary time");
11240
11241        // In window at `now` (age = C - H < C)...
11242        assert!(quote_within_audit_window(boundary, now));
11243        // ...but the horizon prefilter rejects it (age == C at now + H).
11244        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11245
11246        // A hair newer stays answerable through the horizon; a hair older does
11247        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11248        // a nanosecond step would round to the same instant there.
11249        let newer = boundary
11250            .checked_add(Duration::from_micros(1))
11251            .expect("newer");
11252        let older = boundary
11253            .checked_sub(Duration::from_micros(1))
11254            .expect("older");
11255        assert!(quote_answerable_through_nominal_jitter(newer, now));
11256        assert!(!quote_answerable_through_nominal_jitter(older, now));
11257
11258        // A quote too far in the FUTURE is rejected at `now`, independent of the
11259        // horizon.
11260        let future = now
11261            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11262            .and_then(|t| t.checked_add(Duration::from_secs(60)))
11263            .expect("future");
11264        assert!(!quote_answerable_through_nominal_jitter(future, now));
11265    }
11266
11267    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11268    /// answerability check fails at promotion is fully state-neutral — it stamps
11269    /// no `first_audited`, no per-peer window, refunds its token, releases its
11270    /// in-flight slot, does not flip the lane, and does not count a launch — and
11271    /// a same-peer, same-count successor enqueued DURING the reservation is
11272    /// retained and becomes the next reservation after the cancel. This is the
11273    /// exact hole the reviewer flagged: suppression must never outlive a launch
11274    /// that did not send.
11275    /// A pending pin that has aged past the answerability horizon must not
11276    /// suppress a live lower-count nomination for the same peer: under token
11277    /// starvation no reserve scan ever collects the dead entry, so without the
11278    /// enqueue-time check the peer would stay unauditable through this path
11279    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11280    #[test]
11281    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11282        let obs = Arc::new(FirstAuditObservability::default());
11283        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11284        let peer = test_peer(1);
11285
11286        let dead_quote = SystemTime::now()
11287            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11288            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11289            .expect("past wall time");
11290        let stale_high = MonetizedPinEvent {
11291            peer,
11292            pin: [1; 32],
11293            key_count: 400,
11294            quote_ts: dead_quote,
11295        };
11296        scheduler.enqueue(stale_high, &obs);
11297        assert_eq!(scheduler.pending_len(), 1);
11298
11299        // A fresh, lower-count nomination (a post-prune commitment).
11300        let fresh_lower = MonetizedPinEvent {
11301            peer,
11302            pin: [2; 32],
11303            key_count: 100,
11304            quote_ts: SystemTime::now(),
11305        };
11306        scheduler.enqueue(fresh_lower, &obs);
11307
11308        assert_eq!(scheduler.pending_len(), 1);
11309        assert_eq!(
11310            scheduler.pending.peek(&peer).map(|e| e.pin),
11311            Some([2; 32]),
11312            "the live nomination replaced the dead incumbent"
11313        );
11314        assert_eq!(
11315            obs.suppressed_lower.load(Ordering::Relaxed),
11316            0,
11317            "no self-erasure signal for displacing a dead pin"
11318        );
11319        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11320        assert_eq!(
11321            obs.outside_answerability_window.load(Ordering::Relaxed),
11322            1,
11323            "the dead incumbent is accounted as an expiry"
11324        );
11325    }
11326
11327    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11328    /// nomination still loses to an answerable higher-count pending pin.
11329    #[test]
11330    fn first_audit_live_incumbent_still_suppresses_lower_count() {
11331        let obs = Arc::new(FirstAuditObservability::default());
11332        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11333        let peer = test_peer(1);
11334
11335        let live_high = MonetizedPinEvent {
11336            peer,
11337            pin: [1; 32],
11338            key_count: 400,
11339            quote_ts: SystemTime::now(),
11340        };
11341        scheduler.enqueue(live_high, &obs);
11342        let cheaper = MonetizedPinEvent {
11343            peer,
11344            pin: [2; 32],
11345            key_count: 100,
11346            quote_ts: SystemTime::now(),
11347        };
11348        scheduler.enqueue(cheaper, &obs);
11349
11350        assert_eq!(scheduler.pending_len(), 1);
11351        assert_eq!(
11352            scheduler.pending.peek(&peer).map(|e| e.pin),
11353            Some([1; 32]),
11354            "the higher-count live pin is retained"
11355        );
11356        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11357        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11358    }
11359
11360    /// A fresh nomination for peer `b` (distinct pin per peer).
11361    fn live_nomination(b: u8) -> MonetizedPinEvent {
11362        MonetizedPinEvent {
11363            peer: test_peer(b),
11364            pin: [b; 32],
11365            key_count: 100,
11366            quote_ts: SystemTime::now(),
11367        }
11368    }
11369
11370    /// The pending admission cap must equal the number of usable launches the
11371    /// token budget can perform inside one answerability window, counted by
11372    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11373    /// tokens at age zero, one refill per launch interval), not by repeating
11374    /// the derivation formula. Any larger and admitted work is guaranteed to
11375    /// expire unlaunched; any smaller and the budget idles while nominations
11376    /// are displaced.
11377    #[test]
11378    fn first_audit_pending_cap_matches_strict_launch_horizon() {
11379        let quote_ts = SystemTime::now();
11380        // Burst launches fire at age zero and must pass the reserve predicate.
11381        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11382        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11383        let mut refill = 1u32;
11384        loop {
11385            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11386            let at = quote_ts + age;
11387            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11388                break;
11389            }
11390            usable += 1;
11391            refill += 1;
11392            assert!(refill < 10_000, "runaway horizon simulation");
11393        }
11394        assert_eq!(
11395            FIRST_AUDIT_PENDING_CAP, usable,
11396            "cap must match the simulated strict launch horizon"
11397        );
11398    }
11399
11400    /// The pending queue is sized to the launch budget while the dedup set
11401    /// keeps the commitment-cache bound: shrinking `first_audited` would
11402    /// forget audited pins and re-admit duplicates.
11403    #[test]
11404    fn first_audit_pending_cap_independent_of_dedup_cap() {
11405        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11406        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11407        assert_eq!(
11408            scheduler.first_audited.cap().get(),
11409            MAX_LAST_COMMITMENT_BY_PEER
11410        );
11411    }
11412
11413    /// Admission beyond the cap displaces exactly one incumbent per overflow
11414    /// and every displacement is accounted as `capacity_evicted` — the steady
11415    /// overload signal — never silent loss, and never an admission refusal.
11416    #[test]
11417    fn first_audit_admission_beyond_cap_displaces_and_counts() {
11418        let obs = Arc::new(FirstAuditObservability::default());
11419        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11420        let overflow: usize = 5;
11421        let total = FIRST_AUDIT_PENDING_CAP + overflow;
11422
11423        for i in 0..total {
11424            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11425            scheduler.enqueue(live_nomination(b), &obs);
11426        }
11427
11428        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11429        assert_eq!(
11430            obs.capacity_evicted.load(Ordering::Relaxed),
11431            u64::try_from(overflow).expect("overflow fits u64"),
11432            "each admission past the cap displaces exactly one entry"
11433        );
11434        assert_eq!(
11435            obs.queued.load(Ordering::Relaxed),
11436            u64::try_from(total).expect("total fits u64"),
11437            "displacement is not an admission refusal"
11438        );
11439        // Every arrival was admitted (the newest always enters the sample).
11440        let last = u8::try_from(total).expect("test peer count fits u8");
11441        assert!(
11442            scheduler.pending.peek(&test_peer(last)).is_some(),
11443            "the newest arrival always enters the sample"
11444        );
11445    }
11446
11447    /// The reviewer-demonstrated suppression route: a target followed by an
11448    /// ordered batch of distinct-peer nominations, all inside one ingress
11449    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11450    /// the token bucket EMPTY so no reservation can intervene. Under the old
11451    /// keep-newest LRU the target was evicted with certainty; under random
11452    /// displacement its per-overflow eviction probability is `1/cap`, so
11453    /// across repeated trials the target must survive some runs and be
11454    /// displaced in others — never deterministically flushed, and every
11455    /// displacement accounted.
11456    #[test]
11457    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11458        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11459        assert!(FIRST_AUDIT_PENDING_CAP < flood);
11460        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11461
11462        let trials = 100u64;
11463        let mut survived = 0u32;
11464        let mut evicted = 0u32;
11465        for trial in 0..trials {
11466            let obs = Arc::new(FirstAuditObservability::default());
11467            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11468            // Deterministic per-trial seed: the run is fully reproducible (no
11469            // flake budget at all) while still exercising 100 distinct
11470            // eviction sequences.
11471            scheduler.rng = StdRng::seed_from_u64(trial);
11472            // Drain the burst tokens so the pre-overflow reservation
11473            // opportunity cannot fire: this isolates pure retention.
11474            scheduler.limiter.reserve_token();
11475            scheduler.limiter.reserve_token();
11476
11477            let target = test_peer(200);
11478            scheduler.enqueue(live_nomination(200), &obs);
11479            for i in 0..flood {
11480                let b = u8::try_from(i + 1).expect("flood peer fits u8");
11481                scheduler.enqueue(live_nomination(b), &obs);
11482            }
11483
11484            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11485            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11486                .expect("overflow count fits u64");
11487            assert_eq!(
11488                obs.capacity_evicted.load(Ordering::Relaxed),
11489                overflows,
11490                "every overflow past the cap is accounted, none silent"
11491            );
11492            if scheduler.pending.peek(&target).is_some() {
11493                survived += 1;
11494            } else {
11495                evicted += 1;
11496            }
11497        }
11498        // With eviction probability 1/cap per overflow, P(target survives one
11499        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11500        // 100 seeded trials — and the seeds make the split exactly
11501        // reproducible rather than a (vanishingly small) flake budget.
11502        assert!(
11503            survived > 0,
11504            "target must survive some ordered floods — deterministic eviction \
11505             would mean keep-newest retention regressed"
11506        );
11507        assert!(
11508            evicted > 0,
11509            "target must also be displaceable — otherwise overflow is refusing \
11510             admissions instead of sampling"
11511        );
11512    }
11513
11514    /// With a token AVAILABLE, an overflowing arrival must first give pending
11515    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
11516    /// one entry out of the queue, so admission proceeds without any eviction.
11517    #[test]
11518    fn first_audit_overflow_reserves_before_destructive_eviction() {
11519        let obs = Arc::new(FirstAuditObservability::default());
11520        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11521        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11522
11523        for i in 0..FIRST_AUDIT_PENDING_CAP {
11524            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11525            scheduler.enqueue(live_nomination(b), &obs);
11526        }
11527        let overflowing = live_nomination(250);
11528        assert!(scheduler.would_displace(&overflowing));
11529
11530        // The drainer's pre-overflow sequence: reserve, then enqueue.
11531        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11532        assert!(
11533            !scheduler.would_displace(&overflowing),
11534            "a successful reservation frees the slot"
11535        );
11536        scheduler.enqueue(overflowing, &obs);
11537
11538        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11539        assert_eq!(
11540            obs.capacity_evicted.load(Ordering::Relaxed),
11541            0,
11542            "no destructive eviction when a launch opportunity existed"
11543        );
11544    }
11545
11546    /// Displacement stamps no suppression state: a displaced peer's next
11547    /// nomination re-enters like any newcomer (it is NOT window-deduped or
11548    /// treated as a duplicate), so under overload every peer keeps an
11549    /// unpredictable chance of prompt first audit.
11550    #[test]
11551    fn first_audit_displaced_peer_may_be_renominated() {
11552        let obs = Arc::new(FirstAuditObservability::default());
11553        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11554        let total = FIRST_AUDIT_PENDING_CAP + 1;
11555
11556        for i in 0..total {
11557            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11558            scheduler.enqueue(live_nomination(b), &obs);
11559        }
11560        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11561        // Find whichever peer the random displacement removed.
11562        let displaced = (1..=total)
11563            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11564            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11565            .expect("exactly one admitted peer was displaced");
11566
11567        scheduler.enqueue(live_nomination(displaced), &obs);
11568
11569        assert!(
11570            scheduler.pending.peek(&test_peer(displaced)).is_some(),
11571            "the displaced peer re-enters the sample"
11572        );
11573        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11574        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11575        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11576        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11577    }
11578
11579    /// The periodic sweep collects expired pending entries even when the token
11580    /// bucket is empty — the reserve path returns at the budget gate and never
11581    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
11582    /// honest under fleet-wide starvation.
11583    #[test]
11584    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11585        let obs = Arc::new(FirstAuditObservability::default());
11586        let mono = Instant::now();
11587        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11588
11589        let dead_quote = SystemTime::now()
11590            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11591            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11592            .expect("past wall time");
11593        scheduler.enqueue(
11594            MonetizedPinEvent {
11595                peer: test_peer(1),
11596                pin: [1; 32],
11597                key_count: 100,
11598                quote_ts: dead_quote,
11599            },
11600            &obs,
11601        );
11602        scheduler.enqueue(
11603            MonetizedPinEvent {
11604                peer: test_peer(2),
11605                pin: [2; 32],
11606                key_count: 100,
11607                quote_ts: SystemTime::now(),
11608            },
11609            &obs,
11610        );
11611        assert_eq!(scheduler.pending_len(), 2);
11612
11613        // Empty the bucket so the reserve path is budget-gated (fleet-wide
11614        // starvation) and cannot collect the dead entry itself.
11615        scheduler.limiter.tokens = 0;
11616        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11617        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11618        assert_eq!(
11619            scheduler.pending_len(),
11620            2,
11621            "budget-gated reserve scans nothing"
11622        );
11623
11624        let wall_now = SystemTime::now();
11625        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11626        assert_eq!(scheduler.pending_len(), 1);
11627        assert!(
11628            scheduler.pending.peek(&test_peer(2)).is_some(),
11629            "the live entry survives the sweep"
11630        );
11631        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11632        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11633        assert!(
11634            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11635            "the age gauge reflects only live work after the sweep"
11636        );
11637    }
11638
11639    #[test]
11640    #[allow(clippy::too_many_lines)]
11641    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11642        let obs = Arc::new(FirstAuditObservability::default());
11643        let mono = Instant::now();
11644        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11645
11646        // A pre-existing window sentinel for an UNRELATED peer must survive the
11647        // cancel byte-for-byte (cancel never touches `recent`).
11648        let sentinel_peer = test_peer(0xAA);
11649        scheduler.limiter.promote(sentinel_peer, 500, mono);
11650        let sentinel_before = scheduler
11651            .limiter
11652            .recent
11653            .peek(&sentinel_peer)
11654            .copied()
11655            .expect("sentinel present");
11656
11657        let peer = test_peer(1);
11658        let a = MonetizedPinEvent {
11659            peer,
11660            pin: [1; 32],
11661            key_count: 100,
11662            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
11663        };
11664        scheduler.enqueue(a, &obs);
11665
11666        let tokens_before = scheduler.tokens();
11667        let lane_before = scheduler.oldest_first_lane;
11668        let launched_before = obs.launched.load(Ordering::Relaxed);
11669        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11670
11671        // Reserve A (jitter 0 so it is immediately due).
11672        let inflight0 = obs.inflight.load(Ordering::Relaxed);
11673        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11674        assert_eq!(scheduler.reserved_peer(), Some(peer));
11675        assert_eq!(
11676            scheduler.tokens(),
11677            tokens_before - 1,
11678            "reserve consumes a token"
11679        );
11680        assert_eq!(
11681            obs.inflight.load(Ordering::Relaxed),
11682            1,
11683            "reserve holds a slot"
11684        );
11685
11686        // A same-peer, same-count successor arrives DURING the reservation. It
11687        // must be retained (bypasses the window for the reserved peer) and must
11688        // NOT create a second reservation.
11689        let b = MonetizedPinEvent {
11690            peer,
11691            pin: [2; 32],
11692            key_count: 100,
11693            quote_ts: SystemTime::now(),
11694        };
11695        scheduler.enqueue(b, &obs);
11696        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11697        assert!(
11698            !scheduler.try_reserve(
11699                mono,
11700                obs.inflight.load(Ordering::Relaxed),
11701                Duration::ZERO,
11702                &cooldown,
11703                &obs
11704            ),
11705            "no second reservation while one is outstanding"
11706        );
11707
11708        // Resolve A with an injected wall time PAST A's answerability cutoff.
11709        let reservation = scheduler
11710            .take_due_reservation(mono)
11711            .expect("A is due at jitter 0");
11712        let wall_fail = a
11713            .quote_ts
11714            .checked_add(GOSSIP_ANSWERABILITY_TTL)
11715            .and_then(|t| t.checked_add(Duration::from_secs(1)))
11716            .expect("past-cutoff wall time");
11717        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11718        assert!(
11719            promoted.is_none(),
11720            "answerability lapsed -> cancelled, not promoted"
11721        );
11722
11723        // State-neutral cancel.
11724        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11725        assert!(
11726            scheduler.limiter.recent.peek(&peer).is_none(),
11727            "cancel stamps no per-peer window"
11728        );
11729        assert_eq!(
11730            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11731            Some(sentinel_before),
11732            "unrelated window sentinel untouched"
11733        );
11734        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11735        assert_eq!(
11736            scheduler.tokens(),
11737            tokens_before,
11738            "token refunded on cancel"
11739        );
11740        assert_eq!(
11741            obs.inflight.load(Ordering::Relaxed),
11742            0,
11743            "in-flight slot released"
11744        );
11745        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11746        assert_eq!(
11747            obs.launched.load(Ordering::Relaxed),
11748            launched_before,
11749            "no launch counted"
11750        );
11751        assert_eq!(
11752            obs.outside_answerability_window.load(Ordering::Relaxed),
11753            1,
11754            "the cancel reason is recorded"
11755        );
11756
11757        // The successor is still pending and is now fully schedulable: a fresh
11758        // reserve makes B the next reservation (proving eligibility, not merely
11759        // that the limiter would admit it).
11760        assert_eq!(
11761            scheduler.pending_len(),
11762            1,
11763            "successor still pending after cancel"
11764        );
11765        assert!(scheduler.reserved.is_none());
11766        assert!(scheduler.try_reserve(
11767            mono,
11768            obs.inflight.load(Ordering::Relaxed),
11769            Duration::ZERO,
11770            &cooldown,
11771            &obs
11772        ));
11773        assert_eq!(
11774            scheduler.reserved_peer(),
11775            Some(peer),
11776            "the retained successor becomes the next reservation"
11777        );
11778    }
11779
11780    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
11781    /// race, the reserved event is requeued ONLY if no same-peer successor is
11782    /// already pending. A successor arrived after the reservation, so it is the
11783    /// newer nomination (e.g. a count jump) and must not be overwritten by the
11784    /// older reserved event.
11785    #[test]
11786    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
11787        let obs = Arc::new(FirstAuditObservability::default());
11788        let mono = Instant::now();
11789        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11790        let peer = test_peer(1);
11791
11792        // Reserve A.
11793        let a = MonetizedPinEvent {
11794            peer,
11795            pin: [1; 32],
11796            key_count: 100,
11797            quote_ts: SystemTime::now(),
11798        };
11799        scheduler.enqueue(a, &obs);
11800        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
11801        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
11802
11803        // A newer same-peer successor B (a count jump) arrives during the
11804        // reservation and is retained.
11805        let b = MonetizedPinEvent {
11806            peer,
11807            pin: [2; 32],
11808            key_count: 400,
11809            quote_ts: SystemTime::now(),
11810        };
11811        scheduler.enqueue(b, &obs);
11812        assert_eq!(scheduler.pending_len(), 1);
11813
11814        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
11815        // is already stamped for the peer, so promotion loses the race.
11816        let reservation = scheduler.take_due_reservation(mono).expect("due");
11817        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11818        cooldown.insert(peer, mono); // freshly on cooldown
11819        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
11820        assert!(promoted.is_none(), "cooldown race -> not promoted");
11821
11822        // B (newer) is preserved; A did NOT overwrite it.
11823        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
11824        assert_eq!(
11825            scheduler.pending.peek(&peer).map(|e| e.pin),
11826            Some([2; 32]),
11827            "the newer successor B is retained, not the older reserved A"
11828        );
11829        assert!(scheduler.first_audited.is_empty());
11830        assert!(scheduler.limiter.recent.peek(&peer).is_none());
11831    }
11832
11833    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
11834    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
11835    /// and saturates to `0` for a future-dated quote (clock skew) without
11836    /// panicking. A climbing value is the pending-work-aging-out signal.
11837    #[test]
11838    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
11839        let now = SystemTime::now();
11840        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11841        assert_eq!(
11842            scheduler.oldest_pending_quote_age_ms(now),
11843            0,
11844            "empty pending -> zero"
11845        );
11846
11847        // Two peers: quotes 10s and 2s old. The gauge must track the older.
11848        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
11849            let _ = coalesce_first_audit_event(
11850                &mut scheduler.pending,
11851                MonetizedPinEvent {
11852                    peer: test_peer(peer_id),
11853                    pin,
11854                    key_count: 100,
11855                    quote_ts: now - Duration::from_secs(secs),
11856                },
11857                true,
11858                &mut scheduler.rng,
11859            );
11860        }
11861        assert_eq!(
11862            scheduler.oldest_pending_quote_age_ms(now),
11863            10_000,
11864            "tracks the oldest (10s), not the newest (2s)"
11865        );
11866
11867        // A future-dated quote (clock skew) saturates to zero, never panics.
11868        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11869        let _ = coalesce_first_audit_event(
11870            &mut skewed.pending,
11871            MonetizedPinEvent {
11872                peer: test_peer(3),
11873                pin: [3; 32],
11874                key_count: 100,
11875                quote_ts: now + Duration::from_secs(5),
11876            },
11877            true,
11878            &mut skewed.rng,
11879        );
11880        assert_eq!(
11881            skewed.oldest_pending_quote_age_ms(now),
11882            0,
11883            "future quote_ts saturates to zero"
11884        );
11885    }
11886
11887    /// A flood of strictly-lower-count same-peer nominations must neither
11888    /// displace the retained higher pin NOR disturb its recency position (each
11889    /// is suppressed via `peek`, no `push`), and each must be counted as
11890    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
11891    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
11892    /// (the documented `lru` contract that also drives the reserve scan's lane
11893    /// ordering), deliberately independent of the overflow policy: eviction is
11894    /// random-victim, so no assertion may require a particular peer to be
11895    /// displaced.
11896    #[test]
11897    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
11898        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
11899            LruCache::new(NonZeroUsize::new(2).unwrap());
11900        let mut rng = StdRng::seed_from_u64(11);
11901        let victim = test_peer(1);
11902        let other = test_peer(2);
11903        // Victim (high count) inserted first (older), then `other` (newer/MRU).
11904        let _ = coalesce_first_audit_event(
11905            &mut pending,
11906            MonetizedPinEvent {
11907                peer: victim,
11908                pin: [1; 32],
11909                key_count: 400,
11910                quote_ts: SystemTime::now(),
11911            },
11912            true,
11913            &mut rng,
11914        );
11915        let _ = coalesce_first_audit_event(
11916            &mut pending,
11917            MonetizedPinEvent {
11918                peer: other,
11919                pin: [9; 32],
11920                key_count: 100,
11921                quote_ts: SystemTime::now(),
11922            },
11923            true,
11924            &mut rng,
11925        );
11926        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11927        assert_eq!(
11928            order_before,
11929            vec![other, victim],
11930            "sanity: `other` is MRU, the victim is LRU"
11931        );
11932
11933        // Flood the victim with cheaper nominations.
11934        let mut suppressed = 0u64;
11935        for i in 0..8u8 {
11936            let out = coalesce_first_audit_event(
11937                &mut pending,
11938                MonetizedPinEvent {
11939                    peer: victim,
11940                    pin: [i; 32],
11941                    key_count: 50,
11942                    quote_ts: SystemTime::now(),
11943                },
11944                true,
11945                &mut rng,
11946            );
11947            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
11948            suppressed += 1;
11949        }
11950        assert_eq!(suppressed, 8);
11951        // Victim pin/count unchanged.
11952        assert_eq!(
11953            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
11954            Some(([1; 32], 400))
11955        );
11956        // Recency untouched: the iteration order (which the reserve lanes
11957        // consume) is byte-for-byte what it was before the flood.
11958        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11959        assert_eq!(
11960            order_after, order_before,
11961            "the suppressed-lower flood must not have changed any recency position"
11962        );
11963    }
11964
11965    /// The cooldown-race requeue counts a genuine different-peer capacity
11966    /// eviction (the ADR promises capacity loss is observable).
11967    #[test]
11968    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
11969        let obs = Arc::new(FirstAuditObservability::default());
11970        let mono = Instant::now();
11971        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11972        // Pending capacity 1 so a requeue of a different peer must evict.
11973        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11974        let reserved_peer = test_peer(1);
11975        let other_peer = test_peer(2);
11976
11977        // Reserve peer 1.
11978        scheduler.enqueue(
11979            MonetizedPinEvent {
11980                peer: reserved_peer,
11981                pin: [1; 32],
11982                key_count: 100,
11983                quote_ts: SystemTime::now(),
11984            },
11985            &obs,
11986        );
11987        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11988        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11989
11990        // A DIFFERENT peer fills the single pending slot during the reservation.
11991        scheduler.enqueue(
11992            MonetizedPinEvent {
11993                peer: other_peer,
11994                pin: [2; 32],
11995                key_count: 100,
11996                quote_ts: SystemTime::now(),
11997            },
11998            &obs,
11999        );
12000        assert_eq!(scheduler.pending_len(), 1);
12001
12002        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12003        let reservation = scheduler.take_due_reservation(mono).expect("due");
12004        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12005        cooldown.insert(reserved_peer, mono);
12006        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12007        assert!(scheduler
12008            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12009            .is_none());
12010        assert_eq!(
12011            obs.capacity_evicted.load(Ordering::Relaxed),
12012            cap_before + 1,
12013            "the requeue eviction of a different peer is counted"
12014        );
12015        assert_eq!(
12016            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12017            Some([1; 32])
12018        );
12019    }
12020
12021    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12022    /// nomination arriving while an inflated pin is PENDING must not displace it.
12023    /// The inflated pin stays and is the one launched.
12024    #[test]
12025    fn first_audit_pending_lower_count_does_not_replace_higher() {
12026        let obs = Arc::new(FirstAuditObservability::default());
12027        let mono = Instant::now();
12028        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12029        let peer = test_peer(1);
12030
12031        // Inflated (high-count) sidecar pin lands in pending.
12032        scheduler.enqueue(
12033            MonetizedPinEvent {
12034                peer,
12035                pin: [1; 32],
12036                key_count: 400,
12037                quote_ts: SystemTime::now(),
12038            },
12039            &obs,
12040        );
12041        // A cheaper same-peer settlement arrives right after.
12042        scheduler.enqueue(
12043            MonetizedPinEvent {
12044                peer,
12045                pin: [2; 32],
12046                key_count: 100,
12047                quote_ts: SystemTime::now(),
12048            },
12049            &obs,
12050        );
12051
12052        assert_eq!(scheduler.pending_len(), 1);
12053        assert_eq!(
12054            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12055            Some(([1; 32], 400)),
12056            "the inflated pin must not be erased by the cheaper successor"
12057        );
12058        // The dropped cheaper nomination is counted through the enqueue path.
12059        assert_eq!(
12060            obs.suppressed_lower.load(Ordering::Relaxed),
12061            1,
12062            "the attempted cheaper-pin self-erasure is observable"
12063        );
12064
12065        // It reserves and promotes as the inflated pin/count.
12066        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12067        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12068        let reservation = scheduler.take_due_reservation(mono).expect("due");
12069        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12070        let (event, _slot) = scheduler
12071            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12072            .expect("promotes");
12073        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12074    }
12075
12076    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12077    /// loses the cooldown race must be requeued OVER a lower-count same-peer
12078    /// successor that arrived during its jitter, and must remain launchable once
12079    /// the shared cooldown expires — the cheaper successor cannot suppress it.
12080    #[test]
12081    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12082        let obs = Arc::new(FirstAuditObservability::default());
12083        let mono = Instant::now();
12084        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12085        let peer = test_peer(1);
12086
12087        // Reserve the inflated pin.
12088        scheduler.enqueue(
12089            MonetizedPinEvent {
12090                peer,
12091                pin: [1; 32],
12092                key_count: 400,
12093                quote_ts: SystemTime::now(),
12094            },
12095            &obs,
12096        );
12097        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12098        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12099
12100        // A cheaper successor arrives during the reservation (bypasses the
12101        // window as the reserved peer) and sits in pending.
12102        scheduler.enqueue(
12103            MonetizedPinEvent {
12104                peer,
12105                pin: [2; 32],
12106                key_count: 100,
12107                quote_ts: SystemTime::now(),
12108            },
12109            &obs,
12110        );
12111        assert_eq!(scheduler.pending_len(), 1);
12112
12113        // Resolve: answerability passes but the shared cooldown is already
12114        // stamped, so the reservation loses the race and requeues.
12115        let reservation = scheduler.take_due_reservation(mono).expect("due");
12116        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12117        cooldown.insert(peer, mono);
12118        assert!(scheduler
12119            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12120            .is_none());
12121
12122        // The inflated pin (400) replaced the cheaper successor (100).
12123        assert_eq!(scheduler.pending_len(), 1);
12124        assert_eq!(
12125            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12126            Some(([1; 32], 400)),
12127            "the inflated reserved pin must survive the requeue over the cheaper successor"
12128        );
12129        assert!(scheduler.first_audited.is_empty());
12130        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12131
12132        // Once the shared cooldown expires, the inflated pin reserves and
12133        // promotes with its intended pin/count.
12134        let later = mono
12135            .checked_add(Duration::from_secs(
12136                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12137            ))
12138            .expect("later");
12139        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12140        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12141        let reservation = scheduler.take_due_reservation(later).expect("due");
12142        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12143        let (event, _slot) = scheduler
12144            .resolve(
12145                reservation,
12146                SystemTime::now(),
12147                later,
12148                &mut cooldown_later,
12149                &obs,
12150            )
12151            .expect("promotes after cooldown");
12152        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12153    }
12154
12155    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12156    /// launch lane, driven through the real scheduler (reserve -> resolve ->
12157    /// promote), so a stream of fresh nominations cannot keep every launch on
12158    /// the newest lane and starve the oldest.
12159    #[test]
12160    fn first_audit_lane_alternates_across_promotions() {
12161        let obs = Arc::new(FirstAuditObservability::default());
12162        let mono = Instant::now();
12163        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12164        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12165
12166        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12167        let oldest_peer = test_peer(1);
12168        let newest_peer = test_peer(2);
12169        scheduler.enqueue(
12170            MonetizedPinEvent {
12171                peer: oldest_peer,
12172                pin: [1; 32],
12173                key_count: 100,
12174                quote_ts: SystemTime::now(),
12175            },
12176            &obs,
12177        );
12178        scheduler.enqueue(
12179            MonetizedPinEvent {
12180                peer: newest_peer,
12181                pin: [2; 32],
12182                key_count: 100,
12183                quote_ts: SystemTime::now(),
12184            },
12185            &obs,
12186        );
12187
12188        let mut launched_peers = Vec::new();
12189        for _ in 0..2 {
12190            assert!(scheduler.try_reserve(
12191                mono,
12192                obs.inflight.load(Ordering::Relaxed),
12193                Duration::ZERO,
12194                &cooldown,
12195                &obs
12196            ));
12197            let reservation = scheduler.take_due_reservation(mono).expect("due");
12198            // Answerable wall time == the quote's own time (age 0).
12199            let (event, _slot) = scheduler
12200                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12201                .expect("fresh in-window quote promotes");
12202            launched_peers.push(event.peer);
12203        }
12204
12205        // First launch takes the newest lane (lane starts false = newest), the
12206        // second takes the oldest lane: strict alternation.
12207        assert_eq!(
12208            launched_peers,
12209            vec![newest_peer, oldest_peer],
12210            "consecutive promotions alternate newest-then-oldest lane"
12211        );
12212    }
12213
12214    #[test]
12215    fn first_audit_count_jump_boundaries() {
12216        // Exactly 1.5x is NOT a jump; strictly above is.
12217        assert!(!first_audit_count_jump(100, 150));
12218        assert!(first_audit_count_jump(100, 151));
12219        // Anything beats an audited zero; zero never jumps.
12220        assert!(first_audit_count_jump(0, 1));
12221        assert!(!first_audit_count_jump(0, 0));
12222        // Equal max counts must not jump (and must not overflow).
12223        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12224    }
12225
12226    /// A verified payment's quote list includes the local node's own quote, so
12227    /// the verifier emits a monetized-pin event for the local peer on every
12228    /// payment it verifies. The node cannot network-audit itself, so the
12229    /// scheduler must drop such an event at ingress: never queued, and hence
12230    /// never launched nor marked first-audited.
12231    #[test]
12232    fn first_audit_queue_drops_self_targeting_events() {
12233        let obs = Arc::new(FirstAuditObservability::default());
12234        let self_peer = test_peer(1);
12235        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12236        let self_event = MonetizedPinEvent {
12237            peer: self_peer,
12238            pin: [7; 32],
12239            key_count: 1,
12240            quote_ts: SystemTime::now(),
12241        };
12242
12243        scheduler.enqueue(self_event, &obs);
12244        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12245        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12246        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12247
12248        // A remote peer's event still queues normally under the same filter.
12249        let remote_event = MonetizedPinEvent {
12250            peer: test_peer(2),
12251            pin: [8; 32],
12252            ..self_event
12253        };
12254        scheduler.enqueue(remote_event, &obs);
12255        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12256        assert_eq!(scheduler.pending_len(), 1);
12257        assert_eq!(
12258            obs.self_target_skipped.load(Ordering::Relaxed),
12259            1,
12260            "remote event must not count as a self-target skip"
12261        );
12262    }
12263
12264    #[test]
12265    fn fresh_offer_runs_store_admission_payment_checks() {
12266        let context = fresh_offer_payment_context();
12267        assert_eq!(context, VerificationContext::FreshReplication);
12268        // Fresh replication must keep verifying exactly like a direct client
12269        // PUT (store-strength cache, same live checks); the variant only
12270        // exists so price-floor telemetry can tell the two paths apart.
12271        assert!(context.is_store_admission());
12272    }
12273
12274    #[test]
12275    fn paid_notify_uses_paid_list_admission_payment_checks() {
12276        assert_eq!(
12277            paid_notify_payment_context(),
12278            VerificationContext::PaidListAdmission
12279        );
12280    }
12281
12282    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12283    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12284    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12285    #[test]
12286    fn monetized_quote_audit_window_fails_closed_both_ends() {
12287        let now = SystemTime::now();
12288        // Fresh (just quoted) and small future/past skew -> audited.
12289        assert!(quote_within_audit_window(now, now));
12290        assert!(quote_within_audit_window(
12291            now + Duration::from_secs(60),
12292            now
12293        ));
12294        assert!(quote_within_audit_window(
12295            now - Duration::from_secs(3600),
12296            now
12297        ));
12298        // Far future (badly-skewed / replayed) -> skipped.
12299        assert!(!quote_within_audit_window(
12300            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12301            now
12302        ));
12303        // Older than the window -> skipped (pin may have aged out).
12304        assert!(!quote_within_audit_window(
12305            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12306            now
12307        ));
12308    }
12309
12310    #[tokio::test]
12311    async fn replication_branch_lagged_events_are_counted() {
12312        let before = audit_metrics::replication_event_lagged_total();
12313        let flow = handle_replication_event_recv_error(
12314            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12315        );
12316        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12317        let after = audit_metrics::replication_event_lagged_total();
12318        assert_eq!(after.saturating_sub(before), 3);
12319    }
12320
12321    #[tokio::test]
12322    async fn replication_branch_closed_events_stop_the_loop() {
12323        let flow =
12324            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12325        assert_eq!(flow, std::ops::ControlFlow::Break(()));
12326    }
12327
12328    #[tokio::test]
12329    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12330        let (sender, mut receiver) = mpsc::channel(1);
12331        let dropped_body =
12332            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12333                keys: Vec::new(),
12334                paid_list_check_indices: Vec::new(),
12335            });
12336        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12337        let first = InboundReplicationMessage {
12338            source: test_peer(0xC1),
12339            msg: ReplicationMessage {
12340                request_id: 1,
12341                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12342                    key: test_key(1),
12343                }),
12344            },
12345            rr_message_id: None,
12346            received_at: Instant::now(),
12347        };
12348        let second = InboundReplicationMessage {
12349            source: test_peer(0xC2),
12350            msg: ReplicationMessage {
12351                request_id: 2,
12352                body: dropped_body.clone(),
12353            },
12354            rr_message_id: None,
12355            received_at: Instant::now(),
12356        };
12357
12358        assert!(try_enqueue_serial_message(&sender, first).is_ok());
12359        let dropped = try_enqueue_serial_message(&sender, second)
12360            .expect_err("a full serial queue must refuse the second message");
12361        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12362        assert_eq!(dropped.message_class, "verification_request");
12363        assert_eq!(dropped.queue_depth, 1);
12364        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12365        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12366
12367        let queued = receiver
12368            .recv()
12369            .await
12370            .expect("first message should remain queued");
12371        assert_eq!(queued.msg.request_id, 1);
12372        assert!(receiver.try_recv().is_err());
12373    }
12374
12375    #[tokio::test]
12376    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12377        let peer = test_peer(0x44);
12378        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12379
12380        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12381        let mut digest_guards = Vec::new();
12382        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12383            let guard = admit_audit_responder(
12384                &semaphore,
12385                &digest_inflight,
12386                &peer,
12387                AuditResponderClass::Digest,
12388            )
12389            .await;
12390            assert!(guard.is_ok());
12391            digest_guards.push(guard);
12392        }
12393        assert!(
12394            admit_audit_responder(
12395                &semaphore,
12396                &digest_inflight,
12397                &peer,
12398                AuditResponderClass::Digest,
12399            )
12400            .await
12401            .is_err(),
12402            "digest class must stop at its documented per-source cap"
12403        );
12404        drop(digest_guards);
12405
12406        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12407        let mut subtree_guards = Vec::new();
12408        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12409            let guard = admit_audit_responder(
12410                &semaphore,
12411                &subtree_inflight,
12412                &peer,
12413                AuditResponderClass::Subtree,
12414            )
12415            .await;
12416            assert!(guard.is_ok());
12417            subtree_guards.push(guard);
12418        }
12419        assert!(
12420            admit_audit_responder(
12421                &semaphore,
12422                &subtree_inflight,
12423                &peer,
12424                AuditResponderClass::Subtree,
12425            )
12426            .await
12427            .is_err(),
12428            "subtree class must retain the deployed cap of two"
12429        );
12430        drop(subtree_guards);
12431    }
12432
12433    #[test]
12434    fn in_scope_audit_deadlines_share_one_formula() {
12435        let config = config::ReplicationConfig::default();
12436        for key_count in [1, 4, 16] {
12437            assert_eq!(
12438                audit::responsible_audit_response_timeout(&config, key_count),
12439                config.audit_response_timeout(key_count)
12440            );
12441            assert_eq!(
12442                pruning::prune_audit_response_timeout(&config, key_count),
12443                config.audit_response_timeout(key_count)
12444            );
12445        }
12446        assert_eq!(
12447            possession::possession_probe_response_timeout(&config),
12448            config.audit_response_timeout(1)
12449        );
12450    }
12451
12452    #[test]
12453    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12454        const EXISTING_SOURCE_ID: u8 = 1;
12455        const HINT_SENDER_ID: u8 = 2;
12456
12457        let existing_source = test_peer(EXISTING_SOURCE_ID);
12458        let hint_sender = test_peer(HINT_SENDER_ID);
12459        let mut sources = vec![existing_source];
12460
12461        let hint_sources = HashSet::from([hint_sender]);
12462        add_replica_hint_sources(&mut sources, &hint_sources);
12463        add_replica_hint_sources(&mut sources, &hint_sources);
12464
12465        // A paid-only advertiser leaves the claim set empty (see
12466        // `queue_admitted_hints`), so it contributes no fetch source.
12467        add_replica_hint_sources(&mut sources, &HashSet::new());
12468
12469        assert_eq!(sources, vec![existing_source, hint_sender]);
12470    }
12471
12472    #[test]
12473    fn audit_timeout_preserves_active_bootstrap_claim() {
12474        assert!(!audit_failure_clears_bootstrap_claim(
12475            &AuditFailureReason::Timeout
12476        ));
12477    }
12478
12479    fn strike_peer(b: u8) -> PeerId {
12480        let mut bytes = [0u8; 32];
12481        bytes[0] = b;
12482        PeerId::from_bytes(bytes)
12483    }
12484
12485    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12486    // cooldown must collapse a gossip flood into at most one audit per window.
12487
12488    #[test]
12489    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12490        let peer = strike_peer(1);
12491        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12492        let t0 = Instant::now();
12493        // First gossip in the window passes; a burst of further gossips at the
12494        // same instant are all suppressed.
12495        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12496        let mut passed = 1;
12497        for _ in 0..100 {
12498            if cooldown_allows_audit(&mut map, &peer, t0) {
12499                passed += 1;
12500            }
12501        }
12502        assert_eq!(
12503            passed, 1,
12504            "a flood at one instant must trigger exactly one audit"
12505        );
12506    }
12507
12508    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12509    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12510    // consumes the window. This is the property the isolated cooldown tests above
12511    // cannot see: they never sample the lottery, so a regression that reordered
12512    // the gates (sample probability first, only stamp the cooldown on a win)
12513    // would still pass them while breaking flood-resistance: a flood would then
12514    // re-roll the lottery on EVERY message until one won, multiplying audits.
12515    //
12516    // We model the exact production gate order (attempt-window, lottery,
12517    // shared cooldown) with a lottery driven by a fixed outcome instead of
12518    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
12519    // messages all WIN. With the production order, the losing first ticket
12520    // burns the ATTEMPT window and every later winner in the same window is
12521    // blocked, so there are 0 audits this window. If the gates were flipped,
12522    // the second message's winning ticket would slip through. The window only
12523    // reopens after it elapses.
12524    //
12525    // FLIPS IF: the lottery is sampled before the attempt-window
12526    // check-and-stamp (a losing ticket no longer consumes the window),
12527    // re-enabling a flood-amplified audit storm.
12528    #[test]
12529    fn losing_lottery_still_consumes_attempt_window() {
12530        // Calls the SHIPPED `audit_launch_decision` (the same function
12531        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
12532        // production fails this test — not a local reimplementation.
12533        let peer = strike_peer(3);
12534        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12535        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12536        let t0 = Instant::now();
12537
12538        // First flooded message at t0 LOSES the lottery, but the attempt window
12539        // is stamped BEFORE the lottery is consulted, so the window is consumed.
12540        assert!(
12541            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12542            "a losing ticket launches no audit"
12543        );
12544
12545        // 99 more flooded messages at the same instant would all WIN the lottery,
12546        // yet every one must be blocked by the attempt window the loser stamped.
12547        // (If production sampled the lottery FIRST, these would each get a fresh
12548        // roll and audits would multiply — this assertion catches that reorder.)
12549        let mut audits = 0;
12550        for _ in 0..99 {
12551            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12552                audits += 1;
12553            }
12554        }
12555        assert_eq!(
12556            audits, 0,
12557            "a losing first ticket must consume the attempt window so no later \
12558             flooded message in the same window can audit"
12559        );
12560
12561        // The window only reopens after it elapses; the next winning ticket
12562        // then launches exactly one audit and stamps the SHARED cooldown.
12563        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12564        assert!(
12565            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12566            "after the window a winning ticket audits again"
12567        );
12568        assert!(
12569            launched.contains_key(&peer),
12570            "a real launch stamps the shared cooldown"
12571        );
12572    }
12573
12574    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
12575    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
12576    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
12577    /// first audit deferred until its answerability window expires.
12578    ///
12579    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
12580    /// loss (the pre-split behavior, where both paths shared one map).
12581    #[test]
12582    fn losing_lottery_does_not_suppress_monetized_first_audit() {
12583        let peer = strike_peer(4);
12584        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12585        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12586        let t0 = Instant::now();
12587
12588        // A losing ticket consumes the gossip attempt window...
12589        assert!(!audit_launch_decision(
12590            &mut attempts,
12591            &mut launched,
12592            &peer,
12593            t0,
12594            false
12595        ));
12596        // ...but leaves the shared map untouched, so the first-audit reserve
12597        // gate (read-only) and the authoritative promotion check-and-stamp both
12598        // still allow the paid audit to launch immediately.
12599        assert!(
12600            cooldown_would_allow(&launched, &peer, t0),
12601            "reserve gate must not see a losing ticket as audit coverage"
12602        );
12603        assert!(
12604            cooldown_allows_audit(&mut launched, &peer, t0),
12605            "promotion must not be deferred by a losing ticket"
12606        );
12607
12608        // Conversely a WINNING ticket (real audit sent) does suppress the
12609        // first audit for the window, which is the intended shared semantics.
12610        let peer_won = strike_peer(5);
12611        assert!(audit_launch_decision(
12612            &mut attempts,
12613            &mut launched,
12614            &peer_won,
12615            t0,
12616            true
12617        ));
12618        assert!(
12619            !cooldown_would_allow(&launched, &peer_won, t0),
12620            "a real gossip audit still covers the peer for the window"
12621        );
12622    }
12623
12624    #[test]
12625    fn cooldown_lets_audit_through_after_the_window() {
12626        let peer = strike_peer(2);
12627        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12628        let t0 = Instant::now();
12629        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12630        // Within the window: suppressed.
12631        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12632        assert!(!cooldown_allows_audit(&mut map, &peer, within));
12633        // Past the window: allowed again.
12634        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12635        assert!(cooldown_allows_audit(&mut map, &peer, after));
12636    }
12637
12638    #[test]
12639    fn cooldown_is_per_peer_independent() {
12640        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12641        let t0 = Instant::now();
12642        // Different peers each get their own first-audit pass at the same instant.
12643        for i in 0..20u8 {
12644            assert!(
12645                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12646                "peer {i} should be auditable independently"
12647            );
12648        }
12649    }
12650
12651    #[test]
12652    fn audit_on_gossip_constants_match_adr() {
12653        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
12654        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
12655        // values above 5 would silently never be requested).
12656        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12657        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12658        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12659    }
12660
12661    // (d) A confirmed storage-integrity failure penalizes immediately and
12662    // revokes credit; it is not a timeout.
12663    #[test]
12664    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12665        assert!(audit_failure_clears_bootstrap_claim(
12666            &AuditFailureReason::DigestMismatch
12667        ));
12668        assert!(audit_failure_revokes_holder_credit(
12669            &AuditFailureReason::DigestMismatch
12670        ));
12671    }
12672
12673    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
12674    /// uses: confirmed failures revoke credit, `Timeout` does not.
12675    #[test]
12676    fn confirmed_failures_revoke_credit_timeout_does_not() {
12677        for reason in [
12678            AuditFailureReason::MalformedResponse,
12679            AuditFailureReason::DigestMismatch,
12680            AuditFailureReason::KeyAbsent,
12681            AuditFailureReason::Rejected,
12682        ] {
12683            assert!(
12684                audit_failure_revokes_holder_credit(&reason),
12685                "confirmed failure {reason:?} must revoke holder credit"
12686            );
12687        }
12688        assert!(
12689            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12690            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12691        );
12692    }
12693
12694    /// Wiring test for the security fix: the helper the handler calls
12695    /// actually strips a credited peer on a confirmed failure
12696    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
12697    /// Records genuine credit first so neither assertion is vacuous;
12698    /// this fails if `forget_peer` stops being called, or if the
12699    /// `Timeout` exclusion is dropped (both verified by mutation).
12700    #[test]
12701    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12702        let peer = test_peer(0xAB);
12703        let key = test_key(1);
12704        let hash = [0xCD; 32];
12705
12706        // Confirmed failure -> credit revoked.
12707        let mut provers = RecentProvers::new();
12708        provers.record_proof(key, peer, hash, Instant::now());
12709        assert!(
12710            provers.is_credited_holder(&key, &peer, &hash),
12711            "precondition: peer credited before failure"
12712        );
12713        apply_audit_failure_credit_revocation(
12714            &mut provers,
12715            &peer,
12716            &AuditFailureReason::DigestMismatch,
12717        );
12718        assert!(
12719            !provers.is_credited_holder(&key, &peer, &hash),
12720            "DigestMismatch must strip the peer's holder credit"
12721        );
12722
12723        // Timeout -> credit retained.
12724        let mut provers_timeout = RecentProvers::new();
12725        provers_timeout.record_proof(key, peer, hash, Instant::now());
12726        apply_audit_failure_credit_revocation(
12727            &mut provers_timeout,
12728            &peer,
12729            &AuditFailureReason::Timeout,
12730        );
12731        assert!(
12732            provers_timeout.is_credited_holder(&key, &peer, &hash),
12733            "Timeout must retain holder credit (deliberate liveness cushion)"
12734        );
12735    }
12736
12737    #[test]
12738    fn decoded_audit_failures_clear_active_bootstrap_claim() {
12739        for reason in [
12740            AuditFailureReason::MalformedResponse,
12741            AuditFailureReason::DigestMismatch,
12742            AuditFailureReason::KeyAbsent,
12743            AuditFailureReason::Rejected,
12744        ] {
12745            assert!(
12746                audit_failure_clears_bootstrap_claim(&reason),
12747                "decoded non-bootstrap failure {reason:?} should clear active claim"
12748            );
12749        }
12750    }
12751
12752    #[test]
12753    fn first_failed_key_label_truncates_to_16_hex_chars() {
12754        // The high-order 8 bytes of the XorName determine the label so an
12755        // operator can group audit-failures on the same chunk prefix.
12756        let mut key = [0u8; 32];
12757        key[0] = 0x18;
12758        key[7] = 0xff;
12759        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
12760        // to verify they are NOT included in the label.
12761        for byte in &mut key[8..] {
12762            *byte = 0xAA;
12763        }
12764        let label = first_failed_key_label(&[key]);
12765        // Only the first 8 bytes are encoded, low-order bytes are dropped.
12766        assert_eq!(label, "0x18000000000000ff");
12767        assert_eq!(label.len(), "0x".len() + 16);
12768    }
12769
12770    #[test]
12771    fn first_failed_key_label_falls_back_when_empty() {
12772        // Should never happen in production (audit failure handling rejects
12773        // empty sets), but the formatter must still produce a valid label
12774        // so the log line doesn't contain a misleading default.
12775        assert_eq!(first_failed_key_label(&[]), "0x");
12776    }
12777
12778    #[test]
12779    fn first_failed_key_label_uses_first_key_only() {
12780        let first = [0x11u8; 32];
12781        let second = [0x22u8; 32];
12782        assert_eq!(
12783            first_failed_key_label(&[first, second]),
12784            format!("0x{}", hex::encode(&first[..8]))
12785        );
12786    }
12787
12788    // -- apply_fetch_result --------------------------------------------------
12789    //
12790    // The worker's disposition of a fetch outcome. Note there is no trust
12791    // handle in `apply_fetch_result`'s signature: the worker cannot report a
12792    // trust event for ANY outcome, and `execute_single_fetch` returns
12793    // `NoLongerResponsible` before its trust-reporting paths — the source did
12794    // nothing wrong when this node's own responsibility lapsed.
12795
12796    /// Route `key` through the real pipeline stages (pending → promoted →
12797    /// dequeued → in-flight) so it carries a verification retry-slot
12798    /// reservation, exactly as a worker-dequeued key does. Returns the
12799    /// in-flight source.
12800    fn drive_key_in_flight(
12801        q: &mut ReplicationQueues,
12802        key: XorName,
12803        sources: Vec<PeerId>,
12804    ) -> PeerId {
12805        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
12806        let now = Instant::now();
12807        let entry = VerificationEntry {
12808            state: VerificationState::PendingVerify,
12809            verified_sources: Vec::new(),
12810            tried_sources: HashSet::new(),
12811            created_at: now,
12812            next_verify_at: now,
12813            hint_sources: HashSet::from([hinter]),
12814            replica_hint_sources: HashSet::from([hinter]),
12815        };
12816        assert!(q.add_pending_verify(key, entry).admitted());
12817        assert!(q.promote_pending_to_fetch(key, key, sources));
12818        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
12819        let source = *candidate.sources.first().expect("candidate has a source");
12820        q.start_dequeued_fetch(candidate, source);
12821        source
12822    }
12823
12824    #[test]
12825    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
12826        const RETRY_AFTER: Duration = Duration::from_secs(60);
12827
12828        let mut q = ReplicationQueues::new();
12829        let key = test_key(0xAB);
12830        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
12831        assert_eq!(q.retry_reserved_slot_count(), 1);
12832
12833        let follow_up =
12834            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
12835
12836        assert_eq!(
12837            follow_up,
12838            FetchFollowUp::Terminal,
12839            "lapsed responsibility must run the caller's terminal bootstrap accounting"
12840        );
12841        assert!(
12842            !q.contains_key(&key),
12843            "the key must leave every pipeline stage — alternate sources included"
12844        );
12845        assert_eq!(
12846            q.pending_count(),
12847            0,
12848            "a lapsed-responsibility key must not be requeued for verification"
12849        );
12850        assert_eq!(
12851            q.retry_reserved_slot_count(),
12852            0,
12853            "terminal exit must release the verification retry-slot reservation"
12854        );
12855    }
12856
12857    #[test]
12858    fn no_longer_responsible_shares_the_stored_terminal_path() {
12859        const RETRY_AFTER: Duration = Duration::from_secs(60);
12860
12861        // Both variants must walk the identical terminal gate so the
12862        // battle-tested Stored accounting (retry-slot release + bootstrap
12863        // pending-set shrink in the caller) covers lapsed responsibility too.
12864        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
12865            let mut q = ReplicationQueues::new();
12866            let key = test_key(0xCD);
12867            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
12868
12869            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
12870
12871            assert_eq!(follow_up, FetchFollowUp::Terminal);
12872            assert!(!q.contains_key(&key));
12873            assert_eq!(q.retry_reserved_slot_count(), 0);
12874        }
12875    }
12876
12877    #[test]
12878    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
12879        const RETRY_AFTER: Duration = Duration::from_secs(60);
12880
12881        let mut q = ReplicationQueues::new();
12882        let key = test_key(0xEF);
12883        let first = test_peer(0x04);
12884        let second = test_peer(0x05);
12885        drive_key_in_flight(&mut q, key, vec![first, second]);
12886
12887        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12888        assert_eq!(
12889            follow_up,
12890            FetchFollowUp::RetryFrom(second),
12891            "a failed source must not abandon the remaining verified sources"
12892        );
12893        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
12894
12895        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12896        assert_eq!(
12897            follow_up,
12898            FetchFollowUp::RequeuedForVerification,
12899            "exhausted sources must restore the reserved verification entry"
12900        );
12901        assert_eq!(q.pending_count(), 1);
12902        assert_eq!(
12903            q.retry_reserved_slot_count(),
12904            0,
12905            "the reservation converts back into the pending entry itself"
12906        );
12907    }
12908
12909    #[test]
12910    fn source_failure_without_retry_metadata_is_terminal() {
12911        const RETRY_AFTER: Duration = Duration::from_secs(60);
12912
12913        // Direct enqueue (no pending entry) models a fetch with no
12914        // verification retry reservation to restore.
12915        let mut q = ReplicationQueues::new();
12916        let key = test_key(0x1F);
12917        let source = test_peer(0x06);
12918        assert!(q.enqueue_fetch(key, key, vec![source]));
12919        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12920        q.start_dequeued_fetch(candidate, source);
12921
12922        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12923
12924        assert_eq!(follow_up, FetchFollowUp::Terminal);
12925        assert!(!q.contains_key(&key));
12926    }
12927
12928    #[test]
12929    fn already_held_key_leaves_the_pipeline_terminally() {
12930        const RETRY_AFTER: Duration = Duration::from_secs(60);
12931
12932        let mut q = ReplicationQueues::new();
12933        let key = test_key(0x4C);
12934        let source = test_peer(0x0B);
12935        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
12936
12937        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
12938
12939        assert_eq!(
12940            follow_up,
12941            FetchFollowUp::Terminal,
12942            "holding the key already discharges the duty, so the key must leave \
12943             the pipeline exactly as a completed fetch does — requeueing it \
12944             would re-verify a key that needs nothing"
12945        );
12946        assert!(!q.contains_key(&key));
12947        assert_eq!(
12948            q.retry_reserved_slot_count(),
12949            0,
12950            "the terminal path must release the retry-slot reservation, or the \
12951             owner's verification budget leaks"
12952        );
12953    }
12954
12955    #[test]
12956    fn local_write_failure_does_not_conscript_the_remaining_sources() {
12957        const RETRY_AFTER: Duration = Duration::from_secs(60);
12958
12959        let mut q = ReplicationQueues::new();
12960        let key = test_key(0x2A);
12961        let first = test_peer(0x07);
12962        let second = test_peer(0x08);
12963        let third = test_peer(0x09);
12964        drive_key_in_flight(&mut q, key, vec![first, second, third]);
12965
12966        let follow_up =
12967            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
12968
12969        assert_eq!(
12970            follow_up,
12971            FetchFollowUp::RequeuedForVerification,
12972            "a local write failure must go straight back to verification: the two \
12973             untried sources would each re-upload the same chunk into the same \
12974             full disk, and neither of them did anything wrong"
12975        );
12976        assert_eq!(q.in_flight_count(), 0);
12977        assert_eq!(
12978            q.pending_count(),
12979            1,
12980            "the key must come back — capacity frees up, and a stranded key is \
12981             a replica this node silently stops owing"
12982        );
12983        assert_eq!(q.retry_reserved_slot_count(), 0);
12984    }
12985
12986    #[test]
12987    fn local_write_failure_without_retry_metadata_is_terminal() {
12988        const RETRY_AFTER: Duration = Duration::from_secs(60);
12989
12990        // No pending entry to restore, so the only way not to strand the key
12991        // in `in_flight_fetch` forever — which would also stall bootstrap
12992        // drain — is the terminal path.
12993        let mut q = ReplicationQueues::new();
12994        let key = test_key(0x3B);
12995        let source = test_peer(0x0A);
12996        assert!(q.enqueue_fetch(key, key, vec![source]));
12997        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12998        q.start_dequeued_fetch(candidate, source);
12999
13000        let follow_up =
13001            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13002
13003        assert_eq!(follow_up, FetchFollowUp::Terminal);
13004        assert!(!q.contains_key(&key));
13005        assert_eq!(q.retry_reserved_slot_count(), 0);
13006    }
13007}