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 bootstrap;
20pub mod commitment;
21pub mod commitment_state;
22pub mod config;
23pub mod fresh;
24pub mod neighbor_sync;
25pub mod paid_list;
26pub mod possession;
27pub mod protocol;
28pub mod pruning;
29pub mod quorum;
30pub mod recent_provers;
31pub mod scheduling;
32pub mod storage_commitment_audit;
33pub mod subtree;
34pub mod types;
35
36use std::collections::{HashMap, HashSet};
37use std::fmt;
38use std::num::NonZeroUsize;
39use std::path::{Path, PathBuf};
40use std::sync::atomic::{AtomicU64, Ordering};
41use std::sync::Arc;
42use std::time::{Duration, Instant, SystemTime};
43
44use lru::LruCache;
45use std::pin::Pin;
46
47use crate::logging::{debug, error, info, warn};
48use futures::stream::FuturesUnordered;
49use futures::{Future, StreamExt};
50use rand::rngs::StdRng;
51use rand::{Rng, SeedableRng};
52use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
53use tokio::task::JoinHandle;
54use tokio_util::sync::CancellationToken;
55
56use crate::ant_protocol::XorName;
57use crate::error::{Error, Result};
58use crate::payment::{PaymentVerifier, VerificationContext};
59use crate::replication::audit::AuditTickResult;
60use crate::replication::commitment::{commitment_hash, StorageCommitment};
61use crate::replication::commitment_state::{
62    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
63};
64use crate::replication::config::{
65    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
66    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS, REPLICATION_PROTOCOL_ID,
67};
68use crate::replication::paid_list::PaidList;
69use crate::replication::protocol::{
70    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
71    VerificationResponse,
72};
73use crate::replication::quorum::KeyVerificationOutcome;
74use crate::replication::recent_provers::RecentProvers;
75use crate::replication::scheduling::ReplicationQueues;
76use crate::replication::types::{
77    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence, HintPipeline,
78    NeighborSyncState, PeerSyncRecord, RepairProofs, VerificationEntry, VerificationState,
79};
80use crate::storage::LmdbStorage;
81use saorsa_core::identity::{NodeIdentity, PeerId};
82use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
83use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
84
85/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
86/// because it was full (Amendment 2). Process-global because the producer is
87/// the payment verifier (a different module) and the drop happens before the
88/// per-drainer `received` counter. A non-zero value is the rollout signal that
89/// nomination ingress is saturating — benign (penalty-free, lottery/next-
90/// payment covered) but worth watching. `Closed` (engine shut down) is not
91/// counted: it is not a saturation signal.
92static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
93
94/// Record one ingress-full drop. Called by the payment verifier's `try_send`
95/// sites; read by the drainer's periodic summary.
96pub(crate) fn note_monetized_ingress_drop() {
97    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
98}
99
100#[derive(Default)]
101struct FirstAuditObservability {
102    received: AtomicU64,
103    queued: AtomicU64,
104    coalesced: AtomicU64,
105    duplicates: AtomicU64,
106    capacity_evicted: AtomicU64,
107    /// An event targeting the local peer itself, dropped at ingress: the node
108    /// cannot network-audit itself (no dialable address for the local peer).
109    self_target_skipped: AtomicU64,
110    /// A strictly-lower-count same-peer nomination that was dropped so a
111    /// higher-count pending pin survived. A sustained rise is the signal of an
112    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
113    suppressed_lower: AtomicU64,
114    cooldown_deferred_attempts: AtomicU64,
115    rate_deferred_attempts: AtomicU64,
116    window_deduped: AtomicU64,
117    launched: AtomicU64,
118    passed: AtomicU64,
119    timed_out: AtomicU64,
120    failed: AtomicU64,
121    bootstrap_claims: AtomicU64,
122    idle: AtomicU64,
123    insufficient_keys: AtomicU64,
124    outside_answerability_window: AtomicU64,
125    inflight: AtomicU64,
126}
127
128/// Test-only snapshot of the first-audit scheduler counters.
129///
130/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
131/// self-targeting monetized pin was dropped and never launched) instead of
132/// scraping log lines.
133#[cfg(any(test, feature = "test-utils"))]
134#[derive(Debug, Clone, Copy)]
135pub struct FirstAuditStats {
136    /// Events ingested from the monetized-pin channel.
137    pub received: u64,
138    /// Events accepted into the pending first-audit queue.
139    pub queued: u64,
140    /// Events dropped because they targeted the local peer.
141    pub self_target_skipped: u64,
142    /// Audits launched.
143    pub launched: u64,
144    /// Launched audits that passed.
145    pub passed: u64,
146    /// Launched audits that timed out (non-response lane).
147    pub timed_out: u64,
148    /// Launched audits that ended in a confirmed failure.
149    pub failed: u64,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153enum FirstAuditTerminalOutcome {
154    Passed,
155    Timeout,
156    Failed,
157    BootstrapClaim,
158    Idle,
159    InsufficientKeys,
160}
161
162impl FirstAuditTerminalOutcome {
163    #[cfg(any(feature = "logging", test))]
164    const fn as_str(self) -> &'static str {
165        match self {
166            Self::Passed => "passed",
167            Self::Timeout => "timeout",
168            Self::Failed => "failed",
169            Self::BootstrapClaim => "bootstrap_claim",
170            Self::Idle => "idle",
171            Self::InsufficientKeys => "insufficient_keys",
172        }
173    }
174}
175
176fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
177    match result {
178        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
179        AuditTickResult::Failed {
180            evidence:
181                FailureEvidence::AuditFailure {
182                    reason: AuditFailureReason::Timeout,
183                    ..
184                },
185        } => FirstAuditTerminalOutcome::Timeout,
186        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
187        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
188        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
189        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
190    }
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194enum FirstAuditQueueOutcome {
195    /// New peer inserted with free capacity.
196    Queued,
197    /// Collapsed with an existing same-peer entry; the incoming won (higher
198    /// count, or equal count and newer) and replaced it.
199    Coalesced,
200    /// Collapsed with an existing same-peer entry; the incoming LOST because it
201    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
202    /// in place. This is the attempted cheaper-pin self-erasure signal.
203    SuppressedLower,
204    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
205    /// lost the freshness tie (it was not the newer of the two) and the
206    /// existing entry was retained. Benign, not an attack signal.
207    RetainedOnTie,
208    /// A DIFFERENT peer's entry was displaced from the capped pending queue
209    /// (random victim) to make room.
210    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
211}
212
213/// Coalesce a monetized nomination into the per-peer pending queue with a
214/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
215/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
216///
217/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
218/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
219/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
220/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
221/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
222/// cannot promote the retained pin's lane position.
223///
224/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
225/// last, so it wins an equal-count tie for freshness) from a cooldown-race
226/// requeue of an older reserved event (the pending successor is newer, so it
227/// wins the tie).
228fn coalesce_first_audit_event(
229    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
230    incoming: MonetizedPinEvent,
231    incoming_is_newer: bool,
232    rng: &mut StdRng,
233) -> FirstAuditQueueOutcome {
234    if let Some(existing) = pending.peek(&incoming.peer) {
235        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
236        // the retained pin's recency (the security-relevant self-erasure case).
237        if incoming.key_count < existing.key_count {
238            return FirstAuditQueueOutcome::SuppressedLower;
239        }
240        // Equal count -> keep the fresher; an older incoming loses a benign tie.
241        if incoming.key_count == existing.key_count && !incoming_is_newer {
242            return FirstAuditQueueOutcome::RetainedOnTie;
243        }
244        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
245        // the value and bumps MRU; replacing an existing key never evicts a
246        // different peer.
247        let _ = pending.push(incoming.peer, incoming);
248        return FirstAuditQueueOutcome::Coalesced;
249    }
250    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
251    // never the LRU: deterministic keep-newest would let an ordered batch of
252    // `cap` distinct-peer nominations flush a chosen target before any launch
253    // lane sees it, cutting the eviction cost from probabilistic to exact. A
254    // random victim caps an attacker's per-nomination eviction probability at
255    // `1/cap` regardless of arrival order or timing, so suppressing a specific
256    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
257    // nominations and is never certain (ADR-0004 Amendment 4).
258    if pending.len() >= pending.cap().get() {
259        let victim = {
260            let idx = rng.gen_range(0..pending.len());
261            pending.iter().nth(idx).map(|(p, _)| *p)
262        };
263        if let Some(victim_peer) = victim {
264            if let Some(evicted) = pending.pop(&victim_peer) {
265                let _ = pending.push(incoming.peer, incoming);
266                return FirstAuditQueueOutcome::CapacityEvicted {
267                    peer: victim_peer,
268                    pin: evicted.pin,
269                };
270            }
271        }
272    }
273    match pending.push(incoming.peer, incoming) {
274        None => FirstAuditQueueOutcome::Queued,
275        // Unreachable: the random-displacement branch above guarantees
276        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
277        // exists). Kept so any future logic error surfaces as an ACCOUNTED
278        // eviction rather than silent loss — but note this arm would be
279        // LRU-order, not random, so it must stay unreachable.
280        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
281            peer: evicted_peer,
282            pin: evicted.pin,
283        },
284    }
285}
286
287/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
288/// prefiltering a nomination's answerability at schedule time, covering the
289/// spawn/dispatch latency between the timer firing and the wire challenge so a
290/// jitter==MAX pin is not admitted only to fail the authoritative check by a
291/// few milliseconds. Tiny against the multi-hour answerability window.
292const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
293
294/// A first audit the limiter recently launched at a peer: when, and the
295/// committed key count that was audited (for the count-jump override).
296#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297struct RecentFirstAudit {
298    launched_at: Instant,
299    key_count: u32,
300}
301
302/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
303/// panicking or cancelled audit task can never leak a slot and wedge the
304/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
305struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
306
307impl FirstAuditInflightSlot {
308    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
309        observability.inflight.fetch_add(1, Ordering::Relaxed);
310        Self(Arc::clone(observability))
311    }
312}
313
314impl Drop for FirstAuditInflightSlot {
315    fn drop(&mut self) {
316        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
317    }
318}
319
320/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
321/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
322/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
323/// overflow-free integer math). A jump re-nominates a peer despite a recent
324/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
325/// only, so no gossip-lottery audit can ever cover it.
326const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
327    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
328        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
329}
330
331/// The launch limiter's verdict for one pending monetized pin.
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333enum LimiterVerdict {
334    /// Within budget and window: the caller may reserve a launch (and consumes
335    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
336    Admit,
337    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
338    /// pin pending and retry on a later tick.
339    RateDeferred,
340    /// The peer had a first audit within
341    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
342    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
343    /// gossip-lottery re-audit path is unaffected).
344    WindowDeduped,
345}
346
347/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
348/// (launch rate), an in-flight cap, and a per-peer re-audit window that
349/// survives pin rotation.
350///
351/// This is the load-bearing aggregate bound the original scheduler lacked:
352/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
353/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
354/// `now`/`inflight` values so every decision is unit-testable without a
355/// runtime.
356struct FirstAuditLimiter {
357    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
358    tokens: u32,
359    /// Refill anchor. While the bucket is full this tracks `now` (a full
360    /// bucket accrues nothing); while below capacity it advances only by
361    /// whole refill intervals so fractional elapsed time is never lost.
362    last_refill: Instant,
363    /// Peers given a first audit recently, with the audited key count.
364    /// Bounded like the drainer's other per-peer maps.
365    recent: LruCache<PeerId, RecentFirstAudit>,
366}
367
368impl FirstAuditLimiter {
369    fn new(now: Instant) -> Self {
370        Self {
371            tokens: config::FIRST_AUDIT_BUDGET_BURST,
372            last_refill: now,
373            recent: LruCache::new(
374                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
375            ),
376        }
377    }
378
379    /// Whether the per-peer re-audit window admits a nomination for `peer`
380    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
381    /// call at ENQUEUE time — suppressed nominations never occupy pending
382    /// slots — without disturbing LRU recency.
383    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
384        self.recent.peek(peer).map_or(true, |prev| {
385            now.saturating_duration_since(prev.launched_at)
386                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
387                || first_audit_count_jump(prev.key_count, key_count)
388        })
389    }
390
391    /// Refill the token bucket for the time elapsed up to `now`.
392    fn refill(&mut self, now: Instant) {
393        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
394            // Full bucket accrues nothing; keep the anchor current so the
395            // next consumption starts its interval from here.
396            self.last_refill = now;
397            return;
398        }
399        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
400        let elapsed = now.saturating_duration_since(self.last_refill);
401        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
402        if earned == 0 {
403            return;
404        }
405        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
406        if earned >= capacity_gap {
407            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
408            self.last_refill = now;
409        } else {
410            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
411            self.tokens = self
412                .tokens
413                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
414            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
415            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
416        }
417    }
418
419    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
420    /// caller runs the remaining (per-peer cooldown) gate and calls
421    /// [`Self::commit_launch`] only for a launch that actually happens, so a
422    /// deferral elsewhere never burns budget or stamps the window.
423    fn assess(
424        &mut self,
425        peer: &PeerId,
426        key_count: u32,
427        now: Instant,
428        inflight: u64,
429    ) -> LimiterVerdict {
430        if !self.window_allows(peer, key_count, now) {
431            return LimiterVerdict::WindowDeduped;
432        }
433        self.refill(now);
434        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
435            return LimiterVerdict::RateDeferred;
436        }
437        LimiterVerdict::Admit
438    }
439
440    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
441    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
442    /// only at [`Self::promote`], after the authoritative post-jitter
443    /// answerability check, so a reservation that is later cancelled leaves no
444    /// suppression behind.
445    fn reserve_token(&mut self) {
446        self.tokens = self.tokens.saturating_sub(1);
447    }
448
449    /// Return a token consumed by a reservation that was cancelled before it
450    /// launched (answerability lapsed or a concurrent gossip audit won the
451    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
452    /// the bucket.
453    fn refund_token(&mut self) {
454        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
455    }
456
457    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
458    /// (promotion). Separated from token consumption so suppression is only
459    /// ever recorded for a real send.
460    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
461        self.recent.put(
462            peer,
463            RecentFirstAudit {
464                launched_at: now,
465                key_count,
466            },
467        );
468    }
469
470    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
471    /// and stamp the window in one call. Production splits these across
472    /// reservation and promotion; the limiter's own budget/window unit tests do
473    /// not model the jitter reservation and use this shorthand.
474    #[cfg(test)]
475    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
476        self.reserve_token();
477        self.promote(peer, key_count, now);
478    }
479}
480
481/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
482/// across the ENTIRE launch-jitter window ending at
483/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
484/// for it cannot later require aborting an out-of-window challenge. The
485/// too-future bound is enforced at `now` (a jitter delay only ages a pin
486/// forward, never toward the future); the too-old bound is enforced at the
487/// latest possible send time. This is a conservative admission prefilter; the
488/// authoritative answerability check still runs at promotion against the real
489/// send-time wall clock, so A1 (no false conviction) holds regardless of how
490/// jitter and the answerability margin are sized. `checked_add` overflow fails
491/// closed (skip the pin).
492fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
493    let Some(latest_send) = now
494        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
495        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
496    else {
497        return false;
498    };
499    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
500}
501
502/// Open the single first-audit reservation from `pending` if none is
503/// outstanding: samples the launch jitter, snapshots the shared cooldown
504/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
505/// shared implementation for both drainer call sites — the per-wake launch
506/// phase and the pre-overflow opportunity inside the ingress batch — so the
507/// two cannot drift.
508async fn open_first_audit_reservation(
509    scheduler: &mut FirstAuditScheduler,
510    cooldown: &RwLock<HashMap<PeerId, Instant>>,
511    observability: &Arc<FirstAuditObservability>,
512) {
513    if scheduler.has_reservation() {
514        return;
515    }
516    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
517        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
518    ));
519    let inflight = observability.inflight.load(Ordering::Relaxed);
520    let reserved = {
521        let cooldown = cooldown.read().await;
522        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
523    };
524    if reserved {
525        if let Some(peer) = scheduler.reserved_peer() {
526            debug!(
527                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
528                scheduler.pending_len()
529            );
530        }
531    }
532}
533
534/// A far-future `Instant` used to effectively DISABLE the promotion-timer
535/// select arm when no reservation is outstanding. The drainer still wakes at
536/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
537/// needs to be comfortably past the next tick.
538fn first_audit_far_future() -> Instant {
539    Instant::now()
540        .checked_add(Duration::from_secs(3600))
541        .unwrap_or_else(Instant::now)
542}
543
544/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
545/// its in-flight slot and launch token from schedule time until the jitter
546/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
547/// only if the authoritative post-jitter answerability + cooldown checks pass at
548/// promotion, so a cancelled reservation leaves NO suppression behind.
549struct FirstAuditReservation {
550    event: MonetizedPinEvent,
551    ready_at: Instant,
552    inflight: FirstAuditInflightSlot,
553}
554
555/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
556/// pending queue, the dedup set, the launch limiter, the alternating lane, and
557/// the single outstanding reservation. All mutation is single-threaded in the
558/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
559/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
560/// state machine is unit-testable with injected clocks.
561struct FirstAuditScheduler {
562    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
563    /// (a real send), never at reservation, so a cancelled reservation can be
564    /// re-nominated.
565    first_audited: LruCache<[u8; 32], ()>,
566    /// Highest-count-per-peer pending nominations not yet launched. Capped at
567    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
568    /// one effective answerability window); at capacity a uniformly RANDOM
569    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
570    /// of a specific entry can never be forced deterministically. One further
571    /// entry may be held in `reserved` outside this queue — a deliberate
572    /// one-entry guard slot, so total schedulable occupancy is at most
573    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
574    pending: LruCache<PeerId, MonetizedPinEvent>,
575    /// Token bucket + per-peer re-audit window.
576    limiter: FirstAuditLimiter,
577    /// The single outstanding reservation (E′ serializes reservations so the
578    /// per-launch lane alternation is preserved and at most one jitter timer is
579    /// live).
580    reserved: Option<FirstAuditReservation>,
581    /// Alternating launch lane, flipped on every PROMOTION (real launch).
582    oldest_first_lane: bool,
583    /// The local node's own peer ID. A verified payment's quote list includes
584    /// the node's own quote, so the verifier emits a monetized-pin event for
585    /// the local peer on every payment it verifies. The node cannot
586    /// network-audit itself (there is no dialable address for the local peer,
587    /// so the challenge fails instantly and is miscounted as a timeout), while
588    /// any other payee that verifies the same payment schedules its own first
589    /// audit of this node's pin — a self-dial adds no coverage either way.
590    /// Such an event is dropped at ingress: never queued, and hence never
591    /// launched nor marked first-audited.
592    self_peer: PeerId,
593    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
594    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
595    /// production seeds from OS entropy at construction.
596    rng: StdRng,
597}
598
599impl FirstAuditScheduler {
600    fn new(now: Instant, self_peer: PeerId) -> Self {
601        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
602        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
603        Self {
604            first_audited: LruCache::new(dedup_cap),
605            pending: LruCache::new(pending_cap),
606            limiter: FirstAuditLimiter::new(now),
607            reserved: None,
608            oldest_first_lane: false,
609            self_peer,
610            rng: StdRng::from_entropy(),
611        }
612    }
613
614    /// Observability getter: used by the scheduler summary log and unit tests,
615    /// both absent from a release `--no-default-features` build, so it is dead
616    /// only in that configuration.
617    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
618    fn pending_len(&self) -> usize {
619        self.pending.len()
620    }
621
622    /// Observability getter (see [`Self::pending_len`]).
623    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
624    fn tokens(&self) -> u32 {
625        self.limiter.tokens
626    }
627
628    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
629    /// signed quote timestamp of the oldest pin still awaiting a first audit:
630    /// how close the longest-waiting pending pin is to aging out of the
631    /// answerability window. A value climbing toward the window means pending
632    /// work is expiring unaudited instead of launching; a small, steady value
633    /// means the queue is draining promptly. Returns `0` when `pending` is empty
634    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
635    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
636    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
637        self.pending
638            .iter()
639            .map(|(_, e)| e.quote_ts)
640            .min()
641            .and_then(|oldest| now.duration_since(oldest).ok())
642            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
643    }
644
645    /// Drop every pending nomination that has aged past the answerability
646    /// horizon. `try_reserve` collects expired entries only while it can scan —
647    /// under token starvation it returns at the budget gate first — so without
648    /// a periodic sweep dead entries squat the capped pending queue (displacing
649    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
650    /// telemetry. Each removal is accounted as `outside_answerability_window`,
651    /// exactly like a scan-time expiry. Returns how many entries were dropped;
652    /// survivor recency is untouched.
653    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
654        let expired: Vec<PeerId> = self
655            .pending
656            .iter()
657            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
658            .map(|(peer, _)| *peer)
659            .collect();
660        for peer in &expired {
661            self.pending.pop(peer);
662        }
663        if !expired.is_empty() {
664            obs.outside_answerability_window.fetch_add(
665                u64::try_from(expired.len()).unwrap_or(u64::MAX),
666                Ordering::Relaxed,
667            );
668        }
669        expired.len()
670    }
671
672    fn has_reservation(&self) -> bool {
673        self.reserved.is_some()
674    }
675
676    /// Whether admitting `event` would displace a DIFFERENT peer's pending
677    /// entry: the queue is at capacity and `event.peer` has no incumbent to
678    /// coalesce into. The drainer checks this before enqueueing so pending
679    /// work gets a reservation opportunity BEFORE destructive overflow
680    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
681    /// of `pending`, freeing the slot without any eviction.
682    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
683        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
684    }
685
686    /// When the outstanding reservation becomes eligible for promotion.
687    fn reserved_ready_at(&self) -> Option<Instant> {
688        self.reserved.as_ref().map(|r| r.ready_at)
689    }
690
691    /// The peer of the outstanding reservation, if any.
692    fn reserved_peer(&self) -> Option<PeerId> {
693        self.reserved.as_ref().map(|r| r.event.peer)
694    }
695
696    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
697    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
698    /// if already first-audited; the window screen is bypassed for the currently
699    /// reserved peer (so a successor is retained across the reservation, never
700    /// window-dropped); otherwise window-screened. Coalescing is
701    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
702    /// displaces a higher-count pending pin. An incumbent that has aged past
703    /// the answerability horizon is dropped (and accounted as an expiry) before
704    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
705    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
706    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
707    /// displacement is accounted as `capacity_evicted` and stamps no
708    /// suppression, so a displaced peer's next nomination is judged like any
709    /// newcomer. The drainer additionally offers a reservation opportunity
710    /// via [`Self::would_displace`] before calling this on an overflowing
711    /// arrival.
712    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
713        if event.peer == self.self_peer {
714            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
715            return;
716        }
717        if self.first_audited.contains(&event.pin) {
718            obs.duplicates.fetch_add(1, Ordering::Relaxed);
719            return;
720        }
721        let reserved_peer = self.reserved_peer();
722        let is_reserved_peer = reserved_peer == Some(event.peer);
723        if !is_reserved_peer
724            && !self
725                .limiter
726                .window_allows(&event.peer, event.key_count, Instant::now())
727        {
728            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
729            return;
730        }
731        // A pending incumbent past the answerability horizon can never launch,
732        // yet its (possibly higher) key count would still win the coalesce
733        // against a live incoming — e.g. a fresh post-prune lower-count pin —
734        // and under token starvation no reserve scan runs to collect it. Drop
735        // it first so the incoming is judged on its own merits.
736        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
737            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
738        });
739        if stale_incumbent {
740            self.pending.pop(&event.peer);
741            obs.outside_answerability_window
742                .fetch_add(1, Ordering::Relaxed);
743        }
744        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
745        // tie.
746        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
747            FirstAuditQueueOutcome::Queued => {
748                obs.queued.fetch_add(1, Ordering::Relaxed);
749            }
750            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
751                obs.coalesced.fetch_add(1, Ordering::Relaxed);
752            }
753            FirstAuditQueueOutcome::SuppressedLower => {
754                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
755            }
756            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
757                obs.queued.fetch_add(1, Ordering::Relaxed);
758                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
759            }
760        }
761    }
762
763    /// Attempt to create the single reservation from `pending` (E′ reserve).
764    /// Scans in the current lane order and reserves the FIRST eligible pin:
765    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
766    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
767    /// flip the lane — those happen only at promotion. Returns whether a
768    /// reservation was made. `cooldown` is a read-only snapshot (the
769    /// authoritative check-and-stamp is at promotion).
770    fn try_reserve(
771        &mut self,
772        mono_now: Instant,
773        inflight: u64,
774        jitter: Duration,
775        cooldown: &HashMap<PeerId, Instant>,
776        obs: &Arc<FirstAuditObservability>,
777    ) -> bool {
778        if self.reserved.is_some() || self.pending.is_empty() {
779            return false;
780        }
781        self.limiter.refill(mono_now);
782        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
783            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
784            return false;
785        }
786        // MRU->LRU order; reverse for the oldest-first lane so the preferred
787        // end is at the front.
788        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
789            .pending
790            .iter()
791            .enumerate()
792            .map(|(i, (p, e))| (i, *p, *e))
793            .collect();
794        self.pending.clear();
795        if self.oldest_first_lane {
796            ordered.reverse();
797        }
798        let mut chosen: Option<MonetizedPinEvent> = None;
799        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
800        for (idx, peer, event) in ordered {
801            if chosen.is_some() {
802                kept.push((idx, peer, event));
803                continue;
804            }
805            if self.first_audited.contains(&event.pin) {
806                obs.duplicates.fetch_add(1, Ordering::Relaxed);
807                continue; // drop: already audited
808            }
809            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
810                obs.outside_answerability_window
811                    .fetch_add(1, Ordering::Relaxed);
812                continue; // drop: cannot stay answerable through the jitter
813            }
814            // Window + budget + inflight. Tokens do not decrease during the
815            // scan (reserve happens after the loop) and `inflight` is fixed, so
816            // after the upfront budget gate `assess` never returns RateDeferred
817            // here; a defensive RateDeferred keeps the pin.
818            match self
819                .limiter
820                .assess(&peer, event.key_count, mono_now, inflight)
821            {
822                LimiterVerdict::WindowDeduped => {
823                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
824                    continue; // drop: recently first-audited, no count jump
825                }
826                LimiterVerdict::RateDeferred => {
827                    kept.push((idx, peer, event));
828                    continue; // keep (defensive; unreachable after upfront gate)
829                }
830                LimiterVerdict::Admit => {}
831            }
832            if !cooldown_would_allow(cooldown, &peer, mono_now) {
833                obs.cooldown_deferred_attempts
834                    .fetch_add(1, Ordering::Relaxed);
835                kept.push((idx, peer, event));
836                continue; // keep: on shared cooldown, retry later
837            }
838            chosen = Some(event);
839        }
840        // Restore relative recency (oldest re-put first -> newest stays MRU).
841        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
842        for (_, peer, event) in kept {
843            self.pending.put(peer, event);
844        }
845        let Some(event) = chosen else {
846            return false;
847        };
848        self.limiter.reserve_token();
849        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
850        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
851        self.reserved = Some(FirstAuditReservation {
852            event,
853            ready_at,
854            inflight: inflight_slot,
855        });
856        true
857    }
858
859    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
860    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
861        if self
862            .reserved
863            .as_ref()
864            .is_some_and(|r| mono_now >= r.ready_at)
865        {
866            self.reserved.take()
867        } else {
868            None
869        }
870    }
871
872    /// Authoritative promotion of a due reservation (E′). The caller holds the
873    /// shared cooldown write lock and passes the real send-time `wall_now` and
874    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
875    /// launch, or `None` when the launch was cancelled (answerability lapsed
876    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
877    /// On both `None` paths the token is refunded, the in-flight slot released,
878    /// and NO suppression is recorded.
879    ///
880    /// Known operational residual: suppression is stamped here, at promotion,
881    /// while the wire challenge is sent by the detached task the caller spawns
882    /// with the returned event. A task-start or encoding failure between the
883    /// two therefore leaves a stamped-but-unsent window. No remote input can
884    /// force that failure (it requires local task-spawn/alloc failure), so it
885    /// is accepted rather than closed; closing it would require stamping from
886    /// inside the spawned task and re-introduce the cancel-leaves-suppression
887    /// race this design exists to prevent.
888    fn resolve(
889        &mut self,
890        reservation: FirstAuditReservation,
891        wall_now: SystemTime,
892        mono_now: Instant,
893        cooldown: &mut HashMap<PeerId, Instant>,
894        obs: &Arc<FirstAuditObservability>,
895    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
896        let FirstAuditReservation {
897            event, inflight, ..
898        } = reservation;
899        // Authoritative answerability at the REAL send time.
900        if !quote_within_audit_window(event.quote_ts, wall_now) {
901            self.limiter.refund_token();
902            obs.outside_answerability_window
903                .fetch_add(1, Ordering::Relaxed);
904            drop(inflight);
905            return None; // cancelled; nothing stamped, nothing to roll back
906        }
907        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
908        // concurrent gossip audit requeues the reserved event through the SAME
909        // security-aware coalescing: the reserved event is OLDER than any
910        // same-peer successor (`incoming_is_newer = false`), so a higher-count
911        // reserved event still wins over a lower-count successor (the inflated
912        // pin must be audited), while an equal/higher successor is preserved.
913        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
914            self.limiter.refund_token();
915            obs.cooldown_deferred_attempts
916                .fetch_add(1, Ordering::Relaxed);
917            drop(inflight);
918            // Account for the requeue outcome (the nomination itself was already
919            // counted at ingress, so `queued` is not re-incremented): a capacity
920            // eviction of a DIFFERENT peer and a suppressed reserved event are
921            // both observable per the ADR funnel.
922            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
923                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
924                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
925                }
926                FirstAuditQueueOutcome::SuppressedLower => {
927                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
928                }
929                FirstAuditQueueOutcome::Queued
930                | FirstAuditQueueOutcome::Coalesced
931                | FirstAuditQueueOutcome::RetainedOnTie => {}
932            }
933            return None;
934        }
935        // Promote: stamp durable suppression, flip the lane, count the launch.
936        self.limiter.promote(event.peer, event.key_count, mono_now);
937        self.first_audited.put(event.pin, ());
938        self.oldest_first_lane = !self.oldest_first_lane;
939        obs.launched.fetch_add(1, Ordering::Relaxed);
940        Some((event, inflight))
941    }
942}
943
944// ---------------------------------------------------------------------------
945// Constants
946// ---------------------------------------------------------------------------
947
948/// Prefix used by saorsa-core's request-response mechanism.
949const RR_PREFIX: &str = "/rr/";
950
951fn fresh_offer_payment_context() -> VerificationContext {
952    VerificationContext::FreshReplication
953}
954
955fn paid_notify_payment_context() -> VerificationContext {
956    VerificationContext::PaidListAdmission
957}
958
959/// Boxed future type for in-flight fetch tasks.
960type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
961
962/// Shared dependencies for one verification worker cycle.
963struct VerificationCycleContext<'a> {
964    p2p_node: &'a Arc<P2PNode>,
965    paid_list: &'a Arc<PaidList>,
966    storage: &'a Arc<LmdbStorage>,
967    queues: &'a Arc<RwLock<ReplicationQueues>>,
968    config: &'a ReplicationConfig,
969    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
970    is_bootstrapping: &'a Arc<RwLock<bool>>,
971    bootstrap_complete_notify: &'a Arc<Notify>,
972    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
973    /// peer's Present claim to Unresolved unless they're a credited
974    /// holder of the key (i.e. they recently passed a commitment-bound
975    /// audit on it under their currently-credited commitment hash).
976    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
977    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
978    recent_provers: &'a Arc<RwLock<RecentProvers>>,
979}
980
981/// Fetch worker polling interval in milliseconds.
982const FETCH_WORKER_POLL_MS: u64 = 100;
983
984/// Verification worker polling interval in milliseconds.
985const VERIFICATION_WORKER_POLL_MS: u64 = 250;
986
987/// Verification cycle duration that is worth surfacing at info level.
988const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
989
990/// Standard trust event weight for per-operation success/failure signals.
991///
992/// Used for individual replication fetch outcomes, integrity check failures,
993/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
994/// is reserved for confirmed audit failures.
995const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
996
997/// Bootstrap drain check interval in seconds.
998const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
999
1000/// How often the responder rebuilds + rotates its storage commitment.
1001///
1002/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1003/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1004/// rotation-anchored: the responder stays answerable for the current
1005/// commitment plus every root it recently gossiped that is still in-window
1006/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1007/// its last emission (see `commitment_state`). So the rotation cadence does
1008/// not by itself bound answerability — a gossiped commitment stays
1009/// answerable across rotations until its gossip TTL lapses.
1010///
1011/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1012/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1013/// comfortably exceeds the gap between our rotation and the next gossip
1014/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1015/// Idle audit-skip pattern from being the common case.
1016///
1017/// Why not faster: the v12 pin is bound to a specific point-in-time
1018/// commitment, so rotation isn't security-critical for pin freshness —
1019/// only for keeping the committed key set current as the responder
1020/// writes new keys. 1 hour is plenty for that, and slow enough that
1021/// honest auditors mostly hit `current` or `previous` rather than the
1022/// "rotated past" case.
1023const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1024
1025/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1026/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1027/// durable well before it could matter to a restart, while the write-on-change
1028/// guard keeps idle nodes from needless disk writes.
1029const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1030
1031/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1032/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1033/// default that keeps log volume negligible.
1034const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1035
1036/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1037/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1038/// for first audit only if its SIGNED `quote_ts` lands in
1039/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1040/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1041/// badly-skewed or replayed quote) and one too old (the responder may have aged
1042/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1043/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1044/// within this margin); a legit first audit fires moments after payment
1045/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1046/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1047/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1048const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1049
1050/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1051/// inside the answerability window relative to `now`, so first-auditing it cannot
1052/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1053/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1054/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1055/// All comparisons use `duration_since` (no `Duration` overflow).
1056fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1057    let too_future = quote_ts
1058        .duration_since(now)
1059        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1060    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1061    let too_old = now
1062        .duration_since(quote_ts)
1063        .is_ok_and(|age| age >= audit_cutoff);
1064    !(too_future || too_old)
1065}
1066
1067/// Minimum interval between commitment signature verifications for a
1068/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1069///
1070/// A sybil that bypasses the routing-table gate (e.g. by transient
1071/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1072/// per gossip message. This rate limit caps the verify-per-peer rate
1073/// at 1/min, which is comfortably above the legitimate gossip cadence
1074/// (the 10-20 min neighbor-sync round on each peer).
1075const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1076
1077/// Hard cap on the size of `last_commitment_by_peer`.
1078///
1079/// Bounds the per-process memory cost of the auditor's per-peer
1080/// commitment cache. Each entry holds a `StorageCommitment`
1081/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1082/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1083/// realistic close-group neighborhood. When the cap is hit, one
1084/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1085/// order is unspecified; we do not track insertion order). The
1086/// `PeerRemoved` handler proactively drops entries as the DHT
1087/// detects departures, and `ingest_peer_commitment` only admits
1088/// commitments from peers currently in the routing table — together
1089/// the cap is the third line of defence against sybil/churn flooding.
1090const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1091
1092/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1093/// sized to the launch budget instead of the commitment cache.
1094///
1095/// The token bucket can launch at most one audit per
1096/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1097/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1098/// launchable for at most the effective answerability window
1099/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1100/// occupancy beyond `window / interval + burst` is work that cannot launch
1101/// before it expires, so admitting it only builds an aging backlog whose
1102/// telemetry measures the backlog instead of schedulable work.
1103///
1104/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1105/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1106/// rolling sample in which no arrival order lets an attacker deterministically
1107/// flush a chosen target; a fresh pin always enters the sample with an
1108/// unpredictable chance of near-immediate audit, whereas refusing at the door
1109/// would let a sustained payment flood guarantee that every later pin is never
1110/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1111/// ADR-0004 Amendment 4 for the eviction-cost math.
1112///
1113/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1114/// is usable only if the quote stays answerable through `a` plus the maximum
1115/// launch jitter and send slack, so the last usable refill is the largest
1116/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1117/// simulates the shipped predicate instant-by-instant and must agree.
1118#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1119const FIRST_AUDIT_PENDING_CAP: usize = {
1120    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1121        .as_secs()
1122        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1123        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1124        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1125    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1126    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1127    // if the launch interval is ever zeroed: a zero interval makes the budget
1128    // (and this cap) meaningless.
1129    let refills =
1130        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1131    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1132};
1133
1134// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1135// strictly tighter than the commitment-cache bound it replaced.
1136const _: () = {
1137    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1138    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1139};
1140
1141/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1142/// long-running bootstrap node cannot have the set grow without limit
1143/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1144/// the set comfortably outlives normal LRU churn but still caps the
1145/// blast radius of identity-rotation attacks. Once full we refuse new
1146/// inserts (no eviction) — keeps the historic set stable; new v12
1147/// peers above the cap are treated as legacy on rejoin, which matches
1148/// the behaviour before this set existed, not a security regression.
1149const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1150
1151// ---------------------------------------------------------------------------
1152// ReplicationEngine
1153// ---------------------------------------------------------------------------
1154
1155/// The replication engine manages all replication background tasks and state.
1156pub struct ReplicationEngine {
1157    /// Replication configuration (shared across spawned tasks).
1158    config: Arc<ReplicationConfig>,
1159    /// P2P networking node.
1160    p2p_node: Arc<P2PNode>,
1161    /// Local chunk storage.
1162    storage: Arc<LmdbStorage>,
1163    /// Persistent paid-for-list.
1164    paid_list: Arc<PaidList>,
1165    /// Payment verifier for `PoP` validation.
1166    payment_verifier: Arc<PaymentVerifier>,
1167    /// Replication pipeline queues.
1168    queues: Arc<RwLock<ReplicationQueues>>,
1169    /// Neighbor sync cycle state.
1170    sync_state: Arc<RwLock<NeighborSyncState>>,
1171    /// Per-peer sync history (for `RepairOpportunity`).
1172    ///
1173    /// This map grows with peer churn and is intentionally unbounded: entries
1174    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1175    /// naturally bounded by the routing table's k-bucket capacity.
1176    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1177    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1178    ///
1179    /// Records when each peer was last audited so a burst of gossiped
1180    /// commitment changes cannot spawn back-to-back audits of the same peer.
1181    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1182    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1183    /// Gossip-private lottery attempt window (one roll per peer per window,
1184    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1185    /// ticket never stamps the shared map and thus never defers a monetized
1186    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1187    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1188    /// Completed local neighbor-sync cycle epoch for proof maturity.
1189    sync_cycle_epoch: Arc<RwLock<u64>>,
1190    /// Per-key repair proof tracking for audit eligibility.
1191    repair_proofs: Arc<RwLock<RepairProofs>>,
1192    /// Bootstrap state tracking.
1193    bootstrap_state: Arc<RwLock<BootstrapState>>,
1194    /// Whether this node is currently bootstrapping.
1195    is_bootstrapping: Arc<RwLock<bool>>,
1196    /// Trigger for early neighbor sync (signalled on topology changes).
1197    sync_trigger: Arc<Notify>,
1198    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1199    bootstrap_complete_notify: Arc<Notify>,
1200    /// Node identity (for signing storage commitments).
1201    ///
1202    /// Phase 3 of the v12 storage-bound audit design. The responder
1203    /// uses this to sign its periodically-built `StorageCommitment`.
1204    identity: Arc<NodeIdentity>,
1205    /// Responder-side commitment state (two-slot atomic rotation).
1206    ///
1207    /// Periodically rebuilt from the live LMDB key set; gossiped on
1208    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1209    /// commitment-bound audit handler.
1210    commitment_state: Arc<ResponderCommitmentState>,
1211    /// Path to the persisted responder retention snapshot
1212    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1213    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1214    /// removing audit grace safe (an unanswerable in-window pin is then provable
1215    /// misbehaviour, not an honest crash-restart).
1216    retention_path: PathBuf,
1217    /// Auditor-side per-peer commitment record (last known commitment +
1218    /// sticky `commitment_capable` flag).
1219    ///
1220    /// Populated whenever an inbound gossip carries a verified
1221    /// commitment from the sender. Used by `audit_tick` to snapshot
1222    /// `expected_commitment_hash` into outbound challenges, and by
1223    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1224    /// proof should be honoured. The sticky `commitment_capable` flag
1225    /// flips true on first successful ingest and never reverts (§2
1226    /// step 5).
1227    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1228    /// Sticky set of peer IDs we have EVER seen carrying a v12
1229    /// commitment, independent of whether their commitment bytes are
1230    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1231    /// closure consults this set to keep treating churned-out
1232    /// previously-v12 peers as v12-capable (rather than degrading them
1233    /// to "legacy" credit-unconditionally) when they re-appear on the
1234    /// network before their next gossip arrives. Bounded growth: even
1235    /// at one million peers seen over the node's lifetime, the set is
1236    /// 32 MB.
1237    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1238    /// Auditor-side holder-eligibility cache (v12 §6).
1239    ///
1240    /// Recorded on successful commitment-bound audit; read by future
1241    /// quorum / paid-list eligibility checks (phase-3 stretch).
1242    recent_provers: Arc<RwLock<RecentProvers>>,
1243    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1244    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1245    /// failure) so a peer we've never successfully verified can't burn
1246    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1247    /// Lives separately from `last_commitment_by_peer` because that
1248    /// map's records only exist after a successful verify.
1249    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1250    /// Limits concurrent outbound replication sends to prevent bandwidth
1251    /// saturation on home broadband connections.
1252    send_semaphore: Arc<Semaphore>,
1253    /// Bounds concurrent IN-FLIGHT audit-responder tasks (subtree round 1 +
1254    /// byte round 2). Those are spawned off the serial message loop so disk
1255    /// reads don't block replication; the semaphore restores a global
1256    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1257    /// / multi-MiB byte serves.
1258    audit_responder_semaphore: Arc<Semaphore>,
1259    /// Per-source in-flight audit-responder counts, capped at
1260    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1261    /// flood-fair: one peer spamming challenges could occupy every slot and
1262    /// starve honest auditors, whose dropped challenges then convert to
1263    /// audit timeouts against HONEST peers (codex-r2 A). This
1264    /// per-peer cap guarantees no single source can hold more than its share,
1265    /// so a flood self-throttles without denying service to everyone else.
1266    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1267    /// Receiver for fresh-write events from the chunk PUT handler.
1268    ///
1269    /// When present, `start()` spawns a drainer task that calls
1270    /// `replicate_fresh` for each event.
1271    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1272    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1273    /// drainer pushes the responsible close-group peers here after each fresh
1274    /// replication; the possession-check scheduler drains the paired receiver.
1275    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1276    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1277    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1278    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1279    /// for a deterministic first audit. The matching receiver is drained by
1280    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1281    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1282    /// like launches; a dropped nomination is penalty-free — the peer's
1283    /// gossiped commitments stay lottery-covered and its next settled payment
1284    /// re-nominates the paid pin.
1285    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1286    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1287    /// `start_first_audit_drainer`.
1288    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1289    /// Counters shared with the first-audit drainer task, so the scheduler's
1290    /// decisions (queued / launched / self-target skipped / outcome) stay
1291    /// observable from the engine after the drainer takes the receiver.
1292    first_audit_observability: Arc<FirstAuditObservability>,
1293    /// Shutdown token.
1294    shutdown: CancellationToken,
1295    /// Background task handles.
1296    task_handles: Vec<JoinHandle<()>>,
1297}
1298
1299impl ReplicationEngine {
1300    /// Create a new replication engine.
1301    ///
1302    /// # Errors
1303    ///
1304    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1305    /// or if the configuration fails validation.
1306    #[allow(clippy::too_many_arguments)]
1307    pub async fn new(
1308        config: ReplicationConfig,
1309        p2p_node: Arc<P2PNode>,
1310        storage: Arc<LmdbStorage>,
1311        payment_verifier: Arc<PaymentVerifier>,
1312        identity: Arc<NodeIdentity>,
1313        root_dir: &Path,
1314        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1315        shutdown: CancellationToken,
1316    ) -> Result<Self> {
1317        config.validate().map_err(Error::Config)?;
1318
1319        let paid_list = Arc::new(
1320            PaidList::new(root_dir)
1321                .await
1322                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1323        );
1324
1325        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1326        let config = Arc::new(config);
1327        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1328
1329        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1330        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1331        // now capacity-limited — ingress queue here, pending set (LRU), and
1332        // launch rate (token bucket).
1333        let (monetized_pin_tx, monetized_pin_rx) =
1334            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1335
1336        let engine = Self {
1337            config: Arc::clone(&config),
1338            p2p_node,
1339            storage,
1340            paid_list,
1341            payment_verifier,
1342            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1343            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1344            sync_history: Arc::new(RwLock::new(HashMap::new())),
1345            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1346            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1347            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1348            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1349            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1350            is_bootstrapping: Arc::new(RwLock::new(true)),
1351            sync_trigger: Arc::new(Notify::new()),
1352            bootstrap_complete_notify: Arc::new(Notify::new()),
1353            identity,
1354            commitment_state: Arc::new(ResponderCommitmentState::new()),
1355            retention_path: root_dir.join("commitment_retention.bin"),
1356            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1357            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1358            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1359            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1360            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1361            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1362            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1363            fresh_write_rx: Some(fresh_write_rx),
1364            possession_check_tx,
1365            possession_check_rx: Some(possession_check_rx),
1366            monetized_pin_tx,
1367            monetized_pin_rx: Some(monetized_pin_rx),
1368            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1369            shutdown,
1370            task_handles: Vec::new(),
1371        };
1372        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1373        // spawns, so an honest restarted node is answerable for its pre-restart
1374        // pins from the first audit it serves, and the persist loop never races
1375        // an empty snapshot over the good on-disk file.
1376        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1377        Ok(engine)
1378    }
1379
1380    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1381    /// (commitments that backed a payment) for a first audit. Cloneable; the
1382    /// engine drains the matching receiver. Bounded: senders must `try_send`
1383    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1384    #[must_use]
1385    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1386        self.monetized_pin_tx.clone()
1387    }
1388
1389    /// Get a reference to the `PaidList`.
1390    #[must_use]
1391    pub fn paid_list(&self) -> &Arc<PaidList> {
1392        &self.paid_list
1393    }
1394
1395    /// Get a reference to the responder's commitment state. Used by audit
1396    /// handlers to look up commitments by hash; used by the rotation tick
1397    /// to install fresh ones.
1398    #[must_use]
1399    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1400        &self.commitment_state
1401    }
1402
1403    /// Get a reference to the auditor's last-commitment-by-peer table.
1404    #[must_use]
1405    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1406        &self.last_commitment_by_peer
1407    }
1408
1409    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
1410    /// will be read by quorum / paid-list eligibility checks.
1411    #[must_use]
1412    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
1413        &self.recent_provers
1414    }
1415
1416    /// Test-only: rebuild + rotate this node's storage commitment now over its
1417    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
1418    /// just stored without waiting for the rotation cadence.
1419    ///
1420    /// # Errors
1421    ///
1422    /// Propagates any error from reading the local key set or building/signing
1423    /// the commitment.
1424    #[cfg(any(test, feature = "test-utils"))]
1425    pub async fn rebuild_commitment_now(&self) -> Result<()> {
1426        rebuild_and_rotate_commitment(
1427            &self.storage,
1428            &self.identity,
1429            &self.commitment_state,
1430            &self.p2p_node,
1431            &self.config,
1432        )
1433        .await
1434    }
1435
1436    /// Test-only: directly seed this node's cached commitment for `peer`,
1437    /// simulating "we received `peer`'s gossiped commitment" without depending
1438    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
1439    /// peer's commitment deterministically.
1440    #[cfg(any(feature = "test-utils", test))]
1441    pub async fn inject_peer_commitment_for_test(
1442        &self,
1443        peer: &PeerId,
1444        commitment: StorageCommitment,
1445    ) {
1446        let now = Instant::now();
1447        self.last_commitment_by_peer
1448            .write()
1449            .await
1450            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
1451        self.ever_capable_peers.write().await.insert(*peer);
1452    }
1453
1454    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
1455    /// commitment this node has cached for it (from gossip), over the live wire.
1456    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
1457    /// in a real two-node setting without waiting for the gossip cadence.
1458    ///
1459    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
1460    /// peer yet (gossip hasn't reached us). Gated to test builds.
1461    #[cfg(any(test, feature = "test-utils"))]
1462    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
1463        let target = {
1464            let map = self.last_commitment_by_peer.read().await;
1465            map.get(peer)
1466                .and_then(PeerCommitmentRecord::last_commitment)
1467                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
1468        };
1469        let Some((pin, key_count)) = target else {
1470            return audit::AuditTickResult::Idle;
1471        };
1472        let credit = storage_commitment_audit::AuditCredit {
1473            recent_provers: &self.recent_provers,
1474        };
1475        storage_commitment_audit::run_subtree_audit(
1476            &self.p2p_node,
1477            &self.config,
1478            peer,
1479            pin,
1480            key_count,
1481            Some(&credit),
1482        )
1483        .await
1484    }
1485
1486    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
1487    /// tests assert what the live drainer decided for an injected
1488    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
1489    #[cfg(any(test, feature = "test-utils"))]
1490    #[must_use]
1491    pub fn first_audit_stats(&self) -> FirstAuditStats {
1492        let o = &self.first_audit_observability;
1493        FirstAuditStats {
1494            received: o.received.load(Ordering::Relaxed),
1495            queued: o.queued.load(Ordering::Relaxed),
1496            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
1497            launched: o.launched.load(Ordering::Relaxed),
1498            passed: o.passed.load(Ordering::Relaxed),
1499            timed_out: o.timed_out.load(Ordering::Relaxed),
1500            failed: o.failed.load(Ordering::Relaxed),
1501        }
1502    }
1503
1504    /// Test-only: run the possession check immediately for `key` against
1505    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
1506    ///
1507    /// Penalises any peer that does not hold `key` at `AuditChallenge`
1508    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
1509    /// deterministically without waiting for the scheduled check.
1510    #[cfg(any(test, feature = "test-utils"))]
1511    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
1512        possession::run_possession_check(
1513            key,
1514            peers,
1515            &self.p2p_node,
1516            &self.storage,
1517            &self.config,
1518            &self.sync_state,
1519            &self.shutdown,
1520        )
1521        .await;
1522    }
1523
1524    /// Start all background tasks.
1525    ///
1526    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
1527    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
1528    /// missed by the bootstrap-sync gate.
1529    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
1530        if !self.task_handles.is_empty() {
1531            error!("ReplicationEngine::start() called while already running — ignoring");
1532            return;
1533        }
1534        info!("Starting replication engine");
1535
1536        self.start_message_handler();
1537        self.start_neighbor_sync_loop();
1538        self.start_self_lookup_loop();
1539        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
1540        // chunks they SHOULD store (responsibility + prior hint).
1541        self.start_audit_loop();
1542        // Audit #1 (storage-commitment) is gossip-triggered in the message
1543        // handler when a peer's commitment is ingested, not on a periodic tick.
1544        self.start_commitment_rotation_loop();
1545        self.start_retention_persist_loop();
1546        self.start_fetch_worker();
1547        self.start_verification_worker();
1548        self.start_bootstrap_sync(dht_events);
1549        self.start_fresh_write_drainer();
1550        self.start_possession_check_scheduler();
1551        // ADR-0004: deterministic first audit of commitments that backed a
1552        // payment (surfaced by the verifier cross-check).
1553        self.start_first_audit_drainer();
1554        // V2-623: periodic cumulative per-variant traffic accounting.
1555        self.start_traffic_summary_loop();
1556
1557        info!(
1558            "Replication engine started with {} background tasks",
1559            self.task_handles.len()
1560        );
1561    }
1562
1563    /// Returns `true` if the node is still in the replication bootstrap phase.
1564    ///
1565    /// During bootstrap, audit challenges return `Bootstrapping` instead of
1566    /// digests, and neighbor sync responses carry `bootstrapping: true`.
1567    pub async fn is_bootstrapping(&self) -> bool {
1568        *self.is_bootstrapping.read().await
1569    }
1570
1571    /// Wait until the replication bootstrap phase completes.
1572    ///
1573    /// Returns immediately if bootstrap has already completed. Useful for
1574    /// readiness probes, health checks, and test harnesses that need the
1575    /// node to be fully operational before proceeding.
1576    ///
1577    /// Returns `true` if bootstrap completed within the timeout, `false`
1578    /// if the timeout elapsed first.
1579    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
1580        // Register the notification future *before* checking the flag so that
1581        // a transition between the read and the await is not missed.
1582        let notified = self.bootstrap_complete_notify.notified();
1583        tokio::pin!(notified);
1584        notified.as_mut().enable();
1585
1586        if !*self.is_bootstrapping.read().await {
1587            return true;
1588        }
1589
1590        tokio::time::timeout(timeout, notified).await.is_ok()
1591    }
1592
1593    /// Cancel all background tasks and wait for them to terminate.
1594    ///
1595    /// This must be awaited before dropping the engine when the caller needs
1596    /// the `Arc<LmdbStorage>` references held by background tasks to be
1597    /// released (e.g. before reopening the same LMDB environment).
1598    pub async fn shutdown(&mut self) {
1599        self.shutdown.cancel();
1600        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
1601            match tokio::time::timeout(std::time::Duration::from_secs(10), &mut handle).await {
1602                Ok(Ok(())) => {}
1603                Ok(Err(e)) if e.is_cancelled() => {}
1604                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
1605                Err(_) => {
1606                    warn!("Replication task {i} did not stop within 10s, aborting");
1607                    handle.abort();
1608                }
1609            }
1610        }
1611    }
1612
1613    /// Trigger an early neighbor sync round.
1614    ///
1615    /// Useful after topology changes (new nodes joining, network heal after
1616    /// partition) when the caller wants replication to converge faster than
1617    /// the regular 10-20 minute cadence.
1618    pub fn trigger_neighbor_sync(&self) {
1619        self.sync_trigger.notify_one();
1620    }
1621
1622    /// Execute fresh replication for a newly stored record, then schedule the
1623    /// delayed possession check for the responsible close-group peers
1624    /// (ADR-0003). The production PUT path schedules via the fresh-write
1625    /// drainer; this direct entry point schedules here so callers (and tests)
1626    /// that drive replication directly still get the possession check.
1627    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
1628        let peers = fresh::replicate_fresh(
1629            key,
1630            data,
1631            proof_of_payment,
1632            &self.p2p_node,
1633            &self.paid_list,
1634            &self.config,
1635            &self.send_semaphore,
1636        )
1637        .await;
1638        if !peers.is_empty() {
1639            let _ = self
1640                .possession_check_tx
1641                .send(possession::PossessionCheckEvent { key: *key, peers });
1642        }
1643    }
1644
1645    // =======================================================================
1646    // Background task launchers
1647    // =======================================================================
1648
1649    /// Spawn a task that drains the fresh-write channel and triggers
1650    /// replication for each newly-stored chunk.
1651    fn start_fresh_write_drainer(&mut self) {
1652        let Some(mut rx) = self.fresh_write_rx.take() else {
1653            return;
1654        };
1655        let p2p = Arc::clone(&self.p2p_node);
1656        let paid_list = Arc::clone(&self.paid_list);
1657        let config = Arc::clone(&self.config);
1658        let send_semaphore = Arc::clone(&self.send_semaphore);
1659        let possession_tx = self.possession_check_tx.clone();
1660        let shutdown = self.shutdown.clone();
1661
1662        let handle = tokio::spawn(async move {
1663            loop {
1664                tokio::select! {
1665                    () = shutdown.cancelled() => break,
1666                    event = rx.recv() => {
1667                        let Some(event) = event else { break };
1668                        let peers = fresh::replicate_fresh(
1669                            &event.key,
1670                            &event.data,
1671                            &event.payment_proof,
1672                            &p2p,
1673                            &paid_list,
1674                            &config,
1675                            &send_semaphore,
1676                        )
1677                        .await;
1678                        // Schedule the delayed possession check (ADR-0003) for
1679                        // the responsible close-group peers. A closed receiver
1680                        // (engine shutting down) is ignored.
1681                        if !peers.is_empty() {
1682                            let _ = possession_tx.send(possession::PossessionCheckEvent {
1683                                key: event.key,
1684                                peers,
1685                            });
1686                        }
1687                    }
1688                }
1689            }
1690            debug!("Fresh-write drainer shut down");
1691        });
1692        self.task_handles.push(handle);
1693    }
1694
1695    /// Spawn the possession-check scheduler (ADR-0003).
1696    ///
1697    /// Drains scheduled possession-check events and, for each, waits a
1698    /// randomised 5-15 minute settle delay before probing every responsible
1699    /// peer for actual possession. A peer that cryptographically fails to prove
1700    /// possession, including by timeout, is penalised at `AuditChallenge`
1701    /// severity.
1702    fn start_possession_check_scheduler(&mut self) {
1703        let Some(mut rx) = self.possession_check_rx.take() else {
1704            return;
1705        };
1706        let p2p = Arc::clone(&self.p2p_node);
1707        let storage = Arc::clone(&self.storage);
1708        let config = Arc::clone(&self.config);
1709        let sync_state = Arc::clone(&self.sync_state);
1710        let shutdown = self.shutdown.clone();
1711
1712        let handle = tokio::spawn(async move {
1713            loop {
1714                tokio::select! {
1715                    () = shutdown.cancelled() => break,
1716                    event = rx.recv() => {
1717                        let Some(event) = event else { break };
1718                        // Spawn a per-chunk delayed check so the drain loop
1719                        // keeps pace with the write rate. Each check sleeps the
1720                        // randomised settle delay, then probes every peer.
1721                        let p2p = Arc::clone(&p2p);
1722                        let storage = Arc::clone(&storage);
1723                        let config = Arc::clone(&config);
1724                        let sync_state = Arc::clone(&sync_state);
1725                        let shutdown = shutdown.clone();
1726                        let delay_min = config.possession_check_delay_min;
1727                        let delay_max = config.possession_check_delay_max;
1728                        tokio::spawn(async move {
1729                            let delay = possession::random_delay(delay_min, delay_max);
1730                            tokio::select! {
1731                                () = shutdown.cancelled() => {}
1732                                () = tokio::time::sleep(delay) => {
1733                                    possession::run_possession_check(
1734                                        event.key,
1735                                        event.peers,
1736                                        &p2p,
1737                                        &storage,
1738                                        &config,
1739                                        &sync_state,
1740                                        &shutdown,
1741                                    )
1742                                    .await;
1743                                }
1744                            }
1745                        });
1746                    }
1747                }
1748            }
1749            debug!("Possession-check scheduler shut down");
1750        });
1751        self.task_handles.push(handle);
1752    }
1753
1754    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
1755    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
1756    /// as the gossip path, under the same per-peer cooldown and concurrency
1757    /// caps, but with the probability lottery BYPASSED (the lottery governs
1758    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
1759    /// deterministic first audit; a peer minting fresh pins faster than the
1760    /// cooldown forfeits the older ones' coverage, never the newest's (the
1761    /// channel surfaces newest pins as they are monetized).
1762    #[allow(clippy::too_many_lines)]
1763    fn start_first_audit_drainer(&mut self) {
1764        let Some(mut rx) = self.monetized_pin_rx.take() else {
1765            return;
1766        };
1767        let gossip_audit = GossipAuditTrigger {
1768            p2p_node: Arc::clone(&self.p2p_node),
1769            config: Arc::clone(&self.config),
1770            recent_provers: Arc::clone(&self.recent_provers),
1771            sync_state: Arc::clone(&self.sync_state),
1772            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
1773            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
1774        };
1775        let shutdown = self.shutdown.clone();
1776        let observability = Arc::clone(&self.first_audit_observability);
1777        let self_peer = *self.p2p_node.peer_id();
1778
1779        let handle = tokio::spawn(async move {
1780            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
1781            // scheduler. Payments only NOMINATE pins; the token bucket launches
1782            // them at a fixed per-node rate, and durable suppression is stamped
1783            // only at PROMOTION (after an authoritative post-jitter answerability
1784            // + cooldown check), so a cancelled reservation leaves nothing behind.
1785            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
1786            // Periodic retry tick so budget/cooldown-deferred pins get retried
1787            // even when no new nomination arrives. `Skip` collapses a backlog.
1788            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
1789            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1790            let mut last_summary = Instant::now();
1791            loop {
1792                // The reservation's jitter deadline is a wake source: if a
1793                // reservation is outstanding, sleep until it is due; otherwise
1794                // a far-future deadline effectively disables that arm and only
1795                // shutdown/rx/tick wake the loop. Recreated each iteration so a
1796                // newly reserved (earlier) deadline is honoured next turn.
1797                let promotion_due = scheduler
1798                    .reserved_ready_at()
1799                    .unwrap_or_else(first_audit_far_future);
1800                tokio::select! {
1801                    () = shutdown.cancelled() => break,
1802                    event = rx.recv() => match event {
1803                        Some(e) => {
1804                            observability.received.fetch_add(1, Ordering::Relaxed);
1805                            // Pre-overflow reservation opportunity: before an
1806                            // arrival may displace a DIFFERENT peer, let the
1807                            // queue launch — a successful reservation frees the
1808                            // slot without eviction. One reservation can be
1809                            // outstanding at a time, so this consumes at most
1810                            // one slot per jitter window; arrivals beyond it
1811                            // fall through to random displacement (ADR-0004
1812                            // Amendment 4).
1813                            if scheduler.would_displace(&e) {
1814                                open_first_audit_reservation(
1815                                    &mut scheduler,
1816                                    &gossip_audit.cooldown,
1817                                    &observability,
1818                                )
1819                                .await;
1820                            }
1821                            scheduler.enqueue(e, &observability);
1822                            // Drain a bounded burst so a flood cannot starve the
1823                            // launch phase.
1824                            let mut drained = 1usize;
1825                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
1826                                match rx.try_recv() {
1827                                    Ok(e) => {
1828                                        observability.received.fetch_add(1, Ordering::Relaxed);
1829                                        if scheduler.would_displace(&e) {
1830                                            open_first_audit_reservation(
1831                                                &mut scheduler,
1832                                                &gossip_audit.cooldown,
1833                                                &observability,
1834                                            )
1835                                            .await;
1836                                        }
1837                                        scheduler.enqueue(e, &observability);
1838                                        drained += 1;
1839                                    }
1840                                    Err(_) => break,
1841                                }
1842                            }
1843                        }
1844                        None => break,
1845                    },
1846                    _ = tick.tick() => {}
1847                    () = tokio::time::sleep_until(promotion_due.into()) => {}
1848                }
1849
1850                // 1) Promote a due reservation. Resolved after EVERY wake (not
1851                //    only when the timer arm wins) so a continuously-ready `rx`
1852                //    cannot indefinitely delay a due promotion. The authoritative
1853                //    answerability + cooldown check-and-stamp happens here under
1854                //    the shared cooldown write lock, immediately before the send.
1855                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
1856                    let promoted = {
1857                        let mut cooldown = gossip_audit.cooldown.write().await;
1858                        scheduler.resolve(
1859                            reservation,
1860                            SystemTime::now(),
1861                            Instant::now(),
1862                            &mut cooldown,
1863                            &observability,
1864                        )
1865                    };
1866                    if let Some((event, inflight_slot)) = promoted {
1867                        debug!(
1868                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
1869                            event.peer, hex::encode(event.pin), event.key_count,
1870                            observability.inflight.load(Ordering::Relaxed)
1871                        );
1872                        let trigger = gossip_audit.clone();
1873                        let audit_observability = Arc::clone(&observability);
1874                        tokio::spawn(async move {
1875                            // The jitter already elapsed as the reservation's
1876                            // timer; the slot is held for the audit's duration
1877                            // and released on drop (panic-safe).
1878                            let inflight_slot = inflight_slot;
1879                            let started = Instant::now();
1880                            let credit = storage_commitment_audit::AuditCredit {
1881                                recent_provers: &trigger.recent_provers,
1882                            };
1883                            let result = storage_commitment_audit::run_subtree_audit(
1884                                &trigger.p2p_node,
1885                                &trigger.config,
1886                                &event.peer,
1887                                event.pin,
1888                                event.key_count,
1889                                Some(&credit),
1890                            )
1891                            .await;
1892                            let outcome = first_audit_terminal_outcome(&result);
1893                            match outcome {
1894                                FirstAuditTerminalOutcome::Passed => {
1895                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
1896                                }
1897                                FirstAuditTerminalOutcome::Timeout => {
1898                                    audit_observability
1899                                        .timed_out
1900                                        .fetch_add(1, Ordering::Relaxed);
1901                                }
1902                                FirstAuditTerminalOutcome::Failed => {
1903                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
1904                                }
1905                                FirstAuditTerminalOutcome::BootstrapClaim => {
1906                                    audit_observability
1907                                        .bootstrap_claims
1908                                        .fetch_add(1, Ordering::Relaxed);
1909                                }
1910                                FirstAuditTerminalOutcome::Idle => {
1911                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
1912                                }
1913                                FirstAuditTerminalOutcome::InsufficientKeys => {
1914                                    audit_observability
1915                                        .insufficient_keys
1916                                        .fetch_add(1, Ordering::Relaxed);
1917                                }
1918                            }
1919                            drop(inflight_slot);
1920                            debug!(
1921                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
1922                                outcome.as_str(),
1923                                event.peer, hex::encode(event.pin), event.key_count,
1924                                started.elapsed().as_millis(),
1925                                audit_observability.inflight.load(Ordering::Relaxed)
1926                            );
1927                            handle_subtree_audit_result(
1928                                &result,
1929                                &trigger.p2p_node,
1930                                &trigger.sync_state,
1931                                &trigger.recent_provers,
1932                                &trigger.config,
1933                            )
1934                            .await;
1935                        });
1936                    }
1937                }
1938
1939                // 2) Open the single reservation from the pending queue if none
1940                //    is outstanding (read-only cooldown snapshot; the
1941                //    authoritative stamp is at promotion). Serializing
1942                //    reservations preserves per-launch lane alternation and keeps
1943                //    at most one jitter timer live.
1944                open_first_audit_reservation(
1945                    &mut scheduler,
1946                    &gossip_audit.cooldown,
1947                    &observability,
1948                )
1949                .await;
1950
1951                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
1952                    // Token-independent hygiene: collect entries that aged past
1953                    // the answerability horizon while the budget gate kept the
1954                    // reserve scan from running, so the summary below reports
1955                    // only live work.
1956                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
1957                    if swept > 0 {
1958                        debug!(
1959                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
1960                            scheduler.pending_len()
1961                        );
1962                    }
1963                    info!(
1964                        "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={}",
1965                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
1966                        observability.received.load(Ordering::Relaxed),
1967                        observability.queued.load(Ordering::Relaxed),
1968                        observability.coalesced.load(Ordering::Relaxed),
1969                        observability.suppressed_lower.load(Ordering::Relaxed),
1970                        observability.duplicates.load(Ordering::Relaxed),
1971                        observability.capacity_evicted.load(Ordering::Relaxed),
1972                        observability.self_target_skipped.load(Ordering::Relaxed),
1973                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
1974                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
1975                        observability.window_deduped.load(Ordering::Relaxed),
1976                        observability.launched.load(Ordering::Relaxed),
1977                        observability.passed.load(Ordering::Relaxed),
1978                        observability.timed_out.load(Ordering::Relaxed),
1979                        observability.failed.load(Ordering::Relaxed),
1980                        observability.bootstrap_claims.load(Ordering::Relaxed),
1981                        observability.idle.load(Ordering::Relaxed),
1982                        observability.insufficient_keys.load(Ordering::Relaxed),
1983                        observability.outside_answerability_window.load(Ordering::Relaxed),
1984                        scheduler.pending_len(),
1985                        FIRST_AUDIT_PENDING_CAP,
1986                        u8::from(scheduler.has_reservation()),
1987                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
1988                        observability.inflight.load(Ordering::Relaxed),
1989                        scheduler.tokens(),
1990                    );
1991                    last_summary = Instant::now();
1992                }
1993            }
1994            debug!("First-audit drainer shut down");
1995        });
1996        self.task_handles.push(handle);
1997    }
1998
1999    #[allow(clippy::too_many_lines)]
2000    fn start_message_handler(&mut self) {
2001        let mut p2p_events = self.p2p_node.subscribe_events();
2002        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2003        let p2p = Arc::clone(&self.p2p_node);
2004        let storage = Arc::clone(&self.storage);
2005        let paid_list = Arc::clone(&self.paid_list);
2006        let payment_verifier = Arc::clone(&self.payment_verifier);
2007        let queues = Arc::clone(&self.queues);
2008        let config = Arc::clone(&self.config);
2009        let shutdown = self.shutdown.clone();
2010        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2011        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2012        let sync_history = Arc::clone(&self.sync_history);
2013        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2014        let repair_proofs = Arc::clone(&self.repair_proofs);
2015        let sync_trigger = Arc::clone(&self.sync_trigger);
2016        let my_commitment_state = Arc::clone(&self.commitment_state);
2017        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2018        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2019        let recent_provers = Arc::clone(&self.recent_provers);
2020        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2021        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2022        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2023        let sync_state = Arc::clone(&self.sync_state);
2024        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2025        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2026
2027        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2028        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2029        let gossip_audit = GossipAuditTrigger {
2030            p2p_node: Arc::clone(&p2p),
2031            config: Arc::clone(&config),
2032            recent_provers: Arc::clone(&recent_provers),
2033            sync_state: Arc::clone(&sync_state),
2034            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2035            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2036        };
2037
2038        let handle = tokio::spawn(async move {
2039            loop {
2040                tokio::select! {
2041                    () = shutdown.cancelled() => break,
2042                    event = p2p_events.recv() => {
2043                        let Ok(event) = event else { continue };
2044                        if let P2PEvent::Message {
2045                            topic,
2046                            source: Some(source),
2047                            data,
2048                            ..
2049                        } = event {
2050                            // Determine if this is a replication message
2051                            // and whether it arrived via the /rr/ request-response
2052                            // path (which wraps payloads in RequestResponseEnvelope).
2053                            let rr_info = if topic == REPLICATION_PROTOCOL_ID {
2054                                Some((data.clone(), None))
2055                            } else if topic.starts_with(RR_PREFIX)
2056                                && &topic[RR_PREFIX.len()..] == REPLICATION_PROTOCOL_ID
2057                            {
2058                                P2PNode::parse_request_envelope(&data)
2059                                    .filter(|(_, is_resp, _)| !is_resp)
2060                                    .map(|(msg_id, _, payload)| (payload, Some(msg_id)))
2061                            } else {
2062                                None
2063                            };
2064                            if let Some((payload, rr_message_id)) = rr_info {
2065                                match handle_replication_message(
2066                                    &source,
2067                                    &payload,
2068                                    &p2p,
2069                                    &storage,
2070                                    &paid_list,
2071                                    &payment_verifier,
2072                                    &queues,
2073                                    &config,
2074                                    &is_bootstrapping,
2075                                    &bootstrap_state,
2076                                    &sync_history,
2077                                    &sync_cycle_epoch,
2078                                    &repair_proofs,
2079                                    &last_commitment_by_peer,
2080                                    &ever_capable_peers,
2081                                    &sig_verify_attempts,
2082                                    &my_commitment_state,
2083                                    &gossip_audit,
2084                                    &audit_responder_semaphore,
2085                                    &audit_responder_inflight,
2086                                    rr_message_id.as_deref(),
2087                                ).await {
2088                                    Ok(()) => {}
2089                                    Err(e) => {
2090                                        debug!(
2091                                            "Replication message from {source} error: {e}"
2092                                        );
2093                                    }
2094                                }
2095                            }
2096                        }
2097                    }
2098                    // Gap 4: Topology churn handling (Section 13).
2099                    //
2100                    // The DHT routing table emits KClosestPeersChanged when the
2101                    // K-closest peer set actually changes, which is the precise
2102                    // signal for triggering neighbor sync. This replaces the
2103                    // previous approach of checking every PeerConnected /
2104                    // PeerDisconnected event against the close group.
2105                    dht_event = dht_events.recv() => {
2106                        let Ok(dht_event) = dht_event else { continue };
2107                        match dht_event {
2108                            DhtNetworkEvent::KClosestPeersChanged { old, new } => {
2109                                let old_peers = old
2110                                    .iter()
2111                                    .take(config.neighbor_sync_scope)
2112                                    .copied()
2113                                    .collect::<HashSet<_>>();
2114                                let new_scoped = new
2115                                    .iter()
2116                                    .take(config.neighbor_sync_scope)
2117                                    .copied()
2118                                    .collect::<Vec<_>>();
2119                                let new_peers =
2120                                    new_scoped.iter().copied().collect::<HashSet<_>>();
2121                                let entrants = new_scoped
2122                                    .iter()
2123                                    .copied()
2124                                    .filter(|peer| !old_peers.contains(peer))
2125                                    .collect::<Vec<_>>();
2126                                let entrant_count = entrants.len();
2127                                let (priority_insertions, sync_removals) = {
2128                                    let mut state = sync_state.write().await;
2129                                    let sync_removals = state.retain_sync_peers(&new_peers);
2130                                    let priority_insertions = state.queue_priority_peers(entrants);
2131                                    (priority_insertions, sync_removals)
2132                                };
2133                                if priority_insertions > 0 {
2134                                    debug!(
2135                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
2136                                    );
2137                                } else {
2138                                    debug!(
2139                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
2140                                    );
2141                                }
2142                                sync_trigger.notify_one();
2143                            }
2144                            DhtNetworkEvent::PeerRemoved { peer_id } => {
2145                                sync_state.write().await.remove_peer(&peer_id);
2146                                repair_proofs.write().await.remove_peer(&peer_id);
2147                                // v12: drop the commitment bytes and the
2148                                // recent-prover credit so a churn / sybil
2149                                // attacker cannot leave behind one
2150                                // StorageCommitment per identity in
2151                                // `last_commitment_by_peer`. Also drop the
2152                                // sig-verify rate-limit timestamp.
2153                                last_commitment_by_peer.write().await.remove(&peer_id);
2154                                recent_provers.write().await.forget_peer(&peer_id);
2155                                sig_verify_attempts.write().await.remove(&peer_id);
2156                                // Same for the gossip-audit cooldown (ADR-0002)
2157                                // and the lottery-attempt window.
2158                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
2159                                gossip_lottery_attempts.write().await.remove(&peer_id);
2160                                // The sticky `commitment_capable` flag is
2161                                // preserved orthogonally via
2162                                // `ever_capable_peers` — even after this
2163                                // removal, a re-joining peer continues to
2164                                // be treated as v12-capable rather than
2165                                // legacy (§3 shield).
2166                            }
2167                            _ => {}
2168                        }
2169                    }
2170                }
2171            }
2172            debug!("Replication message handler shut down");
2173        });
2174        self.task_handles.push(handle);
2175    }
2176
2177    fn start_neighbor_sync_loop(&mut self) {
2178        let p2p = Arc::clone(&self.p2p_node);
2179        let storage = Arc::clone(&self.storage);
2180        let paid_list = Arc::clone(&self.paid_list);
2181        let queues = Arc::clone(&self.queues);
2182        let config = Arc::clone(&self.config);
2183        let shutdown = self.shutdown.clone();
2184        let sync_state = Arc::clone(&self.sync_state);
2185        let sync_history = Arc::clone(&self.sync_history);
2186        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2187        let repair_proofs = Arc::clone(&self.repair_proofs);
2188        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2189        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2190        let sync_trigger = Arc::clone(&self.sync_trigger);
2191        let commitment_state = Arc::clone(&self.commitment_state);
2192        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2193        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2194        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2195        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
2196        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
2197        // here too so a peer that only ever answers — never initiates sync —
2198        // is still audited; otherwise it could fully evade auditing.
2199        let gossip_audit = GossipAuditTrigger {
2200            p2p_node: Arc::clone(&p2p),
2201            config: Arc::clone(&config),
2202            recent_provers: Arc::clone(&self.recent_provers),
2203            sync_state: Arc::clone(&sync_state),
2204            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2205            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2206        };
2207
2208        let handle = tokio::spawn(async move {
2209            loop {
2210                let interval = config.random_neighbor_sync_interval();
2211                tokio::select! {
2212                    () = shutdown.cancelled() => break,
2213                    () = tokio::time::sleep(interval) => {}
2214                    () = sync_trigger.notified() => {
2215                        debug!("Neighbor sync triggered by topology change");
2216                    }
2217                }
2218                // Wrap the sync round in a select so shutdown cancels
2219                // in-progress network operations rather than waiting for
2220                // the full round to complete.
2221                tokio::select! {
2222                    () = shutdown.cancelled() => break,
2223                    () = run_neighbor_sync_round(
2224                        &p2p,
2225                        &storage,
2226                        &paid_list,
2227                        &queues,
2228                        &config,
2229                        &sync_state,
2230                        &sync_history,
2231                        &sync_cycle_epoch,
2232                        &repair_proofs,
2233                        &is_bootstrapping,
2234                        &bootstrap_state,
2235                        &commitment_state,
2236                        &last_commitment_by_peer,
2237                        &ever_capable_peers,
2238                        &sig_verify_attempts,
2239                        &gossip_audit,
2240                    ) => {}
2241                }
2242            }
2243            debug!("Neighbor sync loop shut down");
2244        });
2245        self.task_handles.push(handle);
2246    }
2247
2248    fn start_self_lookup_loop(&mut self) {
2249        let p2p = Arc::clone(&self.p2p_node);
2250        let config = Arc::clone(&self.config);
2251        let shutdown = self.shutdown.clone();
2252
2253        let handle = tokio::spawn(async move {
2254            loop {
2255                let interval = config.random_self_lookup_interval();
2256                tokio::select! {
2257                    () = shutdown.cancelled() => break,
2258                    () = tokio::time::sleep(interval) => {
2259                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
2260                            debug!("Self-lookup failed: {e}");
2261                        }
2262                    }
2263                }
2264            }
2265            debug!("Self-lookup loop shut down");
2266        });
2267        self.task_handles.push(handle);
2268    }
2269
2270    /// Periodic responsible-chunk audit loop (audit #2): every
2271    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
2272    /// eligible close peer for the chunks it *should* be storing (by
2273    /// responsibility and prior repair hint), independent of the gossip-triggered
2274    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
2275    /// immediately and periodically thereafter.
2276    fn start_audit_loop(&mut self) {
2277        let p2p = Arc::clone(&self.p2p_node);
2278        let storage = Arc::clone(&self.storage);
2279        let config = Arc::clone(&self.config);
2280        let shutdown = self.shutdown.clone();
2281        let sync_history = Arc::clone(&self.sync_history);
2282        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2283        let repair_proofs = Arc::clone(&self.repair_proofs);
2284        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2285        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2286        let sync_state = Arc::clone(&self.sync_state);
2287
2288        let handle = tokio::spawn(async move {
2289            // Invariant 19: wait for bootstrap to drain before starting audits.
2290            loop {
2291                tokio::select! {
2292                    () = shutdown.cancelled() => return,
2293                    () = tokio::time::sleep(
2294                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
2295                    ) => {
2296                        if bootstrap_state.read().await.is_drained() {
2297                            break;
2298                        }
2299                    }
2300                }
2301            }
2302
2303            // Run one audit tick immediately after bootstrap drain.
2304            {
2305                let bootstrapping = *is_bootstrapping.read().await;
2306                let result = {
2307                    let history = sync_history.read().await;
2308                    let current_sync_epoch = *sync_cycle_epoch.read().await;
2309                    audit::audit_tick_with_repair_proofs(
2310                        &p2p,
2311                        &storage,
2312                        &config,
2313                        &history,
2314                        &repair_proofs,
2315                        current_sync_epoch,
2316                        bootstrapping,
2317                    )
2318                    .await
2319                };
2320                handle_audit_result(&result, &p2p, &sync_state, &config).await;
2321            }
2322
2323            // Then run periodically.
2324            loop {
2325                let interval = config.random_audit_tick_interval();
2326                tokio::select! {
2327                    () = shutdown.cancelled() => break,
2328                    () = tokio::time::sleep(interval) => {
2329                        let bootstrapping = *is_bootstrapping.read().await;
2330                        let result = {
2331                            let history = sync_history.read().await;
2332                            let current_sync_epoch = *sync_cycle_epoch.read().await;
2333                            audit::audit_tick_with_repair_proofs(
2334                                &p2p,
2335                                &storage,
2336                                &config,
2337                                &history,
2338                                &repair_proofs,
2339                                current_sync_epoch,
2340                                bootstrapping,
2341                            )
2342                            .await
2343                        };
2344                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
2345                    }
2346                }
2347            }
2348            debug!("Audit loop shut down");
2349        });
2350        self.task_handles.push(handle);
2351    }
2352
2353    /// Periodically rebuild + sign + rotate the responder's storage
2354    /// commitment.
2355    ///
2356    /// Phase 3 of the v12 storage-bound audit. Once per
2357    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
2358    /// current LMDB key set, builds a Merkle tree (for content-addressed
2359    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
2360    /// the root with the node's `MlDsaSecretKey`, and rotates the result
2361    /// into `commitment_state`. Old `previous` slot is dropped by the
2362    /// rotate (per `ResponderCommitmentState::rotate`).
2363    ///
2364    /// Skips if the key set is empty (no commitment to make) — the
2365    /// auditor side falls back to the legacy plain-digest path for
2366    /// peers that have never gossiped a commitment.
2367    fn start_commitment_rotation_loop(&mut self) {
2368        let storage = Arc::clone(&self.storage);
2369        let identity = Arc::clone(&self.identity);
2370        let commitment_state = Arc::clone(&self.commitment_state);
2371        let shutdown = self.shutdown.clone();
2372        let p2p = Arc::clone(&self.p2p_node);
2373        let config = Arc::clone(&self.config);
2374        let sync_trigger = Arc::clone(&self.sync_trigger);
2375        let recent_provers = Arc::clone(&self.recent_provers);
2376
2377        let handle = tokio::spawn(async move {
2378            // Build the first commitment immediately on startup so a
2379            // restarted node can answer commitment-bound audits right
2380            // away — otherwise current() stays None for a full rotation
2381            // interval and audits silently fall back to legacy.
2382            //
2383            // After the first build, trigger an immediate neighbor-sync
2384            // round so the new commitment gossips out within seconds.
2385            // Without this, after a restart remote auditors keep pinning
2386            // the pre-restart (rotated-away) hash until their normal
2387            // sync cadence elapses — up to 1 h in the worst case,
2388            // during which time commitment-bound audits hit "unknown
2389            // commitment hash" -> Idle no-ops.
2390            // ML-DSA signatures are randomized so we cannot reproduce
2391            // the pre-restart hash; the only honest path to recovery
2392            // is fast re-gossip.
2393            // ADR-0004 A1: retention was reloaded in `new()` (before any task
2394            // spawned), so this initial rebuild no-ops when the key set is
2395            // unchanged — preserving the reloaded current pin; otherwise the
2396            // reloaded roots stay answerable as retained slots until their gossip
2397            // TTL lapses. Persistence is handled by the retention-persist loop.
2398            if let Err(e) =
2399                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
2400                    .await
2401            {
2402                warn!("Initial commitment build failed: {e}");
2403            } else {
2404                sync_trigger.notify_one();
2405            }
2406            loop {
2407                tokio::select! {
2408                    () = shutdown.cancelled() => break,
2409                    () = tokio::time::sleep(
2410                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
2411                    ) => {
2412                        if let Err(e) = rebuild_and_rotate_commitment(
2413                            &storage,
2414                            &identity,
2415                            &commitment_state,
2416                            &p2p,
2417                            &config,
2418                        ).await {
2419                            warn!("Commitment rotation failed: {e}");
2420                        }
2421                        // Piggyback a sweep of expired recent_provers
2422                        // entries on the rotation tick (same cadence,
2423                        // 1 h). is_credited_holder already honours the
2424                        // TTL on read, but the sweep reclaims memory
2425                        // for entries we'll never re-read.
2426                        let dropped = recent_provers.write().await.sweep_expired(
2427                            std::time::Instant::now()
2428                        );
2429                        if dropped > 0 {
2430                            debug!("recent_provers: swept {dropped} expired entries");
2431                        }
2432                    }
2433                }
2434            }
2435            debug!("Commitment rotation loop shut down");
2436        });
2437        self.task_handles.push(handle);
2438    }
2439
2440    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
2441    /// (write-on-change) so answerability — including gossip-stamp refreshes and
2442    /// rotations — survives a restart. Flushes once immediately, then every
2443    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
2444    fn start_retention_persist_loop(&mut self) {
2445        let commitment_state = Arc::clone(&self.commitment_state);
2446        let retention_path = self.retention_path.clone();
2447        let shutdown = self.shutdown.clone();
2448        let handle = tokio::spawn(async move {
2449            let mut last: Option<Vec<u8>> = None;
2450            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
2451            loop {
2452                tokio::select! {
2453                    () = shutdown.cancelled() => {
2454                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
2455                            .await;
2456                        break;
2457                    }
2458                    () = tokio::time::sleep(std::time::Duration::from_secs(
2459                        RETENTION_PERSIST_INTERVAL_SECS,
2460                    )) => {
2461                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
2462                            .await;
2463                    }
2464                }
2465            }
2466            debug!("Commitment retention persist loop shut down");
2467        });
2468        self.task_handles.push(handle);
2469    }
2470
2471    /// Periodically emit the cumulative replication traffic summaries: the
2472    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
2473    /// (V2-684). Both read process-global counter tables maintained by the
2474    /// encode/decode and serve choke points in [`protocol`]; needs no engine
2475    /// state.
2476    fn start_traffic_summary_loop(&mut self) {
2477        let shutdown = self.shutdown.clone();
2478        let handle = tokio::spawn(async move {
2479            loop {
2480                tokio::select! {
2481                    () = shutdown.cancelled() => break,
2482                    () = tokio::time::sleep(std::time::Duration::from_secs(
2483                        TRAFFIC_SUMMARY_INTERVAL_SECS,
2484                    )) => {
2485                        protocol::log_traffic_summary();
2486                        protocol::log_served_peers_summary();
2487                        protocol::log_audit_outcome_summary();
2488                    }
2489                }
2490            }
2491            debug!("Replication traffic summary loop shut down");
2492        });
2493        self.task_handles.push(handle);
2494    }
2495
2496    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
2497    fn start_fetch_worker(&mut self) {
2498        let p2p = Arc::clone(&self.p2p_node);
2499        let storage = Arc::clone(&self.storage);
2500        let queues = Arc::clone(&self.queues);
2501        let config = Arc::clone(&self.config);
2502        let shutdown = self.shutdown.clone();
2503        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2504        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2505        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2506        let concurrency = max_parallel_fetch();
2507
2508        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
2509
2510        let handle = tokio::spawn(async move {
2511            // Each in-flight future yields (key, Option<FetchOutcome>) so we
2512            // always recover the key — even if the inner task panics.
2513            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
2514
2515            loop {
2516                // Fill up to `concurrency` slots from the queue.
2517                {
2518                    let mut q = queues.write().await;
2519                    while in_flight.len() < concurrency {
2520                        let Some(candidate) = q.dequeue_fetch() else {
2521                            break;
2522                        };
2523                        let Some(&source) = candidate.sources.first() else {
2524                            warn!(
2525                                "Fetch candidate {} has no sources — dropping",
2526                                hex::encode(candidate.key)
2527                            );
2528                            continue;
2529                        };
2530                        q.start_fetch(candidate.key, source, candidate.sources.clone());
2531
2532                        let p2p = Arc::clone(&p2p);
2533                        let storage = Arc::clone(&storage);
2534                        let config = Arc::clone(&config);
2535                        let token = shutdown.clone();
2536                        let fetch_key = candidate.key;
2537                        in_flight.push(Box::pin(async move {
2538                            let handle = tokio::spawn(async move {
2539                                // Cancel-aware: abort when the engine shuts down.
2540                                tokio::select! {
2541                                    () = token.cancelled() => FetchOutcome {
2542                                        key: fetch_key,
2543                                        result: FetchResult::SourceFailed,
2544                                    },
2545                                    outcome = execute_single_fetch(
2546                                        p2p, storage, config, fetch_key, source,
2547                                    ) => outcome,
2548                                }
2549                            });
2550                            match handle.await {
2551                                Ok(outcome) => (outcome.key, Some(outcome)),
2552                                Err(e) => {
2553                                    error!(
2554                                        "Fetch task for {} panicked: {e}",
2555                                        hex::encode(fetch_key)
2556                                    );
2557                                    (fetch_key, None)
2558                                }
2559                            }
2560                        }));
2561                    }
2562                } // release queues write lock
2563
2564                if in_flight.is_empty() {
2565                    // No work — wait for new items or shutdown.
2566                    tokio::select! {
2567                        () = shutdown.cancelled() => break,
2568                        () = tokio::time::sleep(
2569                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
2570                        ) => continue,
2571                    }
2572                }
2573
2574                // Wait for the next fetch to complete and process the result.
2575                tokio::select! {
2576                    () = shutdown.cancelled() => break,
2577                    Some((key, maybe_outcome)) = in_flight.next() => {
2578                        let mut q = queues.write().await;
2579                        let terminal = if let Some(outcome) = maybe_outcome {
2580                            match outcome.result {
2581                                FetchResult::Stored => {
2582                                    q.complete_fetch(&key);
2583                                    true
2584                                }
2585                                FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
2586                                    if let Some(next_peer) = q.retry_fetch(&key) {
2587                                        // Spawn a new fetch task for the next source.
2588                                        let p2p = Arc::clone(&p2p);
2589                                        let storage = Arc::clone(&storage);
2590                                        let config = Arc::clone(&config);
2591                                        let token = shutdown.clone();
2592                                        let fetch_key = key;
2593                                        in_flight.push(Box::pin(async move {
2594                                            let handle = tokio::spawn(async move {
2595                                                tokio::select! {
2596                                                    () = token.cancelled() => FetchOutcome {
2597                                                        key: fetch_key,
2598                                                        result: FetchResult::SourceFailed,
2599                                                    },
2600                                                    outcome = execute_single_fetch(
2601                                                        p2p, storage, config, fetch_key, next_peer,
2602                                                    ) => outcome,
2603                                                }
2604                                            });
2605                                            match handle.await {
2606                                                Ok(outcome) => (outcome.key, Some(outcome)),
2607                                                Err(e) => {
2608                                                    error!(
2609                                                        "Fetch task for {} panicked: {e}",
2610                                                        hex::encode(fetch_key)
2611                                                    );
2612                                                    (fetch_key, None)
2613                                                }
2614                                            }
2615                                        }));
2616                                        false
2617                                    } else {
2618                                        q.complete_fetch(&key);
2619                                        true
2620                                    }
2621                                }
2622                            }
2623                        } else {
2624                            // Task panicked — reclaim the in-flight slot.
2625                            q.complete_fetch(&key);
2626                            true
2627                        };
2628
2629                        // Shrink bootstrap pending set on terminal exit.
2630                        if terminal {
2631                            drop(q); // release queues lock before acquiring bootstrap_state
2632                            if !bootstrap_state.read().await.is_drained() {
2633                                bootstrap_state.write().await.remove_key(&key);
2634                                let q = queues.read().await;
2635                                if bootstrap::check_bootstrap_drained(
2636                                    &bootstrap_state,
2637                                    &q,
2638                                )
2639                                .await
2640                                {
2641                                    complete_bootstrap(
2642                                        &is_bootstrapping,
2643                                        &bootstrap_complete_notify,
2644                                    ).await;
2645                                }
2646                            }
2647                        }
2648                    }
2649                }
2650            }
2651
2652            // Cancel and drain remaining in-flight fetches on shutdown.
2653            // The CancellationToken is already cancelled by this point, so
2654            // spawned tasks will see cancellation via their select! branches.
2655            while in_flight.next().await.is_some() {}
2656            debug!("Fetch worker shut down");
2657        });
2658        self.task_handles.push(handle);
2659    }
2660
2661    fn start_verification_worker(&mut self) {
2662        let p2p = Arc::clone(&self.p2p_node);
2663        let storage = Arc::clone(&self.storage);
2664        let queues = Arc::clone(&self.queues);
2665        let paid_list = Arc::clone(&self.paid_list);
2666        let config = Arc::clone(&self.config);
2667        let shutdown = self.shutdown.clone();
2668        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2669        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2670        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2671        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2672        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2673        let recent_provers = Arc::clone(&self.recent_provers);
2674
2675        let handle = tokio::spawn(async move {
2676            loop {
2677                tokio::select! {
2678                    () = shutdown.cancelled() => break,
2679                    () = tokio::time::sleep(
2680                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
2681                    ) => {
2682                        let ctx = VerificationCycleContext {
2683                            p2p_node: &p2p,
2684                            paid_list: &paid_list,
2685                            storage: &storage,
2686                            queues: &queues,
2687                            config: &config,
2688                            bootstrap_state: &bootstrap_state,
2689                            is_bootstrapping: &is_bootstrapping,
2690                            bootstrap_complete_notify: &bootstrap_complete_notify,
2691                            last_commitment_by_peer: &last_commitment_by_peer,
2692                            ever_capable_peers: &ever_capable_peers,
2693                            recent_provers: &recent_provers,
2694                        };
2695                        run_verification_cycle(ctx).await;
2696                    }
2697                }
2698            }
2699            debug!("Verification worker shut down");
2700        });
2701        self.task_handles.push(handle);
2702    }
2703
2704    /// Gap 3: Run a one-shot bootstrap sync on startup.
2705    ///
2706    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
2707    /// (indicating the routing table is populated) before snapshotting
2708    /// close neighbors. Falls back after a timeout so bootstrap nodes
2709    /// (which have no peers and therefore never receive the event) still
2710    /// proceed.
2711    ///
2712    /// After the gate, finds close neighbors, syncs with each in
2713    /// round-robin batches, admits returned hints into the verification
2714    /// pipeline, and tracks discovered keys for bootstrap drain detection.
2715    #[allow(clippy::too_many_lines)]
2716    fn start_bootstrap_sync(
2717        &mut self,
2718        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
2719    ) {
2720        let p2p = Arc::clone(&self.p2p_node);
2721        let storage = Arc::clone(&self.storage);
2722        let paid_list = Arc::clone(&self.paid_list);
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_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2730        let repair_proofs = Arc::clone(&self.repair_proofs);
2731        let my_commitment_state = Arc::clone(&self.commitment_state);
2732        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2733        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2734        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2735
2736        let handle = tokio::spawn(async move {
2737            // Wait for DHT bootstrap to complete before snapshotting
2738            // neighbors. The routing table is empty until saorsa-core
2739            // finishes its FIND_NODE rounds and bucket refreshes.
2740            let gate = bootstrap::wait_for_bootstrap_complete(
2741                dht_events,
2742                config.bootstrap_complete_timeout_secs,
2743                &shutdown,
2744            )
2745            .await;
2746
2747            if gate == bootstrap::BootstrapGateResult::Shutdown {
2748                return;
2749            }
2750
2751            let self_id = *p2p.peer_id();
2752            let neighbors =
2753                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
2754                    .await;
2755
2756            if neighbors.is_empty() {
2757                info!("Bootstrap sync: no close neighbors found, marking drained");
2758                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
2759                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
2760                return;
2761            }
2762
2763            let neighbor_count = neighbors.len();
2764            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
2765
2766            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
2767            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
2768                if shutdown.is_cancelled() {
2769                    break;
2770                }
2771
2772                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
2773                    batch,
2774                    &storage,
2775                    &paid_list,
2776                    &p2p,
2777                    config.close_group_size,
2778                    config.paid_list_close_group_size,
2779                )
2780                .await;
2781
2782                for peer in batch {
2783                    if shutdown.is_cancelled() {
2784                        break;
2785                    }
2786
2787                    // Re-read on each iteration so peers see current state.
2788                    let bootstrapping = *is_bootstrapping.read().await;
2789
2790                    bootstrap::increment_pending_requests(&bootstrap_state, 1).await;
2791
2792                    let hints = hints_by_peer.remove(peer).unwrap_or_default();
2793                    let outcome = neighbor_sync::sync_with_peer_with_hints(
2794                        peer,
2795                        &p2p,
2796                        &config,
2797                        bootstrapping,
2798                        hints,
2799                        // Atomically snapshot + mark-gossiped: emitted in the
2800                        // bootstrap-sync request, so we stay answerable for it
2801                        // (ADR-0002). One critical section avoids a TOCTOU where a
2802                        // concurrent retire/rotate drops the slot between read and
2803                        // mark.
2804                        my_commitment_state
2805                            .current_for_gossip()
2806                            .map(|b| b.commitment().clone()),
2807                    )
2808                    .await;
2809
2810                    bootstrap::decrement_pending_requests(&bootstrap_state, 1).await;
2811
2812                    if let Some(outcome) = outcome {
2813                        // Ingest the peer's piggybacked commitment from the
2814                        // response (same verification as the request path).
2815                        // Bootstrap is the FIRST gossip we receive from most
2816                        // peers, so this populates last_commitment_by_peer.
2817                        //
2818                        // We intentionally do NOT trigger a gossip-audit here:
2819                        // during bootstrap this node may itself still be
2820                        // bootstrapping (audits are gated on that), and the
2821                        // close-group/RT view is not yet stable. The peer is
2822                        // audited on the first STEADY-STATE neighbor-sync round
2823                        // after bootstrap drains (request + response paths both
2824                        // trigger), which is within one sync cycle — so caching
2825                        // the commitment here is sufficient and there is no
2826                        // coverage gap (ADR-0002).
2827                        ingest_peer_commitment(
2828                            peer,
2829                            outcome.response.commitment.as_ref(),
2830                            &p2p,
2831                            &last_commitment_by_peer,
2832                            &ever_capable_peers,
2833                            &sig_verify_attempts,
2834                        )
2835                        .await; // sig_verify_attempts in scope from line ~1080
2836
2837                        if !outcome.response.bootstrapping {
2838                            record_sent_replica_hints(
2839                                peer,
2840                                &outcome.sent_replica_hints,
2841                                &repair_proofs,
2842                                &sync_cycle_epoch,
2843                            )
2844                            .await;
2845                            // Admit hints into verification pipeline.
2846                            let outcome = admit_and_queue_hints(
2847                                &self_id,
2848                                peer,
2849                                &outcome.response.replica_hints,
2850                                &outcome.response.paid_hints,
2851                                &p2p,
2852                                &config,
2853                                &storage,
2854                                &paid_list,
2855                                &queues,
2856                            )
2857                            .await;
2858
2859                            // Track discovered keys for drain detection.
2860                            if !outcome.discovered.is_empty() {
2861                                bootstrap::track_discovered_keys(
2862                                    &bootstrap_state,
2863                                    &outcome.discovered,
2864                                )
2865                                .await;
2866                            }
2867
2868                            // Record / retire capacity rejections so the
2869                            // drain check correctly reflects whether each
2870                            // source still owes us re-hinted work after
2871                            // queue overflow.
2872                            if outcome.capacity_rejected_count > 0 {
2873                                bootstrap::note_capacity_rejected(&bootstrap_state, *peer).await;
2874                            } else {
2875                                bootstrap::clear_capacity_rejected(&bootstrap_state, peer).await;
2876                            }
2877                        }
2878                    }
2879                }
2880            }
2881
2882            // Check drain condition.
2883            {
2884                let q = queues.read().await;
2885                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
2886                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
2887                }
2888            }
2889
2890            info!("Bootstrap sync completed");
2891        });
2892        self.task_handles.push(handle);
2893    }
2894}
2895
2896// ===========================================================================
2897// Free functions for background tasks
2898// ===========================================================================
2899
2900/// Which ceiling rejected an audit-responder admission attempt.
2901///
2902/// Stable, machine-readable so a production log-scrape can bucket drops by
2903/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
2904/// single opaque "capacity reached" line; this splits the two distinct causes
2905/// so the next such investigation can tell a global-pool exhaustion (the whole
2906/// node is saturated) from a per-peer cap hit (one source is self-throttling)
2907/// without re-instrumenting.
2908///
2909/// This branch runs a SINGLE shared audit-responder pool for all challenge
2910/// kinds (responsible / subtree / byte), so there is no separate slow/fast
2911/// pool to distinguish here — the `kind=` log field already separates the
2912/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
2913/// dedicated slow pool is later split out, add its variants here.
2914#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2915enum AuditResponderRejectReason {
2916    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
2917    /// free; the per-peer cap was not the binding constraint.
2918    GlobalPoolFull,
2919    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
2920    /// share, so the global permit was never attempted.
2921    PerPeerCapFull,
2922}
2923
2924impl AuditResponderRejectReason {
2925    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
2926    /// frozen — production log tooling greps for them.
2927    fn as_str(self) -> &'static str {
2928        match self {
2929            Self::GlobalPoolFull => "global_pool_full",
2930            Self::PerPeerCapFull => "per_peer_cap_full",
2931        }
2932    }
2933}
2934
2935/// Why an audit-responder admission attempt failed, with the decision-time
2936/// capacity counters that let a drop be logged with full context.
2937///
2938/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
2939/// decision was made (the two ceilings are read under different locks, so they
2940/// are not a single atomic view), but they are exact enough to tell a saturated
2941/// node from a single self-throttling flooder.
2942#[derive(Debug, Clone, Copy)]
2943struct AuditResponderAdmissionFailure {
2944    reason: AuditResponderRejectReason,
2945    /// Global permits in use across the whole engine at decision time.
2946    global_inflight: usize,
2947    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
2948    global_limit: usize,
2949    /// In-flight audit responders already held for `source` at decision time.
2950    peer_inflight: u32,
2951    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
2952    peer_limit: u32,
2953}
2954
2955impl fmt::Display for AuditResponderAdmissionFailure {
2956    /// Renders the stable `reason=... global_inflight=... global_limit=...
2957    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
2958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2959        write!(
2960            f,
2961            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
2962            self.reason.as_str(),
2963            self.global_inflight,
2964            self.global_limit,
2965            self.peer_inflight,
2966            self.peer_limit,
2967        )
2968    }
2969}
2970
2971/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
2972/// on drop, decrements the PER-PEER in-flight count. Moving this into the
2973/// spawned task ties both bounds to the task's exact lifetime — no manual
2974/// decrement to forget on an early return or panic.
2975struct AuditResponderGuard {
2976    _permit: tokio::sync::OwnedSemaphorePermit,
2977    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
2978    peer: PeerId,
2979}
2980
2981impl Drop for AuditResponderGuard {
2982    fn drop(&mut self) {
2983        // Decrement (and prune to keep the map bounded) without blocking the
2984        // async runtime: a short lock on a tiny map.
2985        //
2986        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
2987        // with no spawn. Otherwise defer to a task — but only if a runtime is
2988        // actually current, so `Drop` during shutdown (no runtime) can never
2989        // panic. A missed decrement at shutdown is harmless: the whole map is
2990        // being dropped with the engine.
2991        let peer = self.peer;
2992        if let Ok(mut map) = self.inflight.try_write() {
2993            if let Some(n) = map.get_mut(&peer) {
2994                *n = n.saturating_sub(1);
2995                if *n == 0 {
2996                    map.remove(&peer);
2997                }
2998            }
2999            return;
3000        }
3001        if let Ok(handle) = tokio::runtime::Handle::try_current() {
3002            let inflight = Arc::clone(&self.inflight);
3003            handle.spawn(async move {
3004                let mut map = inflight.write().await;
3005                if let Some(n) = map.get_mut(&peer) {
3006                    *n = n.saturating_sub(1);
3007                    if *n == 0 {
3008                        map.remove(&peer);
3009                    }
3010                }
3011            });
3012        }
3013    }
3014}
3015
3016/// Try to admit one audit-responder task for `source`: take a global permit AND
3017/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
3018/// its decision-time counters (caller drops the challenge, leaving the remote
3019/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
3020/// so one flooder can neither exhaust the global pool's effect on others nor
3021/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
3022/// log exactly WHY the drop happened rather than a single opaque "capacity
3023/// reached".
3024async fn admit_audit_responder(
3025    semaphore: &Arc<Semaphore>,
3026    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
3027    source: &PeerId,
3028) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
3029    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
3030    let peer_limit = MAX_AUDIT_RESPONSES_PER_PEER;
3031    // `available_permits()` is a cheap atomic load; `global_limit - available`
3032    // is the best-effort in-flight count at decision time. Not synchronized with
3033    // the per-peer lock, so it is a snapshot, not a single atomic view.
3034    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
3035
3036    // Per-peer cap first (cheap, and the fairness-critical bound), committed
3037    // under the write lock so concurrent challenges from the same peer can't
3038    // both slip past the cap.
3039    {
3040        let mut map = inflight.write().await;
3041        let entry = map.entry(*source).or_insert(0);
3042        if *entry >= peer_limit {
3043            let peer_inflight = *entry;
3044            drop(map); // release before the (unrelated) semaphore read
3045            return Err(AuditResponderAdmissionFailure {
3046                reason: AuditResponderRejectReason::PerPeerCapFull,
3047                global_inflight: global_inflight(semaphore),
3048                global_limit,
3049                peer_inflight,
3050                peer_limit,
3051            });
3052        }
3053        *entry += 1;
3054    }
3055    // Then the global ceiling. If it's exhausted, give back the per-peer slot we
3056    // just claimed so it isn't leaked.
3057    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
3058        let peer_inflight = {
3059            let mut map = inflight.write().await;
3060            map.remove(source).map_or(0, |n| {
3061                // Report the per-peer occupancy AFTER releasing our rolled-back
3062                // slot: the share still held by this source's other in-flight
3063                // tasks (below the cap, since the per-peer check passed).
3064                let remaining = n.saturating_sub(1);
3065                if remaining > 0 {
3066                    map.insert(*source, remaining);
3067                }
3068                remaining
3069            })
3070        };
3071        return Err(AuditResponderAdmissionFailure {
3072            reason: AuditResponderRejectReason::GlobalPoolFull,
3073            global_inflight: global_inflight(semaphore),
3074            global_limit,
3075            peer_inflight,
3076            peer_limit,
3077        });
3078    };
3079    Ok(AuditResponderGuard {
3080        _permit: permit,
3081        inflight: Arc::clone(inflight),
3082        peer: *source,
3083    })
3084}
3085
3086/// Handle an incoming replication protocol message.
3087///
3088/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
3089/// request-response path and the response must be sent via `send_response`
3090/// so saorsa-core can route it back to the waiting `send_request` caller.
3091#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
3092async fn handle_replication_message(
3093    source: &PeerId,
3094    data: &[u8],
3095    p2p_node: &Arc<P2PNode>,
3096    storage: &Arc<LmdbStorage>,
3097    paid_list: &Arc<PaidList>,
3098    payment_verifier: &Arc<PaymentVerifier>,
3099    queues: &Arc<RwLock<ReplicationQueues>>,
3100    config: &ReplicationConfig,
3101    is_bootstrapping: &Arc<RwLock<bool>>,
3102    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3103    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3104    sync_cycle_epoch: &Arc<RwLock<u64>>,
3105    repair_proofs: &Arc<RwLock<RepairProofs>>,
3106    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
3107    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
3108    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
3109    my_commitment_state: &Arc<ResponderCommitmentState>,
3110    gossip_audit: &GossipAuditTrigger,
3111    audit_responder_semaphore: &Arc<Semaphore>,
3112    audit_responder_inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
3113    rr_message_id: Option<&str>,
3114) -> Result<()> {
3115    let msg = ReplicationMessage::decode(data)
3116        .map_err(|e| Error::Protocol(format!("Failed to decode replication message: {e}")))?;
3117
3118    match msg.body {
3119        ReplicationMessageBody::FreshReplicationOffer(ref offer) => {
3120            handle_fresh_offer(
3121                source,
3122                offer,
3123                storage,
3124                paid_list,
3125                payment_verifier,
3126                p2p_node,
3127                config,
3128                msg.request_id,
3129                rr_message_id,
3130            )
3131            .await
3132        }
3133        ReplicationMessageBody::PaidNotify(ref notify) => {
3134            handle_paid_notify(
3135                source,
3136                notify,
3137                paid_list,
3138                payment_verifier,
3139                p2p_node,
3140                config,
3141            )
3142            .await
3143        }
3144        ReplicationMessageBody::NeighborSyncRequest(ref request) => {
3145            let bootstrapping = *is_bootstrapping.read().await;
3146            // Phase-3 storage-bound audit: store the sender's
3147            // commitment for use as `expected_commitment_hash` in
3148            // future audits. Verify signature before storing so a peer
3149            // cannot inject a forged commitment for someone else.
3150            if let Some(target) = ingest_peer_commitment(
3151                source,
3152                request.commitment.as_ref(),
3153                p2p_node,
3154                last_commitment_by_peer,
3155                ever_capable_peers,
3156                sig_verify_attempts,
3157            )
3158            .await
3159            {
3160                maybe_trigger_gossip_audit(gossip_audit, source, target).await;
3161            }
3162            handle_neighbor_sync_request(
3163                source,
3164                request,
3165                p2p_node,
3166                storage,
3167                paid_list,
3168                queues,
3169                config,
3170                bootstrapping,
3171                bootstrap_state,
3172                sync_history,
3173                sync_cycle_epoch,
3174                repair_proofs,
3175                // Atomically snapshot + mark-gossiped: emitted in the sync
3176                // response, so we must stay answerable for it (ADR-0002).
3177                my_commitment_state
3178                    .current_for_gossip()
3179                    .map(|b| b.commitment().clone()),
3180                msg.request_id,
3181                rr_message_id,
3182            )
3183            .await
3184        }
3185        ReplicationMessageBody::VerificationRequest(ref request) => {
3186            handle_verification_request(
3187                source,
3188                request,
3189                storage,
3190                paid_list,
3191                p2p_node,
3192                msg.request_id,
3193                rr_message_id,
3194            )
3195            .await
3196        }
3197        ReplicationMessageBody::FetchRequest(ref request) => {
3198            handle_fetch_request(
3199                source,
3200                request,
3201                storage,
3202                p2p_node,
3203                msg.request_id,
3204                rr_message_id,
3205            )
3206            .await
3207        }
3208        ReplicationMessageBody::AuditChallenge(challenge) => {
3209            // Responsible-chunk audit (audit #2) responder: answer with per-key
3210            // possession digests. This same handler also answers the
3211            // prune-confirmation audit, which sends the same `AuditChallenge`
3212            // wire message.
3213            //
3214            // Answering digests the stored bytes of every challenged key, so —
3215            // like the subtree/byte audits below — run it on a detached task off
3216            // this serial message loop. Handling it inline lets one challenge
3217            // block all other replication traffic until its digests complete
3218            // (head-of-line blocking). The same flood-fair admission applies: a
3219            // global ceiling AND a per-peer cap, dropping the challenge if either
3220            // is hit. Responsible/prune audit timeouts are penalised by the
3221            // caller, so the caps must remain high enough for honest audit load;
3222            // the per-peer share still prevents one flooder from starving others.
3223            let guard = match admit_audit_responder(
3224                audit_responder_semaphore,
3225                audit_responder_inflight,
3226                source,
3227            )
3228            .await
3229            {
3230                Ok(guard) => guard,
3231                Err(failure) => {
3232                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
3233                    warn!(
3234                        "Audit challenge reply not sent: kind=responsible response=dropped \
3235                         source={source} {failure}"
3236                    );
3237                    return Ok(());
3238                }
3239            };
3240            let bootstrapping = *is_bootstrapping.read().await;
3241            let storage = Arc::clone(storage);
3242            let p2p_node = Arc::clone(p2p_node);
3243            let source = *source;
3244            let request_id = msg.request_id;
3245            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
3246            tokio::spawn(async move {
3247                let _guard = guard; // global permit + per-peer slot, held until done
3248                if let Err(e) = handle_audit_challenge_msg(
3249                    &source,
3250                    &challenge,
3251                    &storage,
3252                    &p2p_node,
3253                    bootstrapping,
3254                    request_id,
3255                    rr_message_id.as_deref(),
3256                )
3257                .await
3258                {
3259                    debug!("Audit challenge from {source} error: {e}");
3260                }
3261            });
3262            Ok(())
3263        }
3264        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
3265            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
3266            // responder rebuilds the WHOLE nonce-selected subtree, reading every
3267            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
3268            // detached task so this serial message loop is never blocked on disk
3269            // I/O — otherwise one audit stalls all replication traffic (§5).
3270            //
3271            // A bounded, flood-fair admission restores backpressure (codex#1 +
3272            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
3273            // we drop this challenge. Subtree auditors grace timeout
3274            // non-responses, so capacity drops throttle flooders without turning
3275            // into trust penalties (and one source cannot starve other peers,
3276            // since its share is capped per-peer).
3277            info!(
3278                "Audit challenge received: kind=subtree source={source} request_response={}",
3279                rr_message_id.is_some(),
3280            );
3281            let guard = match admit_audit_responder(
3282                audit_responder_semaphore,
3283                audit_responder_inflight,
3284                source,
3285            )
3286            .await
3287            {
3288                Ok(guard) => guard,
3289                Err(failure) => {
3290                    protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
3291                    warn!(
3292                        "Audit challenge reply not sent: kind=subtree response=dropped \
3293                         source={source} {failure}"
3294                    );
3295                    return Ok(());
3296                }
3297            };
3298            let bootstrapping = *is_bootstrapping.read().await;
3299            let storage = Arc::clone(storage);
3300            let p2p_node = Arc::clone(p2p_node);
3301            let my_commitment_state = Arc::clone(my_commitment_state);
3302            let source = *source;
3303            let request_id = msg.request_id;
3304            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
3305            tokio::spawn(async move {
3306                let _guard = guard; // global permit + per-peer slot, held until done
3307                let response = storage_commitment_audit::handle_subtree_challenge(
3308                    &challenge,
3309                    &storage,
3310                    p2p_node.peer_id(),
3311                    bootstrapping,
3312                    Some(&my_commitment_state),
3313                )
3314                .await;
3315                let response_kind = subtree_audit_response_kind(&response);
3316                let sent = send_replication_response_checked(
3317                    &source,
3318                    &p2p_node,
3319                    request_id,
3320                    ReplicationMessageBody::SubtreeAuditResponse(response),
3321                    rr_message_id.as_deref(),
3322                )
3323                .await;
3324                if sent {
3325                    info!(
3326                        "Audit challenge reply sent: kind=subtree response={response_kind} \
3327                         source={source} request_response={}",
3328                        rr_message_id.is_some(),
3329                    );
3330                } else {
3331                    warn!(
3332                        "Audit challenge reply not sent: kind=subtree response={response_kind} \
3333                         source={source} request_response={}",
3334                        rr_message_id.is_some(),
3335                    );
3336                }
3337            });
3338            Ok(())
3339        }
3340        ReplicationMessageBody::SubtreeByteChallenge(challenge) => {
3341            // Round 2 of the storage audit (ADR-0002): serve the original bytes
3342            // for the auditor's spot-check keys, or signal `Absent` for a
3343            // committed key we can no longer produce. Reads chunk bytes from
3344            // disk, so likewise spawned off the serial loop (§5) under the same
3345            // flood-fair admission (codex#1 + codex-r2 A).
3346            info!(
3347                "Audit challenge received: kind=byte source={source} request_response={}",
3348                rr_message_id.is_some(),
3349            );
3350            let guard = match admit_audit_responder(
3351                audit_responder_semaphore,
3352                audit_responder_inflight,
3353                source,
3354            )
3355            .await
3356            {
3357                Ok(guard) => guard,
3358                Err(failure) => {
3359                    protocol::record_audit_drop(protocol::AuditDropKind::Byte);
3360                    warn!(
3361                        "Audit challenge reply not sent: kind=byte response=dropped \
3362                         source={source} {failure}"
3363                    );
3364                    return Ok(());
3365                }
3366            };
3367            let bootstrapping = *is_bootstrapping.read().await;
3368            let storage = Arc::clone(storage);
3369            let p2p_node = Arc::clone(p2p_node);
3370            let my_commitment_state = Arc::clone(my_commitment_state);
3371            let source = *source;
3372            let request_id = msg.request_id;
3373            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
3374            tokio::spawn(async move {
3375                let _guard = guard; // global permit + per-peer slot, held until done
3376                let response = storage_commitment_audit::handle_subtree_byte_challenge(
3377                    &challenge,
3378                    &storage,
3379                    p2p_node.peer_id(),
3380                    bootstrapping,
3381                    Some(&my_commitment_state),
3382                )
3383                .await;
3384                let response_kind = subtree_byte_response_kind(&response);
3385                let sent = send_replication_response_checked(
3386                    &source,
3387                    &p2p_node,
3388                    request_id,
3389                    ReplicationMessageBody::SubtreeByteResponse(response),
3390                    rr_message_id.as_deref(),
3391                )
3392                .await;
3393                if sent {
3394                    info!(
3395                        "Audit challenge reply sent: kind=byte response={response_kind} \
3396                         source={source} request_response={}",
3397                        rr_message_id.is_some(),
3398                    );
3399                } else {
3400                    warn!(
3401                        "Audit challenge reply not sent: kind=byte response={response_kind} \
3402                         source={source} request_response={}",
3403                        rr_message_id.is_some(),
3404                    );
3405                }
3406            });
3407            Ok(())
3408        }
3409        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
3410            // ADR-0004: answer a commitment-by-pin fetch from the retained set
3411            // only. `lookup_by_hash` is an allocation-light read over the
3412            // bounded slot set; it returns the live current commitment or any
3413            // still-answerable recently-gossiped/quoted one. A miss is reported
3414            // as `NotRetained` (graced, never confirmed) rather than an error,
3415            // so an aged-out pin can never brand an honest node.
3416            //
3417            // Reuse the audit-responder admission guard (global ceiling + per-peer
3418            // cap) so a flood of fetches cannot drive unbounded commitment
3419            // clone/encode/send work; over-limit is dropped, which the fetching
3420            // peer graces exactly like a missed audit response.
3421            let _guard = match admit_audit_responder(
3422                audit_responder_semaphore,
3423                audit_responder_inflight,
3424                source,
3425            )
3426            .await
3427            {
3428                Ok(guard) => guard,
3429                Err(failure) => {
3430                    debug!("GetCommitmentByPin from {source} dropped: {failure}");
3431                    return Ok(());
3432                }
3433            };
3434            let response = my_commitment_state.lookup_by_hash(&request.pin).map_or(
3435                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
3436                |built| protocol::GetCommitmentByPinResponse::Found {
3437                    commitment: built.commitment().clone(),
3438                },
3439            );
3440            send_replication_response(
3441                source,
3442                p2p_node,
3443                msg.request_id,
3444                ReplicationMessageBody::GetCommitmentByPinResponse(response),
3445                rr_message_id,
3446            )
3447            .await;
3448            Ok(())
3449        }
3450        // Response messages are handled by their respective request initiators.
3451        ReplicationMessageBody::FreshReplicationResponse(_)
3452        | ReplicationMessageBody::NeighborSyncResponse(_)
3453        | ReplicationMessageBody::VerificationResponse(_)
3454        | ReplicationMessageBody::FetchResponse(_)
3455        | ReplicationMessageBody::AuditResponse(_)
3456        | ReplicationMessageBody::SubtreeAuditResponse(_)
3457        | ReplicationMessageBody::SubtreeByteResponse(_)
3458        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
3459    }
3460}
3461
3462// ---------------------------------------------------------------------------
3463// Per-message-type handlers
3464// ---------------------------------------------------------------------------
3465
3466#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
3467async fn handle_fresh_offer(
3468    source: &PeerId,
3469    offer: &protocol::FreshReplicationOffer,
3470    storage: &Arc<LmdbStorage>,
3471    paid_list: &Arc<PaidList>,
3472    payment_verifier: &Arc<PaymentVerifier>,
3473    p2p_node: &Arc<P2PNode>,
3474    config: &ReplicationConfig,
3475    request_id: u64,
3476    rr_message_id: Option<&str>,
3477) -> Result<()> {
3478    let self_id = *p2p_node.peer_id();
3479
3480    // Rule 5: reject if PoP is missing.
3481    if offer.proof_of_payment.is_empty() {
3482        send_replication_response(
3483            source,
3484            p2p_node,
3485            request_id,
3486            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
3487                key: offer.key,
3488                reason: "Missing proof of payment".to_string(),
3489            }),
3490            rr_message_id,
3491        )
3492        .await;
3493        return Ok(());
3494    }
3495
3496    // Enforce chunk size invariant: the normal PUT path rejects data larger
3497    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
3498    // prevent peers from pushing oversized records through replication.
3499    if offer.data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
3500        warn!(
3501            "Rejecting fresh offer for key {}: data size {} exceeds MAX_CHUNK_SIZE {}",
3502            hex::encode(offer.key),
3503            offer.data.len(),
3504            crate::ant_protocol::MAX_CHUNK_SIZE,
3505        );
3506        p2p_node
3507            .report_trust_event(
3508                source,
3509                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
3510            )
3511            .await;
3512        send_replication_response(
3513            source,
3514            p2p_node,
3515            request_id,
3516            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
3517                key: offer.key,
3518                reason: format!(
3519                    "Data size {} exceeds maximum chunk size {}",
3520                    offer.data.len(),
3521                    crate::ant_protocol::MAX_CHUNK_SIZE,
3522                ),
3523            }),
3524            rr_message_id,
3525        )
3526        .await;
3527        return Ok(());
3528    }
3529
3530    // Mirror the normal PUT path: the advertised key must be the content
3531    // address of the supplied bytes before any expensive payment verification.
3532    let computed_key = crate::client::compute_address(&offer.data);
3533    if computed_key != offer.key {
3534        warn!(
3535            "Rejecting fresh offer for key {}: content address mismatch, computed {}",
3536            hex::encode(offer.key),
3537            hex::encode(computed_key),
3538        );
3539        p2p_node
3540            .report_trust_event(
3541                source,
3542                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
3543            )
3544            .await;
3545        send_replication_response(
3546            source,
3547            p2p_node,
3548            request_id,
3549            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
3550                key: offer.key,
3551                reason: format!(
3552                    "Content address mismatch: expected {}, computed {}",
3553                    hex::encode(offer.key),
3554                    hex::encode(computed_key),
3555                ),
3556            }),
3557            rr_message_id,
3558        )
3559        .await;
3560        return Ok(());
3561    }
3562
3563    // Rule 7: check storage admission. Fresh chunk receivers accept across the
3564    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
3565    // the same width client PUTs use), not just the close group plus a small
3566    // margin (ADR-0003). During full-node shunning a healthy replica's routing
3567    // table may still list closer full nodes it hasn't evicted yet, ranking it
3568    // outside the narrow window in its own view; the wider accept window absorbs
3569    // that transient skew so the chunk still lands. Retention (pruning) stays at
3570    // `storage_admission_width`, so steady-state replication is unchanged.
3571    if !admission::is_responsible(
3572        &self_id,
3573        &offer.key,
3574        p2p_node,
3575        config.paid_list_close_group_size,
3576    )
3577    .await
3578    {
3579        send_replication_response(
3580            source,
3581            p2p_node,
3582            request_id,
3583            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
3584                key: offer.key,
3585                reason: "Not in storage-admission range for this key".to_string(),
3586            }),
3587            rr_message_id,
3588        )
3589        .await;
3590        return Ok(());
3591    }
3592
3593    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
3594    // never store this record, so reject it before the expensive payment
3595    // verification (EVM on-chain query / merkle pool work) rather than verifying
3596    // and only then failing at `storage.put` below. Reuses the cached capacity
3597    // check (passing results only, so freed space is detected promptly), and the
3598    // store path keeps its own check as defence-in-depth.
3599    if let Err(e) = storage.check_capacity() {
3600        info!(
3601            target: "ant_node::storage::disk_precheck",
3602            key = %hex::encode(offer.key),
3603            "Rejecting fresh replication offer before payment verification: {e}"
3604        );
3605        send_replication_response(
3606            source,
3607            p2p_node,
3608            request_id,
3609            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
3610                key: offer.key,
3611                reason: e.to_string(),
3612            }),
3613            rr_message_id,
3614        )
3615        .await;
3616        return Ok(());
3617    }
3618
3619    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
3620    // part of the immediate write fan-out: this receiver is about to store the
3621    // record as if the client had PUT it here directly. Storage admission
3622    // was checked above before proof work. FreshReplication verification is
3623    // identical to ClientPut — store-strength cache semantics, paid-quote
3624    // issuer K-closeness checks for single-node proofs, merkle candidate
3625    // closeness for merkle proofs, and the same price-floor policy — the
3626    // distinct context only labels price-floor telemetry.
3627    match payment_verifier
3628        .verify_payment(
3629            &offer.key,
3630            Some(&offer.proof_of_payment),
3631            fresh_offer_payment_context(),
3632        )
3633        .await
3634    {
3635        Ok(status) if status.can_store() => {
3636            debug!(
3637                "PoP validated for fresh offer key {}",
3638                hex::encode(offer.key)
3639            );
3640        }
3641        Ok(_) => {
3642            send_replication_response(
3643                source,
3644                p2p_node,
3645                request_id,
3646                ReplicationMessageBody::FreshReplicationResponse(
3647                    FreshReplicationResponse::Rejected {
3648                        key: offer.key,
3649                        reason: "Payment verification failed: payment required".to_string(),
3650                    },
3651                ),
3652                rr_message_id,
3653            )
3654            .await;
3655            return Ok(());
3656        }
3657        Err(e) => {
3658            warn!(
3659                "PoP verification error for key {}: {e}",
3660                hex::encode(offer.key)
3661            );
3662            send_replication_response(
3663                source,
3664                p2p_node,
3665                request_id,
3666                ReplicationMessageBody::FreshReplicationResponse(
3667                    FreshReplicationResponse::Rejected {
3668                        key: offer.key,
3669                        reason: format!("Payment verification error: {e}"),
3670                    },
3671                ),
3672                rr_message_id,
3673            )
3674            .await;
3675            return Ok(());
3676        }
3677    }
3678
3679    // Rule 6: add to PaidForList.
3680    if let Err(e) = paid_list.insert(&offer.key).await {
3681        warn!("Failed to add key to PaidForList: {e}");
3682    }
3683
3684    // Store the record.
3685    match storage.put(&offer.key, &offer.data).await {
3686        Ok(_) => {
3687            send_replication_response(
3688                source,
3689                p2p_node,
3690                request_id,
3691                ReplicationMessageBody::FreshReplicationResponse(
3692                    FreshReplicationResponse::Accepted { key: offer.key },
3693                ),
3694                rr_message_id,
3695            )
3696            .await;
3697        }
3698        Err(e) => {
3699            send_replication_response(
3700                source,
3701                p2p_node,
3702                request_id,
3703                ReplicationMessageBody::FreshReplicationResponse(
3704                    FreshReplicationResponse::Rejected {
3705                        key: offer.key,
3706                        reason: e.to_string(),
3707                    },
3708                ),
3709                rr_message_id,
3710            )
3711            .await;
3712        }
3713    }
3714
3715    Ok(())
3716}
3717
3718async fn handle_paid_notify(
3719    _source: &PeerId,
3720    notify: &protocol::PaidNotify,
3721    paid_list: &Arc<PaidList>,
3722    payment_verifier: &Arc<PaymentVerifier>,
3723    p2p_node: &Arc<P2PNode>,
3724    config: &ReplicationConfig,
3725) -> Result<()> {
3726    let self_id = *p2p_node.peer_id();
3727
3728    // Rule 3: validate PoP presence before adding.
3729    if notify.proof_of_payment.is_empty() {
3730        return Ok(());
3731    }
3732
3733    // Check if we're in PaidCloseGroup for this key.
3734    if !admission::is_in_paid_close_group(
3735        &self_id,
3736        &notify.key,
3737        p2p_node,
3738        config.paid_list_close_group_size,
3739    )
3740    .await
3741    {
3742        return Ok(());
3743    }
3744
3745    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
3746    // paid-list metadata, so local paid-list close-group membership was checked
3747    // above before proof work. The verifier then runs the same payment proof
3748    // checks as ClientPut while writing a paid-list-strength cache entry.
3749    match payment_verifier
3750        .verify_payment(
3751            &notify.key,
3752            Some(&notify.proof_of_payment),
3753            paid_notify_payment_context(),
3754        )
3755        .await
3756    {
3757        Ok(status) if status.can_store() => {
3758            debug!(
3759                "PoP validated for paid notify key {}",
3760                hex::encode(notify.key)
3761            );
3762        }
3763        Ok(_) => {
3764            warn!(
3765                "Paid notify rejected: payment required for key {}",
3766                hex::encode(notify.key)
3767            );
3768            return Ok(());
3769        }
3770        Err(e) => {
3771            warn!(
3772                "PoP verification error for paid notify key {}: {e}",
3773                hex::encode(notify.key)
3774            );
3775            return Ok(());
3776        }
3777    }
3778
3779    if let Err(e) = paid_list.insert(&notify.key).await {
3780        warn!("Failed to add paid notify key to PaidForList: {e}");
3781    }
3782
3783    Ok(())
3784}
3785
3786#[allow(clippy::too_many_arguments)]
3787async fn handle_neighbor_sync_request(
3788    source: &PeerId,
3789    request: &protocol::NeighborSyncRequest,
3790    p2p_node: &Arc<P2PNode>,
3791    storage: &Arc<LmdbStorage>,
3792    paid_list: &Arc<PaidList>,
3793    queues: &Arc<RwLock<ReplicationQueues>>,
3794    config: &ReplicationConfig,
3795    is_bootstrapping: bool,
3796    bootstrap_state: &Arc<RwLock<BootstrapState>>,
3797    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
3798    sync_cycle_epoch: &Arc<RwLock<u64>>,
3799    repair_proofs: &Arc<RwLock<RepairProofs>>,
3800    my_commitment: Option<StorageCommitment>,
3801    request_id: u64,
3802    rr_message_id: Option<&str>,
3803) -> Result<()> {
3804    let self_id = *p2p_node.peer_id();
3805
3806    // No per-request hint count limit: the wire message size limit
3807    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
3808    // challenges, sync hints don't drive expensive computation — they just
3809    // enter the verification queue. A per-request limit here would break
3810    // bootstrap replication for newly-joined nodes with 0 stored chunks.
3811
3812    // Build response (outbound hints).
3813    let (response, sent_replica_hints, sender_in_rt) =
3814        neighbor_sync::handle_sync_request_with_proofs(
3815            source,
3816            request,
3817            p2p_node,
3818            storage,
3819            paid_list,
3820            config,
3821            is_bootstrapping,
3822            my_commitment.clone(),
3823        )
3824        .await;
3825
3826    // Send response.
3827    let response_sent = send_replication_response_checked(
3828        source,
3829        p2p_node,
3830        request_id,
3831        ReplicationMessageBody::NeighborSyncResponse(response),
3832        rr_message_id,
3833    )
3834    .await;
3835
3836    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
3837    if !sender_in_rt {
3838        return Ok(());
3839    }
3840
3841    // Update sync history for this peer before recording repair proofs so a
3842    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
3843    {
3844        let mut history = sync_history.write().await;
3845        let record = history.entry(*source).or_insert(PeerSyncRecord {
3846            last_sync: None,
3847            cycles_since_sync: 0,
3848        });
3849        record.last_sync = Some(Instant::now());
3850        record.cycles_since_sync = 0;
3851    }
3852
3853    if response_sent && !request.bootstrapping {
3854        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
3855            .await;
3856    }
3857
3858    // Admit inbound hints and queue for verification.
3859    let outcome = admit_and_queue_hints(
3860        &self_id,
3861        source,
3862        &request.replica_hints,
3863        &request.paid_hints,
3864        p2p_node,
3865        config,
3866        storage,
3867        paid_list,
3868        queues,
3869    )
3870    .await;
3871
3872    // Track discovered keys for bootstrap drain detection so that hints
3873    // admitted via inbound sync requests are not missed. Capacity-rejected
3874    // hints keep this source on the "not yet drained" list until its next
3875    // sync re-admits them; a clean cycle clears the source.
3876    if is_bootstrapping {
3877        if !outcome.discovered.is_empty() {
3878            bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
3879        }
3880        if outcome.capacity_rejected_count > 0 {
3881            bootstrap::note_capacity_rejected(bootstrap_state, *source).await;
3882        } else {
3883            bootstrap::clear_capacity_rejected(bootstrap_state, source).await;
3884        }
3885    }
3886
3887    Ok(())
3888}
3889
3890async fn handle_verification_request(
3891    source: &PeerId,
3892    request: &protocol::VerificationRequest,
3893    storage: &Arc<LmdbStorage>,
3894    paid_list: &Arc<PaidList>,
3895    p2p_node: &Arc<P2PNode>,
3896    request_id: u64,
3897    rr_message_id: Option<&str>,
3898) -> Result<()> {
3899    // No per-request key count limit: the wire message size limit
3900    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Verification
3901    // does cheap storage lookups per key, not expensive computation like
3902    // audit digest generation.
3903
3904    #[allow(clippy::cast_possible_truncation)]
3905    let keys_len = request.keys.len() as u32;
3906    let paid_check_set: HashSet<u32> = request
3907        .paid_list_check_indices
3908        .iter()
3909        .copied()
3910        .filter(|&idx| {
3911            if idx >= keys_len {
3912                warn!(
3913                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
3914                    request.keys.len(),
3915                );
3916                false
3917            } else {
3918                true
3919            }
3920        })
3921        .collect();
3922
3923    let mut results = Vec::with_capacity(request.keys.len());
3924    for (i, key) in request.keys.iter().enumerate() {
3925        let present = storage.exists(key).unwrap_or(false);
3926        let paid = if paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX)) {
3927            Some(paid_list.contains(key).unwrap_or(false))
3928        } else {
3929            None
3930        };
3931        results.push(protocol::KeyVerificationResult {
3932            key: *key,
3933            present,
3934            paid,
3935        });
3936    }
3937
3938    send_replication_response(
3939        source,
3940        p2p_node,
3941        request_id,
3942        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
3943        rr_message_id,
3944    )
3945    .await;
3946
3947    Ok(())
3948}
3949
3950async fn handle_fetch_request(
3951    source: &PeerId,
3952    request: &protocol::FetchRequest,
3953    storage: &Arc<LmdbStorage>,
3954    p2p_node: &Arc<P2PNode>,
3955    request_id: u64,
3956    rr_message_id: Option<&str>,
3957) -> Result<()> {
3958    let response = match storage.get(&request.key).await {
3959        Ok(Some(data)) => protocol::FetchResponse::Success {
3960            key: request.key,
3961            data,
3962        },
3963        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
3964        Err(e) => protocol::FetchResponse::Error {
3965            key: request.key,
3966            reason: format!("{e}"),
3967        },
3968    };
3969
3970    send_replication_response(
3971        source,
3972        p2p_node,
3973        request_id,
3974        ReplicationMessageBody::FetchResponse(response),
3975        rr_message_id,
3976    )
3977    .await;
3978
3979    Ok(())
3980}
3981
3982/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
3983/// the prune-confirmation audit, which reuses the same wire message): reply with
3984/// per-key possession digests.
3985async fn handle_audit_challenge_msg(
3986    source: &PeerId,
3987    challenge: &protocol::AuditChallenge,
3988    storage: &Arc<LmdbStorage>,
3989    p2p_node: &Arc<P2PNode>,
3990    is_bootstrapping: bool,
3991    request_id: u64,
3992    rr_message_id: Option<&str>,
3993) -> Result<()> {
3994    #[allow(clippy::cast_possible_truncation)]
3995    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
3996    info!(
3997        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
3998        challenge.keys.len(),
3999        is_bootstrapping,
4000        rr_message_id.is_some(),
4001    );
4002
4003    let response = audit::handle_audit_challenge(
4004        challenge,
4005        storage,
4006        p2p_node.peer_id(),
4007        is_bootstrapping,
4008        stored_chunks,
4009    )
4010    .await;
4011    let response_kind = audit_response_kind(&response);
4012
4013    let sent = send_replication_response_checked(
4014        source,
4015        p2p_node,
4016        request_id,
4017        ReplicationMessageBody::AuditResponse(response),
4018        rr_message_id,
4019    )
4020    .await;
4021    if sent {
4022        info!(
4023            "Audit challenge reply sent: kind=responsible response={} keys={} request_response={}",
4024            response_kind,
4025            challenge.keys.len(),
4026            rr_message_id.is_some(),
4027        );
4028    } else {
4029        warn!(
4030            "Audit challenge reply not sent: kind=responsible response={} keys={} request_response={}",
4031            response_kind,
4032            challenge.keys.len(),
4033            rr_message_id.is_some(),
4034        );
4035    }
4036
4037    Ok(())
4038}
4039
4040fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
4041    match response {
4042        protocol::AuditResponse::Digests { .. } => "digests",
4043        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
4044        protocol::AuditResponse::Rejected { .. } => "rejected",
4045    }
4046}
4047
4048fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
4049    match response {
4050        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
4051        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
4052        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
4053    }
4054}
4055
4056fn subtree_byte_response_kind(response: &protocol::SubtreeByteResponse) -> &'static str {
4057    match response {
4058        protocol::SubtreeByteResponse::Items { .. } => "items",
4059        protocol::SubtreeByteResponse::Bootstrapping { .. } => "bootstrapping",
4060        protocol::SubtreeByteResponse::Rejected { .. } => "rejected",
4061    }
4062}
4063
4064// ---------------------------------------------------------------------------
4065// Message sending helper
4066// ---------------------------------------------------------------------------
4067
4068/// Send a replication response message as a best-effort reply.
4069///
4070/// Encode and send failures are logged by the checked helper. Most response
4071/// paths do not need to branch on send success, so this wrapper keeps those
4072/// call sites explicit about their best-effort behavior.
4073async fn send_replication_response(
4074    peer: &PeerId,
4075    p2p_node: &Arc<P2PNode>,
4076    request_id: u64,
4077    body: ReplicationMessageBody,
4078    rr_message_id: Option<&str>,
4079) {
4080    let _ =
4081        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id).await;
4082}
4083
4084/// Send a replication response message and report whether it was accepted.
4085///
4086/// Returns `true` after the message is encoded and accepted by the P2P send
4087/// path. Returns `false` after logging an encode or send failure. Repair-proof
4088/// recording uses this to avoid trusting hints that were not actually sent.
4089///
4090/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
4091/// request-response path so saorsa-core can route it back to the caller's
4092/// `send_request` future. Otherwise it is sent as a plain message.
4093async fn send_replication_response_checked(
4094    peer: &PeerId,
4095    p2p_node: &Arc<P2PNode>,
4096    request_id: u64,
4097    body: ReplicationMessageBody,
4098    rr_message_id: Option<&str>,
4099) -> bool {
4100    let msg = ReplicationMessage { request_id, body };
4101    let encoded = match msg.encode() {
4102        Ok(data) => data,
4103        Err(e) => {
4104            warn!("Failed to encode replication response: {e}");
4105            return false;
4106        }
4107    };
4108    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
4109    // `FetchResponse` + `SubtreeByteResponse` carry ~99% of served bytes;
4110    // `NeighborSyncResponse` is included for completeness. Other response
4111    // variants (verification/audit/commitment) are intentionally excluded.
4112    if matches!(
4113        msg.body,
4114        ReplicationMessageBody::FetchResponse(_)
4115            | ReplicationMessageBody::SubtreeByteResponse(_)
4116            | ReplicationMessageBody::NeighborSyncResponse(_)
4117    ) {
4118        protocol::record_served(peer, encoded.len());
4119    }
4120    let result = if let Some(msg_id) = rr_message_id {
4121        p2p_node
4122            .send_response(peer, REPLICATION_PROTOCOL_ID, msg_id, encoded)
4123            .await
4124    } else {
4125        p2p_node
4126            .send_message(peer, REPLICATION_PROTOCOL_ID, encoded, &[])
4127            .await
4128    };
4129    if let Err(e) = result {
4130        debug!("Failed to send replication response to {peer}: {e}");
4131        return false;
4132    }
4133    true
4134}
4135
4136async fn record_sent_replica_hints(
4137    peer: &PeerId,
4138    hints: &[neighbor_sync::SentReplicaHint],
4139    repair_proofs: &Arc<RwLock<RepairProofs>>,
4140    sync_cycle_epoch: &Arc<RwLock<u64>>,
4141) {
4142    if hints.is_empty() {
4143        return;
4144    }
4145
4146    let hinted_at_epoch = *sync_cycle_epoch.read().await;
4147    let mut proofs = repair_proofs.write().await;
4148    for hint in hints {
4149        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
4150            debug!(
4151                "Recorded repair hint proof for peer {peer} and key {}",
4152                hex::encode(hint.key)
4153            );
4154        }
4155    }
4156}
4157
4158// ---------------------------------------------------------------------------
4159// Neighbor sync round
4160// ---------------------------------------------------------------------------
4161
4162/// Run one neighbor sync round.
4163#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
4164async fn run_neighbor_sync_round(
4165    p2p_node: &Arc<P2PNode>,
4166    storage: &Arc<LmdbStorage>,
4167    paid_list: &Arc<PaidList>,
4168    queues: &Arc<RwLock<ReplicationQueues>>,
4169    config: &ReplicationConfig,
4170    sync_state: &Arc<RwLock<NeighborSyncState>>,
4171    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4172    sync_cycle_epoch: &Arc<RwLock<u64>>,
4173    repair_proofs: &Arc<RwLock<RepairProofs>>,
4174    is_bootstrapping: &Arc<RwLock<bool>>,
4175    bootstrap_state: &Arc<RwLock<BootstrapState>>,
4176    commitment_state: &Arc<ResponderCommitmentState>,
4177    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4178    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
4179    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
4180    gossip_audit: &GossipAuditTrigger,
4181) {
4182    let self_id = *p2p_node.peer_id();
4183    let bootstrapping = *is_bootstrapping.read().await;
4184
4185    // Check if cycle is complete; start new one if needed.
4186    // We check under a read lock, then release it before the expensive
4187    // prune pass and DHT snapshot so other tasks are not starved.
4188    let cycle_complete = sync_state.read().await.is_cycle_complete();
4189    if cycle_complete {
4190        // A completed local neighbor-sync cycle advances the epoch component
4191        // of repair-proof maturity. The per-key wall-clock minimum age is
4192        // checked when audits are selected.
4193        {
4194            let mut history = sync_history.write().await;
4195            for record in history.values_mut() {
4196                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
4197            }
4198        }
4199        {
4200            let mut epoch = sync_cycle_epoch.write().await;
4201            *epoch = epoch.saturating_add(1);
4202        }
4203
4204        // Post-cycle pruning (Section 11) — runs without holding sync_state.
4205        // Prune candidacy is unconditional once the hysteresis elapses;
4206        // bootstrap state only defers the remote prune-confirmation audits
4207        // until bootstrap has drained.
4208        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
4209        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
4210            self_id: &self_id,
4211            storage,
4212            paid_list,
4213            p2p_node,
4214            config,
4215            sync_state,
4216            repair_proofs,
4217            allow_remote_prune_audits,
4218            commitment_state: Some(commitment_state),
4219        })
4220        .await;
4221
4222        // Take fresh close-neighbor snapshot (DHT query, no lock held).
4223        let neighbors =
4224            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
4225                .await;
4226
4227        // Now re-acquire write lock and re-check before swapping cycle.
4228        let mut state = sync_state.write().await;
4229        if state.is_cycle_complete() {
4230            // Preserve cooldown and bootstrap-claim tracking across cycles.
4231            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
4232            // would reset the abuse detection timer every cycle.
4233            let old_sync_times = std::mem::take(&mut state.last_sync_times);
4234            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
4235            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
4236            let old_prune_cursor = state.prune_cursor;
4237            *state = NeighborSyncState::new_cycle(neighbors);
4238            state.last_sync_times = old_sync_times;
4239            state.bootstrap_claims = old_bootstrap_claims;
4240            state.bootstrap_claim_history = old_bootstrap_claim_history;
4241            state.prune_cursor = old_prune_cursor;
4242        }
4243    }
4244
4245    // Select batch of peers.
4246    let batch = {
4247        let mut state = sync_state.write().await;
4248        neighbor_sync::select_sync_batch(
4249            &mut state,
4250            config.neighbor_sync_peer_count,
4251            config.neighbor_sync_cooldown,
4252        )
4253    };
4254
4255    if batch.is_empty() {
4256        return;
4257    }
4258
4259    debug!("Neighbor sync: syncing with {} peers", batch.len());
4260
4261    // Snapshot our current commitment once per round so all peers in
4262    // this batch see the same thing (gossip is the responder's attestation;
4263    // same value across the batch is fine and reduces RwLock churn). Atomically
4264    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
4265    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
4266    let my_commitment = commitment_state
4267        .current_for_gossip()
4268        .map(|b| b.commitment().clone());
4269
4270    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
4271        &batch,
4272        storage,
4273        paid_list,
4274        p2p_node,
4275        config.close_group_size,
4276        config.paid_list_close_group_size,
4277    )
4278    .await;
4279
4280    // Sync with each peer in the batch.
4281    for peer in &batch {
4282        let hints = hints_by_peer.remove(peer).unwrap_or_default();
4283        let outcome = neighbor_sync::sync_with_peer_with_hints(
4284            peer,
4285            p2p_node,
4286            config,
4287            bootstrapping,
4288            hints,
4289            my_commitment.clone(),
4290        )
4291        .await;
4292
4293        if let Some(outcome) = outcome {
4294            handle_sync_response(
4295                &self_id,
4296                peer,
4297                &outcome.response,
4298                &outcome.sent_replica_hints,
4299                p2p_node,
4300                config,
4301                bootstrapping,
4302                bootstrap_state,
4303                storage,
4304                paid_list,
4305                queues,
4306                sync_state,
4307                sync_history,
4308                sync_cycle_epoch,
4309                repair_proofs,
4310                last_commitment_by_peer,
4311                ever_capable_peers,
4312                sig_verify_attempts,
4313                gossip_audit,
4314            )
4315            .await;
4316        } else {
4317            // Sync failed -- remove peer and try to fill slot.
4318            let replacement = {
4319                let mut state = sync_state.write().await;
4320                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
4321            };
4322
4323            // Attempt sync with the replacement peer (if one was found).
4324            if let Some(replacement_peer) = replacement {
4325                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
4326                    std::slice::from_ref(&replacement_peer),
4327                    storage,
4328                    paid_list,
4329                    p2p_node,
4330                    config.close_group_size,
4331                    config.paid_list_close_group_size,
4332                )
4333                .await;
4334                let hints = replacement_hints
4335                    .remove(&replacement_peer)
4336                    .unwrap_or_default();
4337                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
4338                    &replacement_peer,
4339                    p2p_node,
4340                    config,
4341                    bootstrapping,
4342                    hints,
4343                    my_commitment.clone(),
4344                )
4345                .await;
4346
4347                if let Some(outcome) = replacement_outcome {
4348                    handle_sync_response(
4349                        &self_id,
4350                        &replacement_peer,
4351                        &outcome.response,
4352                        &outcome.sent_replica_hints,
4353                        p2p_node,
4354                        config,
4355                        bootstrapping,
4356                        bootstrap_state,
4357                        storage,
4358                        paid_list,
4359                        queues,
4360                        sync_state,
4361                        sync_history,
4362                        sync_cycle_epoch,
4363                        repair_proofs,
4364                        last_commitment_by_peer,
4365                        ever_capable_peers,
4366                        sig_verify_attempts,
4367                        gossip_audit,
4368                    )
4369                    .await;
4370                }
4371            }
4372        }
4373    }
4374}
4375
4376/// Process a successful neighbor sync response: record the sync, check for
4377/// bootstrap claim abuse, and admit inbound hints.
4378#[allow(clippy::too_many_arguments)]
4379async fn handle_sync_response(
4380    self_id: &PeerId,
4381    peer: &PeerId,
4382    resp: &NeighborSyncResponse,
4383    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
4384    p2p_node: &Arc<P2PNode>,
4385    config: &ReplicationConfig,
4386    bootstrapping: bool,
4387    bootstrap_state: &Arc<RwLock<BootstrapState>>,
4388    storage: &Arc<LmdbStorage>,
4389    paid_list: &Arc<PaidList>,
4390    queues: &Arc<RwLock<ReplicationQueues>>,
4391    sync_state: &Arc<RwLock<NeighborSyncState>>,
4392    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4393    sync_cycle_epoch: &Arc<RwLock<u64>>,
4394    repair_proofs: &Arc<RwLock<RepairProofs>>,
4395    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4396    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
4397    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
4398    gossip_audit: &GossipAuditTrigger,
4399) {
4400    // Ingest the peer's commitment if they piggybacked one on the response.
4401    // Same verification as the request path (peer-id binding + signature);
4402    // forged commitments are dropped at the edge. A *changed* commitment here
4403    // is a gossip-audit trigger just like on the request path — so a peer that
4404    // only ever answers sync (never initiates) is still audited (ADR-0002).
4405    if let Some(target) = ingest_peer_commitment(
4406        peer,
4407        resp.commitment.as_ref(),
4408        p2p_node,
4409        last_commitment_by_peer,
4410        ever_capable_peers,
4411        sig_verify_attempts,
4412    )
4413    .await
4414    {
4415        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
4416    }
4417
4418    // Record successful sync.
4419    {
4420        let mut state = sync_state.write().await;
4421        neighbor_sync::record_successful_sync(&mut state, peer);
4422    }
4423    {
4424        let mut history = sync_history.write().await;
4425        let record = history.entry(*peer).or_insert(PeerSyncRecord {
4426            last_sync: None,
4427            cycles_since_sync: 0,
4428        });
4429        record.last_sync = Some(Instant::now());
4430        record.cycles_since_sync = 0;
4431    }
4432
4433    // Process inbound hints from response (skip if peer is bootstrapping).
4434    if resp.bootstrapping {
4435        // Gap 6: BootstrapClaimAbuse grace period enforcement.
4436        // Separate state mutation from network I/O to avoid holding the
4437        // write lock across report_trust_event.
4438        let should_report = {
4439            let now = Instant::now();
4440            let mut state = sync_state.write().await;
4441            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
4442                BootstrapClaimObservation::WithinGrace { .. } => false,
4443                BootstrapClaimObservation::PastGrace { first_seen } => {
4444                    warn!(
4445                        "Peer {peer} has been claiming bootstrap for {:?}, \
4446                         exceeding grace period of {:?} — reporting abuse",
4447                        now.duration_since(first_seen),
4448                        config.bootstrap_claim_grace_period,
4449                    );
4450                    true
4451                }
4452                BootstrapClaimObservation::Repeated { first_seen } => {
4453                    warn!(
4454                        "Peer {peer} repeated bootstrap claim after previously stopping; \
4455                         first claim was {:?} ago — reporting abuse",
4456                        now.duration_since(first_seen),
4457                    );
4458                    true
4459                }
4460            }
4461        };
4462        if should_report {
4463            p2p_node
4464                .report_trust_event(
4465                    peer,
4466                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
4467                )
4468                .await;
4469        }
4470    } else {
4471        // Peer is not claiming bootstrap; clear active claim while retaining
4472        // history so the peer cannot start a second grace window later.
4473        {
4474            let mut state = sync_state.write().await;
4475            state.clear_active_bootstrap_claim(peer);
4476        }
4477        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
4478        let outcome = admit_and_queue_hints(
4479            self_id,
4480            peer,
4481            &resp.replica_hints,
4482            &resp.paid_hints,
4483            p2p_node,
4484            config,
4485            storage,
4486            paid_list,
4487            queues,
4488        )
4489        .await;
4490
4491        // Track discovered keys for bootstrap drain detection so that hints
4492        // admitted via regular neighbor sync are not missed. Capacity-
4493        // rejected hints keep this source on the "not yet drained" list
4494        // until its next sync replays them; a clean cycle clears it.
4495        if bootstrapping {
4496            if !outcome.discovered.is_empty() {
4497                bootstrap::track_discovered_keys(bootstrap_state, &outcome.discovered).await;
4498            }
4499            if outcome.capacity_rejected_count > 0 {
4500                bootstrap::note_capacity_rejected(bootstrap_state, *peer).await;
4501            } else {
4502                bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
4503            }
4504        }
4505    }
4506}
4507
4508/// Admit hints and queue them for verification, returning newly-discovered keys.
4509///
4510/// Shared by neighbor-sync request handling, response handling, and bootstrap
4511/// sync so that admission + queueing logic lives in one place.
4512#[allow(clippy::too_many_arguments)]
4513/// Outcome of [`admit_and_queue_hints`].
4514///
4515/// `capacity_rejected_count` is non-zero when one or more legitimately
4516/// admissible hints were dropped because `pending_verify`'s global or
4517/// per-source bound was hit. Callers that care about completeness
4518/// (bootstrap drain accounting) MUST NOT treat their work as complete while
4519/// this is > 0 — the source will need to re-hint after capacity frees up.
4520struct AdmissionOutcome {
4521    discovered: HashSet<XorName>,
4522    capacity_rejected_count: usize,
4523}
4524
4525#[allow(clippy::too_many_arguments)]
4526async fn admit_and_queue_hints(
4527    self_id: &PeerId,
4528    source_peer: &PeerId,
4529    replica_hints: &[XorName],
4530    paid_hints: &[XorName],
4531    p2p_node: &Arc<P2PNode>,
4532    config: &ReplicationConfig,
4533    storage: &Arc<LmdbStorage>,
4534    paid_list: &Arc<PaidList>,
4535    queues: &Arc<RwLock<ReplicationQueues>>,
4536) -> AdmissionOutcome {
4537    let pending_keys: HashSet<XorName> = {
4538        let q = queues.read().await;
4539        q.pending_keys().into_iter().collect()
4540    };
4541
4542    let admitted = admission::admit_hints(
4543        self_id,
4544        replica_hints,
4545        paid_hints,
4546        p2p_node,
4547        config,
4548        storage,
4549        paid_list,
4550        &pending_keys,
4551    )
4552    .await;
4553
4554    let mut discovered = HashSet::new();
4555    let mut capacity_rejected_count: usize = 0;
4556    let mut q = queues.write().await;
4557    let now = Instant::now();
4558
4559    for key in admitted.replica_keys {
4560        if !storage.exists(&key).unwrap_or(false) {
4561            let result = q.add_pending_verify(
4562                key,
4563                VerificationEntry {
4564                    state: VerificationState::PendingVerify,
4565                    pipeline: HintPipeline::Replica,
4566                    verified_sources: Vec::new(),
4567                    tried_sources: HashSet::new(),
4568                    created_at: now,
4569                    hint_sender: *source_peer,
4570                },
4571            );
4572            match result {
4573                crate::replication::scheduling::AdmissionResult::Admitted => {
4574                    discovered.insert(key);
4575                }
4576                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
4577                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
4578                    capacity_rejected_count += 1;
4579                }
4580            }
4581        }
4582    }
4583
4584    for key in admitted.paid_only_keys {
4585        let result = q.add_pending_verify(
4586            key,
4587            VerificationEntry {
4588                state: VerificationState::PendingVerify,
4589                pipeline: HintPipeline::PaidOnly,
4590                verified_sources: Vec::new(),
4591                tried_sources: HashSet::new(),
4592                created_at: now,
4593                hint_sender: *source_peer,
4594            },
4595        );
4596        match result {
4597            crate::replication::scheduling::AdmissionResult::Admitted => {
4598                discovered.insert(key);
4599            }
4600            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
4601            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
4602                capacity_rejected_count += 1;
4603            }
4604        }
4605    }
4606
4607    if capacity_rejected_count > 0 {
4608        debug!(
4609            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
4610             rejected at queue capacity; source will need to re-hint after pending_verify drains"
4611        );
4612    }
4613
4614    AdmissionOutcome {
4615        discovered,
4616        capacity_rejected_count,
4617    }
4618}
4619
4620// ---------------------------------------------------------------------------
4621// Verification cycle
4622// ---------------------------------------------------------------------------
4623
4624/// Run one verification cycle: process pending keys through quorum checks.
4625#[allow(clippy::too_many_lines)]
4626async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
4627    let cycle_started = Instant::now();
4628    let VerificationCycleContext {
4629        p2p_node,
4630        paid_list,
4631        storage,
4632        queues,
4633        config,
4634        bootstrap_state,
4635        is_bootstrapping,
4636        bootstrap_complete_notify,
4637        last_commitment_by_peer,
4638        ever_capable_peers,
4639        recent_provers,
4640    } = ctx;
4641
4642    // Evict stale entries that have been pending too long (e.g. unreachable
4643    // verification targets during a network partition).
4644    {
4645        let mut q = queues.write().await;
4646        q.evict_stale(config::PENDING_VERIFY_MAX_AGE);
4647    }
4648
4649    let pending_keys = {
4650        let q = queues.read().await;
4651        q.pending_keys()
4652    };
4653
4654    if pending_keys.is_empty() {
4655        return;
4656    }
4657    let initial_pending_count = pending_keys.len();
4658
4659    let self_id = *p2p_node.peer_id();
4660
4661    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
4662    // step 4).
4663    let mut local_paid_presence_probe_keys = Vec::new();
4664    let mut local_paid_paid_only_keys = Vec::new();
4665    let mut keys_needing_network = Vec::new();
4666    let mut terminal_keys: Vec<XorName> = Vec::new();
4667    {
4668        let mut q = queues.write().await;
4669        for key in &pending_keys {
4670            if paid_list.contains(key).unwrap_or(false) {
4671                if let Some(pipeline) =
4672                    q.set_pending_state(key, VerificationState::PaidListVerified)
4673                {
4674                    match pipeline {
4675                        HintPipeline::PaidOnly => {
4676                            // Paid-only + local paid state needs one more
4677                            // storage-admission check outside this lock: if we
4678                            // are also in the close group plus storage margin,
4679                            // the hint can repair a missing replica.
4680                            local_paid_paid_only_keys.push(*key);
4681                        }
4682                        HintPipeline::Replica => {
4683                            // Local paid-list membership authorizes the key.
4684                            // We still need a presence probe to discover fetch
4685                            // sources, but we must not require remote paid
4686                            // majority or presence quorum.
4687                            local_paid_presence_probe_keys.push(*key);
4688                        }
4689                    }
4690                }
4691            } else {
4692                keys_needing_network.push(*key);
4693            }
4694        }
4695    }
4696
4697    if !local_paid_paid_only_keys.is_empty() {
4698        let mut terminal_paid_only = Vec::new();
4699        for key in local_paid_paid_only_keys {
4700            if storage.exists(&key).unwrap_or(false) {
4701                terminal_paid_only.push(key);
4702            } else if admission::is_responsible(
4703                &self_id,
4704                &key,
4705                p2p_node,
4706                storage_admission_width(config.close_group_size),
4707            )
4708            .await
4709            {
4710                local_paid_presence_probe_keys.push(key);
4711            } else {
4712                terminal_paid_only.push(key);
4713            }
4714        }
4715
4716        if !terminal_paid_only.is_empty() {
4717            let mut q = queues.write().await;
4718            for key in terminal_paid_only {
4719                q.remove_pending(&key);
4720                terminal_keys.push(key);
4721            }
4722        }
4723    }
4724
4725    let local_paid_probe_count = local_paid_presence_probe_keys.len();
4726    let keys_needing_network_count = keys_needing_network.len();
4727
4728    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
4729    // step 4, authorization succeeds immediately; run a presence-only probe
4730    // to find any holder we can fetch from.
4731    if !local_paid_presence_probe_keys.is_empty() {
4732        let targets = quorum::compute_presence_targets(
4733            &local_paid_presence_probe_keys,
4734            p2p_node,
4735            config,
4736            &self_id,
4737        )
4738        .await;
4739        let evidence = quorum::run_verification_round(
4740            &local_paid_presence_probe_keys,
4741            &targets,
4742            p2p_node,
4743            config,
4744        )
4745        .await;
4746
4747        let mut q = queues.write().await;
4748        for key in local_paid_presence_probe_keys {
4749            if storage.exists(&key).unwrap_or(false) {
4750                q.remove_pending(&key);
4751                terminal_keys.push(key);
4752                continue;
4753            }
4754            let sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
4755                quorum::present_sources_for_key(&key, ev, &targets)
4756            });
4757            if sources.is_empty() {
4758                // Terminal failure: remove pending and report. No fetch path.
4759                q.remove_pending(&key);
4760                warn!(
4761                    "Locally paid key {} has no responding holders (possible data loss)",
4762                    hex::encode(key)
4763                );
4764                terminal_keys.push(key);
4765            } else {
4766                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
4767                // Atomic remove+enqueue: if fetch_queue is at capacity, the
4768                // pending entry is preserved and retried next cycle (no
4769                // silent drop of verified replica-repair work).
4770                let _ = q.promote_pending_to_fetch(key, distance, sources);
4771            }
4772        }
4773    }
4774
4775    // Steps 2-5: Network verification (skipped if all keys resolved locally).
4776    if !keys_needing_network.is_empty() {
4777        // Step 2: Compute targets and run network verification round.
4778        let targets =
4779            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
4780                .await;
4781
4782        let evidence =
4783            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
4784
4785        // Step 3: Evaluate results — collect outcomes without holding the write
4786        // lock across paid-list I/O.
4787        //
4788        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
4789        // table and recent_provers cache up front so the synchronous
4790        // evaluate_key_evidence_with_holder_check predicate can consult
4791        // them without awaiting. The predicate downgrades a Present
4792        // claim to Unresolved unless the peer is credited for that key.
4793        // Snapshot per-peer commitment data. We need two views:
4794        //   - `commitment_by_peer_snapshot`: peers that currently have
4795        //     a verified commitment record on file (used to look up
4796        //     their current hash).
4797        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
4798        //     set. Sourced from a separate set rather than the
4799        //     commitment map so eviction (PeerRemoved cleanup, sybil
4800        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
4801        //     a previously-v12 peer to "legacy" credit-unconditionally.
4802        //     Legacy / pre-v12 peers that have never sent a commitment
4803        //     remain absent from the set and are credited via the
4804        //     legacy path so mixed-version networks stay live.
4805        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
4806            let map = last_commitment_by_peer.read().await;
4807            map.iter()
4808                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
4809                // of every peer's ~5 KiB commitment.
4810                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
4811                .collect()
4812        };
4813        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
4814        // Take a full snapshot of recent_provers under the read lock,
4815        // then release. The cache is bounded (16/key × keys), so the
4816        // clone is cheap.
4817        let provers_snapshot = recent_provers.read().await.clone();
4818        // For the replica-fetch path, we need to know whether THIS
4819        // node already holds the key being verified. The v12 §6
4820        // holder-credit gate is meant to prevent uncredited Present
4821        // claims from contributing to paid-list / reward quorum for
4822        // keys we DO hold (and could audit ourselves). For keys we
4823        // are trying to FETCH (i.e. not in local storage), there is
4824        // no possible local audit credit, and gating the presence
4825        // quorum on credit would deadlock replica-repair in a
4826        // fully v12-capable close group.
4827        let mut locally_held: HashSet<XorName> = HashSet::new();
4828        for key in &keys_needing_network {
4829            if storage.exists(key).unwrap_or(false) {
4830                locally_held.insert(*key);
4831            }
4832        }
4833        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
4834            if !locally_held.contains(key) {
4835                // Replica-fetch path: we don't hold this key, so we
4836                // cannot have collected audit credit for it. Trust
4837                // Present claims to drive fetch-source promotion;
4838                // chunk-PUT payment_verifier is the security backstop
4839                // when the bytes actually arrive.
4840                return true;
4841            }
4842            if !capable_peer_snapshot.contains(peer) {
4843                // Pre-v12 / legacy peer that has never gossiped a
4844                // commitment. The v12 §6 holder-eligibility check
4845                // doesn't apply: their Present evidence comes through
4846                // the legacy path and we credit it unconditionally
4847                // so a mixed-version network stays live during
4848                // transition.
4849                return true;
4850            }
4851            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
4852                // Peer is commitment_capable (sticky) but currently
4853                // has no live commitment record on file (e.g. their
4854                // last gossip was evicted from the LRU cache, or it
4855                // failed verification). Withhold credit until they
4856                // re-prove storage under a fresh commitment.
4857                return false;
4858            };
4859            provers_snapshot.is_credited_holder(key, peer, hash)
4860        };
4861
4862        let mut evaluated: Vec<(XorName, KeyVerificationOutcome, HintPipeline)> = Vec::new();
4863        {
4864            let q = queues.read().await;
4865            for key in &keys_needing_network {
4866                let Some(ev) = evidence.get(key) else {
4867                    continue;
4868                };
4869                let Some(entry) = q.get_pending(key) else {
4870                    continue;
4871                };
4872                let outcome = quorum::evaluate_key_evidence_with_holder_check(
4873                    key,
4874                    ev,
4875                    &targets,
4876                    config,
4877                    holder_credit,
4878                );
4879                evaluated.push((*key, outcome, entry.pipeline));
4880            }
4881        } // read lock released
4882
4883        // Step 4: Insert verified keys into PaidForList (no lock held).
4884        let mut paid_insert_keys: Vec<XorName> = Vec::new();
4885        for (key, outcome, _) in &evaluated {
4886            if matches!(
4887                outcome,
4888                KeyVerificationOutcome::QuorumVerified { .. }
4889                    | KeyVerificationOutcome::PaidListVerified { .. }
4890            ) {
4891                paid_insert_keys.push(*key);
4892            }
4893        }
4894        for key in &paid_insert_keys {
4895            if let Err(e) = paid_list.insert(key).await {
4896                warn!("Failed to add verified key to PaidForList: {e}");
4897            }
4898        }
4899
4900        // Paid-only hints normally update PaidForList only. If this node is
4901        // also within the storage-admission group for the key, a verified
4902        // paid-only hint can safely repair a missing replica using sources
4903        // from the same verification round.
4904        let mut paid_only_fetch_keys: HashSet<XorName> = HashSet::new();
4905        for (key, outcome, pipeline) in &evaluated {
4906            if *pipeline == HintPipeline::PaidOnly
4907                && matches!(
4908                    outcome,
4909                    KeyVerificationOutcome::QuorumVerified { .. }
4910                        | KeyVerificationOutcome::PaidListVerified { .. }
4911                )
4912                && !storage.exists(key).unwrap_or(false)
4913                && admission::is_responsible(
4914                    &self_id,
4915                    key,
4916                    p2p_node,
4917                    storage_admission_width(config.close_group_size),
4918                )
4919                .await
4920            {
4921                paid_only_fetch_keys.insert(*key);
4922            }
4923        }
4924
4925        // Step 5: Update queues with the evaluated outcomes.
4926        let mut q = queues.write().await;
4927        for (key, outcome, pipeline) in evaluated {
4928            match outcome {
4929                KeyVerificationOutcome::QuorumVerified { sources }
4930                | KeyVerificationOutcome::PaidListVerified { sources } => {
4931                    let fetch_eligible =
4932                        pipeline == HintPipeline::Replica || paid_only_fetch_keys.contains(&key);
4933                    if fetch_eligible && !sources.is_empty() {
4934                        let distance =
4935                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
4936                        // Atomic remove+enqueue: on fetch_queue capacity miss
4937                        // the pending entry is preserved so this verified key
4938                        // is retried on the next cycle (no silent drop).
4939                        let _ = q.promote_pending_to_fetch(key, distance, sources);
4940                        // Not terminal — either moved to fetch queue, or
4941                        // retained as pending until queue drains.
4942                    } else if fetch_eligible && sources.is_empty() {
4943                        warn!(
4944                            "Verified storage-admitted key {} has no holders (possible data loss)",
4945                            hex::encode(key)
4946                        );
4947                        q.remove_pending(&key);
4948                        terminal_keys.push(key);
4949                    } else {
4950                        q.remove_pending(&key);
4951                        terminal_keys.push(key);
4952                    }
4953                }
4954                KeyVerificationOutcome::QuorumFailed
4955                | KeyVerificationOutcome::QuorumInconclusive => {
4956                    q.remove_pending(&key);
4957                    terminal_keys.push(key);
4958                }
4959            }
4960        }
4961    }
4962
4963    // Step 6: Remove terminal keys from bootstrap pending set and re-check
4964    // the drain condition.
4965    update_bootstrap_after_verification(
4966        &terminal_keys,
4967        bootstrap_state,
4968        queues,
4969        is_bootstrapping,
4970        bootstrap_complete_notify,
4971    )
4972    .await;
4973
4974    let (pending_after, fetch_after, in_flight_after) = {
4975        let q = queues.read().await;
4976        (
4977            q.pending_count(),
4978            q.fetch_queue_count(),
4979            q.in_flight_count(),
4980        )
4981    };
4982    let terminal_key_count = terminal_keys.len();
4983    let elapsed_ms = cycle_started.elapsed().as_millis();
4984
4985    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
4986        info!(
4987            target: "ant_node::replication::verification",
4988            "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}",
4989        );
4990    } else {
4991        debug!(
4992            target: "ant_node::replication::verification",
4993            "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}",
4994        );
4995    }
4996}
4997
4998/// Post-verification bootstrap bookkeeping: remove terminal keys from the
4999/// bootstrap pending set and transition out of bootstrapping when drained.
5000async fn update_bootstrap_after_verification(
5001    terminal_keys: &[XorName],
5002    bootstrap_state: &Arc<RwLock<BootstrapState>>,
5003    queues: &Arc<RwLock<ReplicationQueues>>,
5004    is_bootstrapping: &Arc<RwLock<bool>>,
5005    bootstrap_complete_notify: &Arc<Notify>,
5006) {
5007    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
5008        return;
5009    }
5010    {
5011        let mut bs = bootstrap_state.write().await;
5012        for key in terminal_keys {
5013            bs.remove_key(key);
5014        }
5015    }
5016    let q = queues.read().await;
5017    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
5018        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
5019    }
5020}
5021
5022/// Set `is_bootstrapping` to `false` and wake all waiters.
5023async fn complete_bootstrap(
5024    is_bootstrapping: &Arc<RwLock<bool>>,
5025    bootstrap_complete_notify: &Arc<Notify>,
5026) {
5027    *is_bootstrapping.write().await = false;
5028    bootstrap_complete_notify.notify_waiters();
5029    info!("Replication bootstrap complete");
5030}
5031
5032// ---------------------------------------------------------------------------
5033// Fetch types and single-fetch executor
5034// ---------------------------------------------------------------------------
5035
5036/// Result classification for a single fetch attempt.
5037enum FetchResult {
5038    /// Data fetched, integrity-checked, and stored successfully.
5039    Stored,
5040    /// Content-address integrity check failed — do not retry.
5041    IntegrityFailed,
5042    /// Source failed (network error or non-success response) — retryable.
5043    SourceFailed,
5044}
5045
5046/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
5047/// worker loop to update queue state.
5048struct FetchOutcome {
5049    key: XorName,
5050    result: FetchResult,
5051}
5052
5053#[allow(clippy::too_many_lines)]
5054/// Execute a single fetch request against `source` for `key`.
5055///
5056/// Handles encoding, network I/O, integrity checking, storage, and trust
5057/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
5058/// queue state without holding any locks during the network round-trip.
5059async fn execute_single_fetch(
5060    p2p_node: Arc<P2PNode>,
5061    storage: Arc<LmdbStorage>,
5062    config: Arc<ReplicationConfig>,
5063    key: XorName,
5064    source: PeerId,
5065) -> FetchOutcome {
5066    let request = protocol::FetchRequest { key };
5067    let msg = ReplicationMessage {
5068        request_id: rand::thread_rng().gen::<u64>(),
5069        body: ReplicationMessageBody::FetchRequest(request),
5070    };
5071
5072    let encoded = match msg.encode() {
5073        Ok(data) => data,
5074        Err(e) => {
5075            warn!("Failed to encode fetch request: {e}");
5076            return FetchOutcome {
5077                key,
5078                result: FetchResult::SourceFailed,
5079            };
5080        }
5081    };
5082
5083    let result = p2p_node
5084        .send_request(
5085            &source,
5086            REPLICATION_PROTOCOL_ID,
5087            encoded,
5088            config.fetch_request_timeout,
5089        )
5090        .await;
5091
5092    match result {
5093        Ok(response) => {
5094            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
5095                p2p_node
5096                    .report_trust_event(
5097                        &source,
5098                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5099                    )
5100                    .await;
5101                return FetchOutcome {
5102                    key,
5103                    result: FetchResult::SourceFailed,
5104                };
5105            };
5106
5107            match resp_msg.body {
5108                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
5109                    key: resp_key,
5110                    data,
5111                }) => {
5112                    // Validate the response key matches the requested key.
5113                    // A malicious peer could serve valid data for a different
5114                    // key, passing integrity checks while the requested key
5115                    // is falsely marked as fetched.
5116                    if resp_key != key {
5117                        warn!(
5118                            "Fetch response key mismatch: requested {}, got {}",
5119                            hex::encode(key),
5120                            hex::encode(resp_key)
5121                        );
5122                        p2p_node
5123                            .report_trust_event(
5124                                &source,
5125                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5126                            )
5127                            .await;
5128                        return FetchOutcome {
5129                            key,
5130                            result: FetchResult::IntegrityFailed,
5131                        };
5132                    }
5133
5134                    // Enforce chunk size invariant on fetched data.
5135                    // Checked before the content-address hash to avoid
5136                    // hashing up to 10 MiB of oversized junk data.
5137                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5138                        warn!(
5139                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
5140                            hex::encode(resp_key),
5141                            data.len(),
5142                            crate::ant_protocol::MAX_CHUNK_SIZE,
5143                        );
5144                        p2p_node
5145                            .report_trust_event(
5146                                &source,
5147                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5148                            )
5149                            .await;
5150                        return FetchOutcome {
5151                            key,
5152                            result: FetchResult::IntegrityFailed,
5153                        };
5154                    }
5155
5156                    // Content-address integrity check.
5157                    let computed = crate::client::compute_address(&data);
5158                    if computed != resp_key {
5159                        warn!(
5160                            "Fetched record integrity check failed: expected {}, got {}",
5161                            hex::encode(resp_key),
5162                            hex::encode(computed)
5163                        );
5164                        p2p_node
5165                            .report_trust_event(
5166                                &source,
5167                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5168                            )
5169                            .await;
5170                        return FetchOutcome {
5171                            key,
5172                            result: FetchResult::IntegrityFailed,
5173                        };
5174                    }
5175
5176                    if let Err(e) = storage.put(&resp_key, &data).await {
5177                        warn!(
5178                            "Failed to store fetched record {}: {e}",
5179                            hex::encode(resp_key)
5180                        );
5181                        return FetchOutcome {
5182                            key,
5183                            result: FetchResult::SourceFailed,
5184                        };
5185                    }
5186
5187                    FetchOutcome {
5188                        key,
5189                        result: FetchResult::Stored,
5190                    }
5191                }
5192                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
5193                    ..
5194                }) => {
5195                    // This peer was selected as a fetch source because it
5196                    // recently answered `Present` during verification. A
5197                    // subsequent NotFound is evidence of a stale/false claim
5198                    // or chunk wiping, so penalize lightly and try another
5199                    // verified source.
5200                    warn!(
5201                        "Fetch: verified source {source} returned NotFound for {}",
5202                        hex::encode(key)
5203                    );
5204                    p2p_node
5205                        .report_trust_event(
5206                            &source,
5207                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5208                        )
5209                        .await;
5210                    FetchOutcome {
5211                        key,
5212                        result: FetchResult::SourceFailed,
5213                    }
5214                }
5215                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
5216                    reason,
5217                    ..
5218                }) => {
5219                    warn!(
5220                        "Fetch: peer {source} returned error for {}: {reason}",
5221                        hex::encode(key)
5222                    );
5223                    p2p_node
5224                        .report_trust_event(
5225                            &source,
5226                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5227                        )
5228                        .await;
5229                    FetchOutcome {
5230                        key,
5231                        result: FetchResult::SourceFailed,
5232                    }
5233                }
5234                _ => {
5235                    // Unexpected message type — treat as malformed.
5236                    p2p_node
5237                        .report_trust_event(
5238                            &source,
5239                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5240                        )
5241                        .await;
5242                    FetchOutcome {
5243                        key,
5244                        result: FetchResult::SourceFailed,
5245                    }
5246                }
5247            }
5248        }
5249        Err(e) => {
5250            debug!("Fetch request to {source} failed: {e}");
5251            // No ApplicationFailure here — P2PNode::send_request() already
5252            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
5253            FetchOutcome {
5254                key,
5255                result: FetchResult::SourceFailed,
5256            }
5257        }
5258    }
5259}
5260
5261// ---------------------------------------------------------------------------
5262// Audit result handler
5263// ---------------------------------------------------------------------------
5264
5265/// Format the first confirmed-failed key as a 16-hex-char label.
5266///
5267/// Pairs with `challenged_peer` to form a stable cross-host correlation
5268/// handle in the audit-failure log line, e.g.
5269///
5270/// ```text
5271/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
5272/// ```
5273///
5274/// Falls back to `"0x"` when the list is empty so the log line never
5275/// contains a misleading default.
5276fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
5277    confirmed_failed_keys.first().map_or_else(
5278        || "0x".to_string(),
5279        |k| format!("0x{}", hex::encode(&k[..8])),
5280    )
5281}
5282
5283/// Execute the side effects for a subtree storage-commitment audit failure.
5284///
5285/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
5286/// legitimately time out on slow or loaded honest peers, so it never touches the
5287/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
5288/// failures still penalise immediately and revoke holder credit.
5289async fn handle_subtree_failed_audit(
5290    challenged_peer: &PeerId,
5291    confirmed_failed_key_count: usize,
5292    reason: &AuditFailureReason,
5293    p2p_node: &Arc<P2PNode>,
5294    sync_state: &Arc<RwLock<NeighborSyncState>>,
5295    recent_provers: &Arc<RwLock<RecentProvers>>,
5296) {
5297    if matches!(reason, AuditFailureReason::Timeout) {
5298        debug!(
5299            "Audit timeout for {challenged_peer} fully graced \
5300             (subtree audit does not evict on timeout)"
5301        );
5302        return;
5303    }
5304
5305    // The caller already logged the rich failure line with reason + per-category
5306    // summary; avoid a redundant second error log here.
5307    let _ = confirmed_failed_key_count;
5308    {
5309        let mut state = sync_state.write().await;
5310        state.clear_active_bootstrap_claim(challenged_peer);
5311    }
5312    {
5313        let mut provers_guard = recent_provers.write().await;
5314        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
5315    }
5316    p2p_node
5317        .report_trust_event(
5318            challenged_peer,
5319            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
5320        )
5321        .await;
5322}
5323
5324/// Handle audit result: log findings and emit trust events.
5325async fn handle_subtree_audit_result(
5326    result: &AuditTickResult,
5327    p2p_node: &Arc<P2PNode>,
5328    sync_state: &Arc<RwLock<NeighborSyncState>>,
5329    recent_provers: &Arc<RwLock<RecentProvers>>,
5330    config: &ReplicationConfig,
5331) {
5332    match result {
5333        AuditTickResult::Passed {
5334            challenged_peer,
5335            keys_checked,
5336        } => {
5337            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
5338            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
5339            // Peer responded normally — clear the active bootstrap claim while
5340            // retaining history so a later claim is treated as repeated abuse.
5341            {
5342                let mut state = sync_state.write().await;
5343                state.clear_active_bootstrap_claim(challenged_peer);
5344            }
5345            p2p_node
5346                .report_trust_event(
5347                    challenged_peer,
5348                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
5349                )
5350                .await;
5351        }
5352        AuditTickResult::Failed { evidence } => {
5353            if let FailureEvidence::AuditFailure {
5354                challenged_peer,
5355                confirmed_failed_keys,
5356                summary,
5357                reason,
5358                ..
5359            } = evidence
5360            {
5361                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
5362                // Rich diagnostics (from main's audit-failure logging) + the
5363                // first-failed-key correlation handle.
5364                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
5365                error!(
5366                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
5367                    confirmed_failed_keys.len(),
5368                    summary.challenged_keys,
5369                    summary.absent_keys,
5370                    summary.digest_mismatch_keys,
5371                );
5372                // Route the side effects through the subtree-only failure path.
5373                // Responsible-chunk `AuditChallenge` handling intentionally uses
5374                // its own old immediate-penalty handler below.
5375                handle_subtree_failed_audit(
5376                    challenged_peer,
5377                    confirmed_failed_keys.len(),
5378                    reason,
5379                    p2p_node,
5380                    sync_state,
5381                    recent_provers,
5382                )
5383                .await;
5384            }
5385        }
5386        AuditTickResult::BootstrapClaim { peer } => {
5387            // Gap 6: BootstrapClaimAbuse grace period in audit path.
5388            // Separate state mutation from network I/O to avoid holding the
5389            // write lock across report_trust_event.
5390            let should_report = {
5391                let now = Instant::now();
5392                let mut state = sync_state.write().await;
5393                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
5394                {
5395                    BootstrapClaimObservation::WithinGrace { .. } => {
5396                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
5397                        false
5398                    }
5399                    BootstrapClaimObservation::PastGrace { first_seen } => {
5400                        warn!(
5401                            "Audit: peer {peer} claiming bootstrap past grace period \
5402                             ({:?} > {:?}), reporting abuse",
5403                            now.duration_since(first_seen),
5404                            config.bootstrap_claim_grace_period,
5405                        );
5406                        true
5407                    }
5408                    BootstrapClaimObservation::Repeated { first_seen } => {
5409                        warn!(
5410                            "Audit: peer {peer} repeated bootstrap claim after previously \
5411                             stopping; first claim was {:?} ago, reporting abuse",
5412                            now.duration_since(first_seen),
5413                        );
5414                        true
5415                    }
5416                }
5417            };
5418            if should_report {
5419                p2p_node
5420                    .report_trust_event(
5421                        peer,
5422                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5423                    )
5424                    .await;
5425            }
5426        }
5427        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
5428    }
5429}
5430
5431/// Whether a confirmed audit failure with this reason clears the peer's active
5432/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
5433/// bootstrapping); every confirmed storage-integrity reason does.
5434///
5435/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
5436/// the bootstrap claim but are still reported as audit failures, matching the
5437/// pre-ADR-0002 behaviour.
5438fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
5439    !matches!(reason, AuditFailureReason::Timeout)
5440}
5441
5442/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
5443/// events and manage bootstrap-claim state.
5444///
5445/// This is intentionally separate from the subtree audit result handler. A
5446/// responsible-chunk `AuditChallenge` `Failed` result reports
5447/// `ApplicationFailure` immediately for every reason, including `Timeout`,
5448/// restoring the pre-ADR-0002 behaviour.
5449async fn handle_audit_result(
5450    result: &AuditTickResult,
5451    p2p_node: &Arc<P2PNode>,
5452    sync_state: &Arc<RwLock<NeighborSyncState>>,
5453    config: &ReplicationConfig,
5454) {
5455    match result {
5456        AuditTickResult::Passed {
5457            challenged_peer,
5458            keys_checked,
5459        } => {
5460            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
5461            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
5462            {
5463                let mut state = sync_state.write().await;
5464                state.clear_active_bootstrap_claim(challenged_peer);
5465            }
5466            p2p_node
5467                .report_trust_event(
5468                    challenged_peer,
5469                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
5470                )
5471                .await;
5472        }
5473        AuditTickResult::Failed { evidence } => {
5474            if let FailureEvidence::AuditFailure {
5475                challenged_peer,
5476                confirmed_failed_keys,
5477                summary,
5478                reason,
5479                ..
5480            } = evidence
5481            {
5482                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
5483                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
5484                error!(
5485                    "Audit failure for {challenged_peer}: reason={reason:?}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
5486                    confirmed_failed_keys.len(),
5487                    summary.challenged_keys,
5488                    summary.absent_keys,
5489                    summary.digest_mismatch_keys,
5490                );
5491                if audit_failure_clears_bootstrap_claim(reason) {
5492                    let mut state = sync_state.write().await;
5493                    state.clear_active_bootstrap_claim(challenged_peer);
5494                } else {
5495                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
5496                }
5497                p2p_node
5498                    .report_trust_event(
5499                        challenged_peer,
5500                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
5501                    )
5502                    .await;
5503            }
5504        }
5505        AuditTickResult::BootstrapClaim { peer } => {
5506            let should_report = {
5507                let now = Instant::now();
5508                let mut state = sync_state.write().await;
5509                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
5510                {
5511                    BootstrapClaimObservation::WithinGrace { .. } => {
5512                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
5513                        false
5514                    }
5515                    BootstrapClaimObservation::PastGrace { first_seen } => {
5516                        warn!(
5517                            "Audit: peer {peer} claiming bootstrap past grace period \
5518                             ({:?} > {:?}), reporting abuse",
5519                            now.duration_since(first_seen),
5520                            config.bootstrap_claim_grace_period,
5521                        );
5522                        true
5523                    }
5524                    BootstrapClaimObservation::Repeated { first_seen } => {
5525                        warn!(
5526                            "Audit: peer {peer} repeated bootstrap claim after previously \
5527                             stopping; first claim was {:?} ago, reporting abuse",
5528                            now.duration_since(first_seen),
5529                        );
5530                        true
5531                    }
5532                }
5533            };
5534            if should_report {
5535                p2p_node
5536                    .report_trust_event(
5537                        peer,
5538                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5539                    )
5540                    .await;
5541            }
5542        }
5543        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
5544    }
5545}
5546
5547/// Whether a confirmed audit failure with this reason should revoke the
5548/// peer's `recent_provers` holder credit immediately (v12 §6).
5549///
5550/// `true` for any reason where the peer actually answered (or admitted
5551/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
5552/// bytes for committed key"), `MalformedResponse` — these prove the
5553/// peer no longer holds what it committed to, so it must not keep
5554/// holder credit for the proof TTL. `false` for `Timeout`: a single
5555/// dropped packet must not strip an honest peer; the 40-min TTL is the
5556/// deliberate liveness cushion there.
5557fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
5558    !matches!(reason, AuditFailureReason::Timeout)
5559}
5560
5561/// Apply the holder-credit revocation decision for a confirmed audit
5562/// failure. Pure over `RecentProvers` so the handler wiring is unit-
5563/// testable without a live `P2PNode`: the production `Failed` arm of
5564/// `handle_subtree_audit_result` calls exactly this.
5565fn apply_audit_failure_credit_revocation(
5566    provers: &mut RecentProvers,
5567    challenged_peer: &PeerId,
5568    reason: &AuditFailureReason,
5569) {
5570    if audit_failure_revokes_holder_credit(reason) {
5571        provers.forget_peer(challenged_peer);
5572    }
5573}
5574
5575// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
5576
5577// ---------------------------------------------------------------------------
5578// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
5579// ---------------------------------------------------------------------------
5580
5581/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
5582/// message handler passes one value instead of a long argument list; all
5583/// fields are cheap `Arc` clones.
5584#[derive(Clone)]
5585struct GossipAuditTrigger {
5586    p2p_node: Arc<P2PNode>,
5587    config: Arc<ReplicationConfig>,
5588    recent_provers: Arc<RwLock<RecentProvers>>,
5589    sync_state: Arc<RwLock<NeighborSyncState>>,
5590    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
5591    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
5592    /// only when a real audit is about to be sent — never by a losing lottery
5593    /// ticket — so gossip traffic alone can never suppress a paid first audit.
5594    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
5595    /// Gossip-private lottery attempt window: stamped on every roll (win or
5596    /// lose) so a gossip flood cannot re-roll the lottery within the window.
5597    /// The first-audit scheduler never reads this map.
5598    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
5599}
5600
5601/// What a gossip ingest yields for the audit trigger: the commitment hash to
5602/// pin and the `key_count` needed to size the response deadline from the actual
5603/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
5604/// or not) so a stable-keyset node stays auditable — not just on its first
5605/// commitment.
5606#[derive(Debug, Clone, Copy)]
5607struct AuditTarget {
5608    pin_hash: [u8; 32],
5609    key_count: u32,
5610}
5611
5612/// ADR-0004: a commitment that backed a payment, surfaced by the payment
5613/// verifier's cross-check so it can receive a **deterministic first audit**.
5614///
5615/// Sent from the verifier to the replication engine's first-audit drainer. The
5616/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
5617/// audits of the same peer revert to the gossip lottery), orders most-recently-
5618/// monetized first, and runs the same `run_subtree_audit` under the same
5619/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
5620#[derive(Debug, Clone, Copy)]
5621pub struct MonetizedPinEvent {
5622    /// The peer whose commitment backed the payment.
5623    pub peer: PeerId,
5624    /// The pinned commitment hash.
5625    pub pin: [u8; 32],
5626    /// The committed key count (sizes the audit deadline).
5627    pub key_count: u32,
5628    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
5629    /// pin whose quote is older than the answerability window (ADR-0004 A1
5630    /// guardrail A): with grace removed, challenging an aged-out pin would
5631    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
5632    pub quote_ts: SystemTime,
5633}
5634
5635/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
5636/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
5637/// stamps `now`), `false` if it was audited within
5638/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
5639/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
5640/// without a live node: a burst of gossips from one peer yields at most one
5641/// `true` per cooldown window.
5642fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
5643    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
5644    let known = match map.get(peer) {
5645        Some(&last) => {
5646            if now.saturating_duration_since(last) < cooldown {
5647                return false;
5648            }
5649            true
5650        }
5651        None => false,
5652    };
5653    // Bound the map under churn like its siblings (drop the oldest stamp) before
5654    // admitting a brand-new peer.
5655    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
5656        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
5657            map.remove(&victim);
5658        }
5659    }
5660    map.insert(*peer, now);
5661    true
5662}
5663
5664/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
5665/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
5666/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
5667/// already covered; the authoritative check-and-stamp still runs at promotion,
5668/// so this is only an optimization and never the security boundary.
5669fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
5670    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
5671    map.get(peer).map_or(true, |&last| {
5672        now.saturating_duration_since(last) >= cooldown
5673    })
5674}
5675
5676/// The gossip-audit launch decision in ONE place so the ordering is shared
5677/// between production and its test (ADR-0002 "occasional surprise exams").
5678///
5679/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
5680/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
5681/// sampled first, a gossip flood would re-roll it on every message until one
5682/// won, multiplying audits, so each peer gets at most one lottery roll per
5683/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
5684/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
5685/// also consults — only after a WIN, i.e. only when a real audit is about to be
5686/// sent. A losing ticket must never stamp `launched`: no challenge went on the
5687/// wire, so it must not defer a paid first audit (repeatable losses could
5688/// otherwise hold a monetized pin past its answerability window). Production
5689/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
5690/// test calls it with a deterministic `lottery_wins`, so a reorder regression
5691/// here fails the test.
5692fn audit_launch_decision(
5693    attempts: &mut HashMap<PeerId, Instant>,
5694    launched: &mut HashMap<PeerId, Instant>,
5695    peer: &PeerId,
5696    now: Instant,
5697    lottery_wins: bool,
5698) -> bool {
5699    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
5700    // window even on a loss; private to the gossip path).
5701    if !cooldown_allows_audit(attempts, peer, now) {
5702        return false;
5703    }
5704    // Gate 2: the probability lottery. A loss stops here and stamps nothing
5705    // shared.
5706    if !lottery_wins {
5707        return false;
5708    }
5709    // Gate 3: the shared actual-audit cooldown (a recent real audit from
5710    // either path still suppresses this launch), stamped only on launch.
5711    cooldown_allows_audit(launched, peer, now)
5712}
5713
5714/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
5715/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
5716/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
5717/// handling is never blocked on a network round-trip.
5718async fn maybe_trigger_gossip_audit(
5719    trigger: &GossipAuditTrigger,
5720    peer: &PeerId,
5721    target: AuditTarget,
5722) {
5723    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
5724    // lives in the pure `audit_launch_decision` so the ordering is shared with
5725    // its test. Sample the lottery here, then let the helper apply the gates.
5726    let now = Instant::now();
5727    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
5728    {
5729        // Lock order: attempts before the shared cooldown; this is the only
5730        // place both are held together.
5731        let mut attempts = trigger.lottery_attempts.write().await;
5732        let mut launched = trigger.cooldown.write().await;
5733        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
5734            return;
5735        }
5736    }
5737
5738    let trigger = trigger.clone();
5739    let peer = *peer;
5740    tokio::spawn(async move {
5741        let credit = storage_commitment_audit::AuditCredit {
5742            recent_provers: &trigger.recent_provers,
5743        };
5744        let result = storage_commitment_audit::run_subtree_audit(
5745            &trigger.p2p_node,
5746            &trigger.config,
5747            &peer,
5748            target.pin_hash,
5749            target.key_count,
5750            Some(&credit),
5751        )
5752        .await;
5753        handle_subtree_audit_result(
5754            &result,
5755            &trigger.p2p_node,
5756            &trigger.sync_state,
5757            &trigger.recent_provers,
5758            &trigger.config,
5759        )
5760        .await;
5761    });
5762}
5763
5764/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
5765///
5766/// Returns `true` if a signature verify is allowed now (and stamps the attempt
5767/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
5768/// of its last attempt. Holds one write lock across the decision so two
5769/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
5770/// caller's expensive verify so a slow/failed verify still rate-limits the next
5771/// message. Bounds the map under a flood of distinct peer ids.
5772async fn sig_verify_rate_limit_ok(
5773    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
5774    source: &PeerId,
5775    now: Instant,
5776) -> bool {
5777    let mut attempts = sig_verify_attempts.write().await;
5778    if let Some(&last) = attempts.get(source) {
5779        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
5780            return false;
5781        }
5782    }
5783    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
5784        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
5785            attempts.remove(&victim);
5786        }
5787    }
5788    attempts.insert(*source, now);
5789    true
5790}
5791
5792/// Verify + store an inbound commitment from a gossip peer.
5793///
5794/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
5795/// the bootstrap-sync loop. Drops the commitment unless all five gates
5796/// pass:
5797///   1. `source` is in our DHT routing table (sybil/churn cap).
5798///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
5799///      binding to the authenticated transport peer).
5800///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
5801///      (the embedded pubkey actually belongs to the claimed identity —
5802///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
5803///   4. `verify_commitment_signature(commitment)` succeeds against the
5804///      embedded public key. The signed payload binds the pubkey, so an
5805///      adversary cannot swap the key while keeping the body.
5806///   5. The cache has room or this is an update for an existing entry
5807///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
5808///
5809/// On all-pass, the commitment is stored as the auditor's per-peer
5810/// "last known commitment" for use as `expected_commitment_hash` in
5811/// future audits.
5812///
5813/// Failures (no commitment / mismatched peer id / bad signature) are
5814/// silent drops — gossip is best-effort and a malformed commitment from
5815/// one peer should not affect anything else.
5816///
5817/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
5818/// or not its root changed), so the caller can run a probabilistic,
5819/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
5820/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
5821/// being auditable, so it cannot pass one audit and then delete data while
5822/// re-gossiping the same root forever. The cooldown + probability bound the
5823/// audit frequency. Returns `None` only if the commitment was dropped (failed a
5824/// gate) or there is nothing to pin.
5825///
5826/// Handle a capable peer gossiping `None` (a commitment downgrade).
5827///
5828/// A capable peer that previously gossiped a commitment but now gossips `None`
5829/// is trying to drop off the audit path. Within the answerability window we keep
5830/// the cached commitment pinned AND return it as an audit target so this gossip
5831/// still schedules a subtree audit against the peer's last known commitment — if
5832/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
5833/// the trigger MUST fire here or the downgrade is never re-challenged).
5834///
5835/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
5836/// honours for its own retired commitment: once that elapses since we last
5837/// received the peer's commitment, an honest peer has legitimately retired that
5838/// root (its responder side `retire_current`s and lets it age out) and can no
5839/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
5840/// failure, so we then forget the cached commitment (keeping the sticky
5841/// `commitment_capable` bit) and stop pinning it.
5842async fn handle_commitment_downgrade(
5843    source: &PeerId,
5844    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
5845) -> Option<AuditTarget> {
5846    let now = Instant::now();
5847    let cached = {
5848        let map = last_commitment_by_peer.read().await;
5849        map.get(source).and_then(|rec| {
5850            if !rec.commitment_capable {
5851                return None;
5852            }
5853            let last = rec.last_commitment()?;
5854            let pin = rec.commitment_hash()?;
5855            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
5856            Some((pin, last.key_count, fresh))
5857        })
5858    };
5859    match cached {
5860        Some((pin, key_count, true)) => {
5861            warn!(
5862                "ingest_peer_commitment: commitment-capable peer {source} sent None \
5863                 (downgrade attempt); auditing against its last cached commitment"
5864            );
5865            Some(AuditTarget {
5866                pin_hash: pin,
5867                key_count,
5868            })
5869        }
5870        Some((_, _, false)) => {
5871            // Cached commitment has aged past the answerability window — forget
5872            // it so we stop pinning a root the peer is no longer obliged to
5873            // answer. Keep `commitment_capable` (sticky). Re-check freshness
5874            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
5875            // from this peer may have refreshed `received_at` in the gap between
5876            // our read and write locks; if so, leave its fresh commitment intact.
5877            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
5878                let still_stale =
5879                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
5880                if still_stale {
5881                    rec.clear_commitment();
5882                    debug!(
5883                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
5884                         commitment aged past the answerability TTL; forgetting it"
5885                    );
5886                }
5887            }
5888            None
5889        }
5890        None => None,
5891    }
5892}
5893
5894async fn ingest_peer_commitment(
5895    source: &PeerId,
5896    commitment: Option<&StorageCommitment>,
5897    p2p_node: &Arc<P2PNode>,
5898    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
5899    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
5900    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
5901) -> Option<AuditTarget> {
5902    let Some(c) = commitment else {
5903        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
5904    };
5905    // RT-membership gate: only accept commitments from peers in our
5906    // routing table. Off-RT senders (sybils, drive-by relays) cannot
5907    // populate the cache, which closes the hole where a flood of
5908    // off-RT identities could fill the cap and evict honest
5909    // peers. The neighbor-sync request handler applies the same gate
5910    // before admitting inbound replication hints (see neighbor_sync.rs
5911    // `sender_in_rt`); we mirror that policy here for the commitment
5912    // piggyback.
5913    if !p2p_node.dht_manager().is_in_routing_table(source).await {
5914        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
5915        return None;
5916    }
5917    // Peer-id binding: the commitment's claimed sender must match the
5918    // authenticated transport peer (`source`). Defeats relay/replay
5919    // and also pins which embedded public key we are about to verify
5920    // against — the verify itself trusts the embedded key, so the
5921    // peer-id binding is the link to a real identity.
5922    if &c.sender_peer_id != source.as_bytes() {
5923        warn!(
5924            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
5925             (dropped, possible relay attempt)"
5926        );
5927        return None;
5928    }
5929    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
5930    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
5931    // with a throwaway key they own and lie about which identity it
5932    // belongs to (the embedded-key signature would verify trivially).
5933    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
5934    if derived_peer_id != c.sender_peer_id {
5935        warn!(
5936            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
5937             {source} (dropped, throwaway-key attack)"
5938        );
5939        return None;
5940    }
5941    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
5942    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
5943    // sybil/RT-membership-bypassing peer that flooded valid-looking
5944    // gossip would otherwise burn CPU on every message. The rate
5945    // limit is checked AFTER cheap structural gates (RT, peer-id
5946    // binding, pubkey-binding) and BEFORE the expensive sig verify.
5947    //
5948    // Tracked in `sig_verify_attempts` (separate from
5949    // last_commitment_by_peer) so EVERY attempt — successful or not —
5950    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
5951    // would skip the cap for peers we've never successfully verified,
5952    // letting a flood of invalid-but-structurally-plausible gossips
5953    // burn CPU.
5954    let now = Instant::now();
5955    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
5956        debug!(
5957            "ingest_peer_commitment: rate-limited sig verify from {source} \
5958             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
5959        );
5960        return None;
5961    }
5962    // Signature verify, using the public key embedded in the commitment
5963    // itself. The pubkey is bound by the signature payload (see
5964    // commitment_signed_payload) so an adversary cannot keep the body
5965    // and swap the key to one they hold the secret for.
5966    if !crate::replication::commitment::verify_commitment_signature(c) {
5967        warn!(
5968            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
5969             (dropped, forged commitment)"
5970        );
5971        return None;
5972    }
5973    // The new commitment's hash, used to store and to pin for the audit target.
5974    let new_hash = commitment_hash(c);
5975    let mut map = last_commitment_by_peer.write().await;
5976    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
5977    // evict an arbitrary existing entry to make room. Updates for peers
5978    // already in the map are always accepted (they replace, not grow).
5979    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
5980        // Drop one arbitrary entry. HashMap iter order is random which
5981        // is fine — over time PeerRemoved cleanup keeps the working set
5982        // anchored on the real RT membership; this cap only fires under
5983        // active flooding attempts.
5984        if let Some(victim) = map.keys().next().copied() {
5985            map.remove(&victim);
5986            warn!(
5987                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
5988                 evicted {victim} to admit {source}"
5989            );
5990        }
5991    }
5992    // Preserve sticky commitment_capable across updates — once true,
5993    // always true. New entries start with capable = true (we just
5994    // verified a valid commitment from this peer).
5995    map.entry(*source)
5996        .and_modify(|r| {
5997            // set_commitment refreshes the cached hash (§13) alongside the
5998            // commitment + received_at so they never drift.
5999            r.set_commitment(c.clone(), now);
6000            r.last_sig_verify_at = now;
6001            r.commitment_capable = true; // sticky-redundant but explicit
6002        })
6003        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
6004    drop(map);
6005    // Record the sticky "ever v12-capable" bit in a set independent of
6006    // `last_commitment_by_peer` (whose entries can be evicted by
6007    // `PeerRemoved` and the sybil cap). This is what the §3 audit
6008    // shield and the §6 holder-eligibility closure consult to decide
6009    // whether the peer is expected to speak v12.
6010    //
6011    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
6012    // identity-rotation attacks: once full, new entries are refused.
6013    // Refusal degrades over-cap peers to the behaviour before this set
6014    // existed (treated as legacy on rejoin), which is not a security
6015    // regression and preserves the historic set stable.
6016    {
6017        let mut set = ever_capable_peers.write().await;
6018        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
6019            set.insert(*source);
6020        } else {
6021            warn!(
6022                "ingest_peer_commitment: ever_capable_peers at cap \
6023                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
6024            );
6025        }
6026    }
6027    // Return an audit target for EVERY valid stored commitment (changed or
6028    // not), so the caller's cooldown+probability-gated trigger keeps a
6029    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
6030    // failure (new_hash == None, unreachable for a real commitment) yields None.
6031    new_hash.map(|pin_hash| AuditTarget {
6032        pin_hash,
6033        key_count: c.key_count,
6034    })
6035}
6036
6037// ---------------------------------------------------------------------------
6038// Storage-bound audit (v12) — responder commitment rotation
6039// ---------------------------------------------------------------------------
6040
6041/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
6042/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
6043/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
6044async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
6045    let bytes = match tokio::fs::read(path).await {
6046        Ok(b) => b,
6047        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
6048            debug!(
6049                "Commitment retention: no snapshot at {} (fresh start)",
6050                path.display()
6051            );
6052            return;
6053        }
6054        Err(e) => {
6055            warn!(
6056                "Commitment retention: failed to read {}: {e}",
6057                path.display()
6058            );
6059            return;
6060        }
6061    };
6062    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
6063        state.restore(&persisted);
6064        info!(
6065            "Commitment retention: reloaded {} slot(s) from {}",
6066            state.retained_slot_count(),
6067            path.display()
6068        );
6069    } else {
6070        warn!(
6071            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
6072            path.display()
6073        );
6074    }
6075}
6076
6077/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
6078/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
6079/// needless disk writes on idle nodes. On success updates `last` to the bytes
6080/// written; on a serialization/write error the existing on-disk snapshot is left
6081/// intact (never truncated).
6082async fn persist_retention_if_changed(
6083    state: &ResponderCommitmentState,
6084    path: &Path,
6085    last: &mut Option<Vec<u8>>,
6086) {
6087    let Some(bytes) = state.snapshot().to_bytes() else {
6088        warn!("Commitment retention: serialization failed; keeping previous snapshot");
6089        return;
6090    };
6091    if last.as_deref() == Some(bytes.as_slice()) {
6092        return;
6093    }
6094    if write_retention_atomic(path, bytes.clone()).await {
6095        *last = Some(bytes);
6096    }
6097}
6098
6099/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
6100/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
6101/// success. Only the retention-persist loop writes this path, so a fixed temp
6102/// name is safe.
6103async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
6104    let path = path.to_path_buf();
6105    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
6106        let tmp = path.with_extension("tmp");
6107        std::fs::write(&tmp, &bytes)?;
6108        std::fs::File::open(&tmp)?.sync_all()?;
6109        std::fs::rename(&tmp, &path)?;
6110        // Fsync the directory so the rename (the durable-commit point) is not
6111        // lost on a crash right after it. An empty parent (relative filename)
6112        // means the current directory.
6113        let dir = path
6114            .parent()
6115            .filter(|p| !p.as_os_str().is_empty())
6116            .unwrap_or_else(|| Path::new("."));
6117        std::fs::File::open(dir)?.sync_all()?;
6118        Ok(())
6119    })
6120    .await;
6121    match res {
6122        Ok(Ok(())) => true,
6123        Ok(Err(e)) => {
6124            warn!("Commitment retention: persist failed: {e}");
6125            false
6126        }
6127        Err(e) => {
6128            warn!("Commitment retention: persist task join failed: {e}");
6129            false
6130        }
6131    }
6132}
6133
6134/// Read the current LMDB key set, build + sign a fresh
6135/// `StorageCommitment`, and rotate it into `state` as the new `current`.
6136/// The prior `current` is demoted to `previous`; the prior `previous` is
6137/// dropped (per `ResponderCommitmentState::rotate`).
6138///
6139/// For content-addressed chunks (Autonomi's chunk store), `address ==
6140/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
6141/// re-read each chunk's bytes to compute the leaf hash.
6142///
6143/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
6144/// rotate. The auditor side handles "no commitment for this peer" by
6145/// falling back to the legacy plain-digest audit path.
6146async fn rebuild_and_rotate_commitment(
6147    storage: &Arc<LmdbStorage>,
6148    identity: &Arc<NodeIdentity>,
6149    state: &Arc<ResponderCommitmentState>,
6150    p2p: &Arc<P2PNode>,
6151    config: &Arc<ReplicationConfig>,
6152) -> Result<()> {
6153    let stored_keys = storage
6154        .all_keys()
6155        .await
6156        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
6157
6158    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
6159    // everything currently on disk ("hold"). This is the half of the retention
6160    // contract that lets out-of-range chunks age out: a key that has left our
6161    // close group is excluded from the NEXT commitment, so once its last gossip
6162    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
6163    // set, `ResponderCommitmentState::is_held` goes false,
6164    // and the pruner (which until then vetoes its deletion) reclaims it. Without
6165    // this filter the pruner's reprieve would keep re-committing stale keys
6166    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
6167    // re-committed and re-gossiped every rotation — a permanent pin).
6168    let storage_empty = stored_keys.is_empty();
6169    let self_id = *p2p.peer_id();
6170    let mut keys = Vec::with_capacity(stored_keys.len());
6171    for k in stored_keys {
6172        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
6173            keys.push(k);
6174        }
6175    }
6176
6177    if keys.is_empty() {
6178        if storage_empty {
6179            // Storage is genuinely empty — there is nothing to answer for, so
6180            // drop the previously advertised commitment immediately. Keeping it
6181            // would leave remote auditors pinning a hash we can never satisfy
6182            // again (the bytes are gone).
6183            if state.retained_slot_count() > 0 {
6184                debug!("Commitment rotation: storage empty, clearing retained slots");
6185                state.clear_all();
6186            }
6187            return Ok(());
6188        }
6189        // Bytes are still on disk but no key is currently in range. We must NOT
6190        // clear retention here: a peer may still be pinning a root we gossiped
6191        // moments ago and could demand its bytes in a round-2 challenge, which
6192        // we can still answer (the bytes are present). But we must STOP
6193        // advertising the stale commitment: retire it so `current()` returns
6194        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
6195        // The retired slot then ages out by its gossip-answerability TTL while
6196        // remaining answerable for in-flight pins until then. Once it ages out,
6197        // `is_held` flips false and the pruner reclaims the now-uncommitted,
6198        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
6199        // pointing at the stale root, which the gossip loop would keep
6200        // re-stamping — pinning its keys forever.)
6201        debug!(
6202            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
6203             (stays answerable until its gossip TTL lapses, bytes still on disk)"
6204        );
6205        state.retire_current();
6206        return Ok(());
6207    }
6208
6209    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
6210    // to more than the protocol limit; auditor would reject the
6211    // commitment otherwise).
6212    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
6213    if keys.len() > cap {
6214        warn!(
6215            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
6216             truncating — investigate as this likely means a misconfiguration",
6217            keys.len(),
6218            cap
6219        );
6220    }
6221
6222    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
6223    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
6224    // full chunk re-read per rotation.
6225    //
6226    // Consequence to be precise about: because the leaf is `(key, key)`,
6227    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
6228    // commitment therefore binds "which keys I claim to hold"; it does NOT
6229    // by itself prove byte possession. Byte possession is enforced by the
6230    // audit-verify path, which recomputes `bytes_hash == BLAKE3(local_bytes)`
6231    // and the per-key digest against the AUDITOR'S OWN local copy of the
6232    // bytes — so a responder that holds the key list but dropped the bytes
6233    // still fails (`missing bytes for committed key` / digest mismatch).
6234    // This is sound ONLY while keys are content addresses. If this module
6235    // is ever reused for non-content-addressed records (`bytes_hash != key`),
6236    // the `(k, k)` shortcut would let a byte-less node forge a valid root and
6237    // MUST be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
6238    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
6239
6240    // No-op-rotation guard: compute just the Merkle root from `entries`
6241    // and compare against the currently-advertised commitment's root.
6242    // If they match, the key set is unchanged and a new rotation would
6243    // only swap a randomized ML-DSA signature for a fresh one — same
6244    // content, different commitment_hash. That invalidates every
6245    // outstanding `recent_provers` credit on this node across the
6246    // close group with no security benefit, breaking steady-state
6247    // quorum liveness on large nodes that can't re-audit every key
6248    // every rotation interval. Skip the rotation entirely when the
6249    // tree is unchanged.
6250    // Build the tree ONCE here (moving `entries`): it serves both the no-op
6251    // root check below and, if we proceed, the signed commitment via
6252    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
6253    // inside `BuiltCommitment::build`).
6254    let candidate_tree = commitment::MerkleTree::build(entries)
6255        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
6256    let candidate_root = candidate_tree.root();
6257    if let Some(current) = state.current() {
6258        if current.commitment().root == candidate_root {
6259            debug!(
6260                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
6261                hex::encode(candidate_root)
6262            );
6263            // Even though we skip re-signing (to avoid invalidating holder
6264            // credit), retention must still advance on the wall clock: a
6265            // previously-gossiped commitment that holds a now-out-of-range key
6266            // must be able to age out of the answerability window even when the
6267            // committed key set is frozen here for many rotations. Without this,
6268            // the no-op guard would pin a stale slot — and its key — forever.
6269            state.age_out();
6270            return Ok(());
6271        }
6272    }
6273
6274    let sk_bytes = identity.secret_key_bytes().to_vec();
6275    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
6276        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
6277    let pk_bytes = identity.public_key().as_bytes().to_vec();
6278    let peer_id_bytes = *p2p.peer_id().as_bytes();
6279
6280    let built = commitment_state::BuiltCommitment::build_from_tree(
6281        candidate_tree,
6282        &peer_id_bytes,
6283        &sk,
6284        &pk_bytes,
6285    )
6286    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
6287
6288    let hash = hex::encode(built.hash());
6289    let key_count = built.commitment().key_count;
6290    state.rotate(built);
6291    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
6292    Ok(())
6293}
6294
6295#[cfg(test)]
6296#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
6297mod tests {
6298    use super::*;
6299    use super::{
6300        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
6301        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
6302        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
6303        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
6304        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
6305        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
6306        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
6307        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
6308    };
6309    use crate::payment::VerificationContext;
6310    use crate::replication::audit::AuditTickResult;
6311    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
6312    use crate::replication::recent_provers::RecentProvers;
6313    use crate::replication::types::{AuditFailureReason, FailureEvidence};
6314    use lru::LruCache;
6315    use saorsa_core::identity::PeerId;
6316    use std::collections::HashMap;
6317    use std::num::NonZeroUsize;
6318    use std::sync::atomic::Ordering;
6319    use std::sync::Arc;
6320    use std::time::Duration;
6321    use std::time::Instant;
6322    use std::time::SystemTime;
6323
6324    fn test_peer(b: u8) -> PeerId {
6325        let mut bytes = [0u8; 32];
6326        bytes[0] = b;
6327        PeerId::from_bytes(bytes)
6328    }
6329
6330    fn test_key(b: u8) -> crate::ant_protocol::XorName {
6331        let mut k = [0u8; 32];
6332        k[0] = b;
6333        k
6334    }
6335
6336    #[tokio::test]
6337    async fn audit_responder_admission_reports_per_peer_cap_full() {
6338        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
6339        let inflight = Arc::new(RwLock::new(HashMap::new()));
6340        let peer = test_peer(0xA1);
6341
6342        let mut guards = Vec::new();
6343        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
6344            match admit_audit_responder(&semaphore, &inflight, &peer).await {
6345                Ok(guard) => guards.push(guard),
6346                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
6347            }
6348        }
6349
6350        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
6351            panic!("admission should fail once per-peer cap is full");
6352        };
6353        assert_eq!(err.reason, AuditResponderRejectReason::PerPeerCapFull);
6354        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
6355        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
6356        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
6357
6358        drop(guards);
6359    }
6360
6361    #[tokio::test]
6362    async fn audit_responder_admission_reports_global_pool_full() {
6363        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
6364        let inflight = Arc::new(RwLock::new(HashMap::new()));
6365        let peer = test_peer(0xA2);
6366
6367        let mut held_global_permits = Vec::new();
6368        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
6369            held_global_permits.push(
6370                Arc::clone(&semaphore)
6371                    .try_acquire_owned()
6372                    .expect("test should be able to exhaust the global pool"),
6373            );
6374        }
6375
6376        let Err(err) = admit_audit_responder(&semaphore, &inflight, &peer).await else {
6377            panic!("admission should fail once global pool is full");
6378        };
6379        assert_eq!(err.reason, AuditResponderRejectReason::GlobalPoolFull);
6380        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
6381        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
6382        assert_eq!(err.peer_inflight, 0);
6383        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
6384
6385        drop(held_global_permits);
6386    }
6387
6388    #[test]
6389    fn first_audit_terminal_outcomes_are_stable() {
6390        let peer = test_peer(1);
6391        let passed = AuditTickResult::Passed {
6392            challenged_peer: peer,
6393            keys_checked: 1,
6394        };
6395        let timed_out = AuditTickResult::Failed {
6396            evidence: FailureEvidence::AuditFailure {
6397                challenge_id: 1,
6398                challenged_peer: peer,
6399                confirmed_failed_keys: vec![test_key(1)],
6400                summary: crate::replication::types::AuditFailureSummary::default(),
6401                reason: AuditFailureReason::Timeout,
6402            },
6403        };
6404
6405        assert_eq!(
6406            first_audit_terminal_outcome(&passed),
6407            FirstAuditTerminalOutcome::Passed
6408        );
6409        assert_eq!(
6410            first_audit_terminal_outcome(&timed_out),
6411            FirstAuditTerminalOutcome::Timeout
6412        );
6413        assert_eq!(
6414            first_audit_terminal_outcome(&AuditTickResult::Idle),
6415            FirstAuditTerminalOutcome::Idle
6416        );
6417        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
6418        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
6419        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
6420        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
6421        assert_eq!(
6422            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
6423            "insufficient_keys"
6424        );
6425        assert_eq!(
6426            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
6427            "bootstrap_claim"
6428        );
6429    }
6430
6431    #[test]
6432    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
6433        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
6434        let mut rng = StdRng::seed_from_u64(7);
6435        let peer = test_peer(1);
6436        let base = MonetizedPinEvent {
6437            peer,
6438            pin: [1; 32],
6439            key_count: 100,
6440            quote_ts: SystemTime::now(),
6441        };
6442
6443        // First insert into an empty slot: Queued.
6444        assert_eq!(
6445            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
6446            FirstAuditQueueOutcome::Queued
6447        );
6448
6449        // A strictly LOWER-count same-peer nomination must NOT displace it.
6450        let lower = MonetizedPinEvent {
6451            pin: [2; 32],
6452            key_count: 50,
6453            ..base
6454        };
6455        assert_eq!(
6456            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
6457            FirstAuditQueueOutcome::SuppressedLower
6458        );
6459        assert_eq!(
6460            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
6461            Some(([1; 32], 100)),
6462            "the higher-count pin is retained"
6463        );
6464
6465        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
6466        let higher = MonetizedPinEvent {
6467            pin: [3; 32],
6468            key_count: 400,
6469            ..base
6470        };
6471        assert_eq!(
6472            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
6473            FirstAuditQueueOutcome::Coalesced
6474        );
6475        assert_eq!(
6476            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
6477            Some(([3; 32], 400))
6478        );
6479
6480        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
6481        let equal_newer = MonetizedPinEvent {
6482            pin: [4; 32],
6483            key_count: 400,
6484            ..base
6485        };
6486        assert_eq!(
6487            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
6488            FirstAuditQueueOutcome::Coalesced
6489        );
6490        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
6491        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
6492        let equal_older = MonetizedPinEvent {
6493            pin: [5; 32],
6494            key_count: 400,
6495            ..base
6496        };
6497        assert_eq!(
6498            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
6499            FirstAuditQueueOutcome::RetainedOnTie
6500        );
6501        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
6502
6503        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
6504        let other_peer = MonetizedPinEvent {
6505            peer: test_peer(2),
6506            pin: [6; 32],
6507            key_count: 100,
6508            ..base
6509        };
6510        assert_eq!(
6511            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
6512            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
6513        );
6514        assert_eq!(pending.len(), 1);
6515        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
6516    }
6517
6518    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
6519
6520    #[test]
6521    fn first_audit_limiter_enforces_burst_then_refills() {
6522        let base = Instant::now();
6523        let mut limiter = FirstAuditLimiter::new(base);
6524        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
6525
6526        // The full burst is admitted back-to-back (distinct peers).
6527        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
6528            let peer = test_peer(u8::try_from(i).expect("small burst"));
6529            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
6530            limiter.commit_launch(peer, 10, base);
6531        }
6532        // Bucket empty: the next distinct peer is deferred, never dropped.
6533        let extra = test_peer(0xEE);
6534        assert_eq!(
6535            limiter.assess(&extra, 10, base, 0),
6536            LimiterVerdict::RateDeferred
6537        );
6538
6539        // One full interval later exactly one token is available again.
6540        let later = base + interval;
6541        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
6542        limiter.commit_launch(extra, 10, later);
6543        let extra2 = test_peer(0xEF);
6544        assert_eq!(
6545            limiter.assess(&extra2, 10, later, 0),
6546            LimiterVerdict::RateDeferred
6547        );
6548    }
6549
6550    #[test]
6551    fn first_audit_limiter_refill_keeps_fractional_remainder() {
6552        let base = Instant::now();
6553        let mut limiter = FirstAuditLimiter::new(base);
6554        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
6555        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
6556            let peer = test_peer(u8::try_from(i).expect("small burst"));
6557            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
6558            limiter.commit_launch(peer, 1, base);
6559        }
6560        // 1.5 intervals later one token is earned and the half interval is
6561        // NOT lost to drift...
6562        let at_1_5 = base + interval + interval / 2;
6563        let p = test_peer(0xAA);
6564        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
6565        limiter.commit_launch(p, 1, at_1_5);
6566        // ...so the next token arrives at 2.0 intervals, not 2.5.
6567        let at_2_0 = base + interval * 2;
6568        let q = test_peer(0xAB);
6569        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
6570    }
6571
6572    #[test]
6573    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
6574        let base = Instant::now();
6575        let mut limiter = FirstAuditLimiter::new(base);
6576        let peer = test_peer(1);
6577        assert_eq!(
6578            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
6579            LimiterVerdict::RateDeferred
6580        );
6581        // A freed slot admits without any clock movement.
6582        assert_eq!(
6583            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
6584            LimiterVerdict::Admit
6585        );
6586    }
6587
6588    #[test]
6589    fn first_audit_limiter_assess_consumes_nothing() {
6590        let base = Instant::now();
6591        let mut limiter = FirstAuditLimiter::new(base);
6592        let peer = test_peer(3);
6593        // Repeated assessment must not burn budget or stamp the window: only
6594        // `commit_launch` consumes (the cooldown gate between assess and
6595        // commit can defer, and that deferral must be free).
6596        for _ in 0..10 {
6597            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
6598        }
6599        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
6600            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
6601            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
6602            limiter.commit_launch(p, 5, base);
6603        }
6604    }
6605
6606    #[test]
6607    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
6608        let base = Instant::now();
6609        let mut limiter = FirstAuditLimiter::new(base);
6610        let peer = test_peer(7);
6611        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
6612        limiter.commit_launch(peer, 100, base);
6613
6614        // A rotated pin with a similar count inside the window is dropped...
6615        let soon = base + Duration::from_secs(60);
6616        assert_eq!(
6617            limiter.assess(&peer, 100, soon, 0),
6618            LimiterVerdict::WindowDeduped
6619        );
6620        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
6621        assert_eq!(
6622            limiter.assess(&peer, 150, soon, 0),
6623            LimiterVerdict::WindowDeduped
6624        );
6625        // ...but a >1.5x committed-count jump re-nominates immediately (an
6626        // inflated sidecar-only pin is invisible to the gossip lottery, so
6627        // the window must not shield it).
6628        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
6629
6630        // Window expiry re-admits an unchanged count.
6631        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
6632        assert_eq!(
6633            limiter.assess(&peer, 100, expired, 0),
6634            LimiterVerdict::Admit
6635        );
6636    }
6637
6638    #[test]
6639    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
6640        // A window-deduped nomination must be DROPPED, not kept pending as
6641        // rate-deferred, even when the bucket is also empty: re-queuing a
6642        // suppressed rotation would hold a pending slot for two hours.
6643        let base = Instant::now();
6644        let mut limiter = FirstAuditLimiter::new(base);
6645        let peer = test_peer(9);
6646        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
6647        limiter.commit_launch(peer, 10, base);
6648        let other = test_peer(10);
6649        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
6650        limiter.commit_launch(other, 10, base);
6651        assert_eq!(
6652            limiter.assess(&peer, 10, base, 0),
6653            LimiterVerdict::WindowDeduped
6654        );
6655    }
6656
6657    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
6658    /// is answerable now but would age out of the answerability window during
6659    /// the launch jitter, so scheduling state is only ever committed for a pin
6660    /// that can still be challenged when it actually sends.
6661    #[test]
6662    fn first_audit_horizon_prefilter_boundary() {
6663        let now = SystemTime::now();
6664        // C = the too-old cutoff; H = the worst-case send horizon.
6665        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
6666        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
6667        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
6668        let boundary = now
6669            .checked_add(h)
6670            .and_then(|t| t.checked_sub(c))
6671            .expect("boundary time");
6672
6673        // In window at `now` (age = C - H < C)...
6674        assert!(quote_within_audit_window(boundary, now));
6675        // ...but the horizon prefilter rejects it (age == C at now + H).
6676        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
6677
6678        // A hair newer stays answerable through the horizon; a hair older does
6679        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
6680        // a nanosecond step would round to the same instant there.
6681        let newer = boundary
6682            .checked_add(Duration::from_micros(1))
6683            .expect("newer");
6684        let older = boundary
6685            .checked_sub(Duration::from_micros(1))
6686            .expect("older");
6687        assert!(quote_answerable_through_nominal_jitter(newer, now));
6688        assert!(!quote_answerable_through_nominal_jitter(older, now));
6689
6690        // A quote too far in the FUTURE is rejected at `now`, independent of the
6691        // horizon.
6692        let future = now
6693            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
6694            .and_then(|t| t.checked_add(Duration::from_secs(60)))
6695            .expect("future");
6696        assert!(!quote_answerable_through_nominal_jitter(future, now));
6697    }
6698
6699    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
6700    /// answerability check fails at promotion is fully state-neutral — it stamps
6701    /// no `first_audited`, no per-peer window, refunds its token, releases its
6702    /// in-flight slot, does not flip the lane, and does not count a launch — and
6703    /// a same-peer, same-count successor enqueued DURING the reservation is
6704    /// retained and becomes the next reservation after the cancel. This is the
6705    /// exact hole the reviewer flagged: suppression must never outlive a launch
6706    /// that did not send.
6707    /// A pending pin that has aged past the answerability horizon must not
6708    /// suppress a live lower-count nomination for the same peer: under token
6709    /// starvation no reserve scan ever collects the dead entry, so without the
6710    /// enqueue-time check the peer would stay unauditable through this path
6711    /// indefinitely (e.g. after a prune legitimately lowered its key count).
6712    #[test]
6713    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
6714        let obs = Arc::new(FirstAuditObservability::default());
6715        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6716        let peer = test_peer(1);
6717
6718        let dead_quote = SystemTime::now()
6719            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
6720            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
6721            .expect("past wall time");
6722        let stale_high = MonetizedPinEvent {
6723            peer,
6724            pin: [1; 32],
6725            key_count: 400,
6726            quote_ts: dead_quote,
6727        };
6728        scheduler.enqueue(stale_high, &obs);
6729        assert_eq!(scheduler.pending_len(), 1);
6730
6731        // A fresh, lower-count nomination (a post-prune commitment).
6732        let fresh_lower = MonetizedPinEvent {
6733            peer,
6734            pin: [2; 32],
6735            key_count: 100,
6736            quote_ts: SystemTime::now(),
6737        };
6738        scheduler.enqueue(fresh_lower, &obs);
6739
6740        assert_eq!(scheduler.pending_len(), 1);
6741        assert_eq!(
6742            scheduler.pending.peek(&peer).map(|e| e.pin),
6743            Some([2; 32]),
6744            "the live nomination replaced the dead incumbent"
6745        );
6746        assert_eq!(
6747            obs.suppressed_lower.load(Ordering::Relaxed),
6748            0,
6749            "no self-erasure signal for displacing a dead pin"
6750        );
6751        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
6752        assert_eq!(
6753            obs.outside_answerability_window.load(Ordering::Relaxed),
6754            1,
6755            "the dead incumbent is accounted as an expiry"
6756        );
6757    }
6758
6759    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
6760    /// nomination still loses to an answerable higher-count pending pin.
6761    #[test]
6762    fn first_audit_live_incumbent_still_suppresses_lower_count() {
6763        let obs = Arc::new(FirstAuditObservability::default());
6764        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6765        let peer = test_peer(1);
6766
6767        let live_high = MonetizedPinEvent {
6768            peer,
6769            pin: [1; 32],
6770            key_count: 400,
6771            quote_ts: SystemTime::now(),
6772        };
6773        scheduler.enqueue(live_high, &obs);
6774        let cheaper = MonetizedPinEvent {
6775            peer,
6776            pin: [2; 32],
6777            key_count: 100,
6778            quote_ts: SystemTime::now(),
6779        };
6780        scheduler.enqueue(cheaper, &obs);
6781
6782        assert_eq!(scheduler.pending_len(), 1);
6783        assert_eq!(
6784            scheduler.pending.peek(&peer).map(|e| e.pin),
6785            Some([1; 32]),
6786            "the higher-count live pin is retained"
6787        );
6788        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
6789        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
6790    }
6791
6792    /// A fresh nomination for peer `b` (distinct pin per peer).
6793    fn live_nomination(b: u8) -> MonetizedPinEvent {
6794        MonetizedPinEvent {
6795            peer: test_peer(b),
6796            pin: [b; 32],
6797            key_count: 100,
6798            quote_ts: SystemTime::now(),
6799        }
6800    }
6801
6802    /// The pending admission cap must equal the number of usable launches the
6803    /// token budget can perform inside one answerability window, counted by
6804    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
6805    /// tokens at age zero, one refill per launch interval), not by repeating
6806    /// the derivation formula. Any larger and admitted work is guaranteed to
6807    /// expire unlaunched; any smaller and the budget idles while nominations
6808    /// are displaced.
6809    #[test]
6810    fn first_audit_pending_cap_matches_strict_launch_horizon() {
6811        let quote_ts = SystemTime::now();
6812        // Burst launches fire at age zero and must pass the reserve predicate.
6813        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
6814        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
6815        let mut refill = 1u32;
6816        loop {
6817            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
6818            let at = quote_ts + age;
6819            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
6820                break;
6821            }
6822            usable += 1;
6823            refill += 1;
6824            assert!(refill < 10_000, "runaway horizon simulation");
6825        }
6826        assert_eq!(
6827            FIRST_AUDIT_PENDING_CAP, usable,
6828            "cap must match the simulated strict launch horizon"
6829        );
6830    }
6831
6832    /// The pending queue is sized to the launch budget while the dedup set
6833    /// keeps the commitment-cache bound: shrinking `first_audited` would
6834    /// forget audited pins and re-admit duplicates.
6835    #[test]
6836    fn first_audit_pending_cap_independent_of_dedup_cap() {
6837        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6838        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
6839        assert_eq!(
6840            scheduler.first_audited.cap().get(),
6841            MAX_LAST_COMMITMENT_BY_PEER
6842        );
6843    }
6844
6845    /// Admission beyond the cap displaces exactly one incumbent per overflow
6846    /// and every displacement is accounted as `capacity_evicted` — the steady
6847    /// overload signal — never silent loss, and never an admission refusal.
6848    #[test]
6849    fn first_audit_admission_beyond_cap_displaces_and_counts() {
6850        let obs = Arc::new(FirstAuditObservability::default());
6851        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6852        let overflow: usize = 5;
6853        let total = FIRST_AUDIT_PENDING_CAP + overflow;
6854
6855        for i in 0..total {
6856            let b = u8::try_from(i + 1).expect("test peer count fits u8");
6857            scheduler.enqueue(live_nomination(b), &obs);
6858        }
6859
6860        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
6861        assert_eq!(
6862            obs.capacity_evicted.load(Ordering::Relaxed),
6863            u64::try_from(overflow).expect("overflow fits u64"),
6864            "each admission past the cap displaces exactly one entry"
6865        );
6866        assert_eq!(
6867            obs.queued.load(Ordering::Relaxed),
6868            u64::try_from(total).expect("total fits u64"),
6869            "displacement is not an admission refusal"
6870        );
6871        // Every arrival was admitted (the newest always enters the sample).
6872        let last = u8::try_from(total).expect("test peer count fits u8");
6873        assert!(
6874            scheduler.pending.peek(&test_peer(last)).is_some(),
6875            "the newest arrival always enters the sample"
6876        );
6877    }
6878
6879    /// The reviewer-demonstrated suppression route: a target followed by an
6880    /// ordered batch of distinct-peer nominations, all inside one ingress
6881    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
6882    /// the token bucket EMPTY so no reservation can intervene. Under the old
6883    /// keep-newest LRU the target was evicted with certainty; under random
6884    /// displacement its per-overflow eviction probability is `1/cap`, so
6885    /// across repeated trials the target must survive some runs and be
6886    /// displaced in others — never deterministically flushed, and every
6887    /// displacement accounted.
6888    #[test]
6889    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
6890        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
6891        assert!(FIRST_AUDIT_PENDING_CAP < flood);
6892        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
6893
6894        let trials = 100u64;
6895        let mut survived = 0u32;
6896        let mut evicted = 0u32;
6897        for trial in 0..trials {
6898            let obs = Arc::new(FirstAuditObservability::default());
6899            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6900            // Deterministic per-trial seed: the run is fully reproducible (no
6901            // flake budget at all) while still exercising 100 distinct
6902            // eviction sequences.
6903            scheduler.rng = StdRng::seed_from_u64(trial);
6904            // Drain the burst tokens so the pre-overflow reservation
6905            // opportunity cannot fire: this isolates pure retention.
6906            scheduler.limiter.reserve_token();
6907            scheduler.limiter.reserve_token();
6908
6909            let target = test_peer(200);
6910            scheduler.enqueue(live_nomination(200), &obs);
6911            for i in 0..flood {
6912                let b = u8::try_from(i + 1).expect("flood peer fits u8");
6913                scheduler.enqueue(live_nomination(b), &obs);
6914            }
6915
6916            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
6917            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
6918                .expect("overflow count fits u64");
6919            assert_eq!(
6920                obs.capacity_evicted.load(Ordering::Relaxed),
6921                overflows,
6922                "every overflow past the cap is accounted, none silent"
6923            );
6924            if scheduler.pending.peek(&target).is_some() {
6925                survived += 1;
6926            } else {
6927                evicted += 1;
6928            }
6929        }
6930        // With eviction probability 1/cap per overflow, P(target survives one
6931        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
6932        // 100 seeded trials — and the seeds make the split exactly
6933        // reproducible rather than a (vanishingly small) flake budget.
6934        assert!(
6935            survived > 0,
6936            "target must survive some ordered floods — deterministic eviction \
6937             would mean keep-newest retention regressed"
6938        );
6939        assert!(
6940            evicted > 0,
6941            "target must also be displaceable — otherwise overflow is refusing \
6942             admissions instead of sampling"
6943        );
6944    }
6945
6946    /// With a token AVAILABLE, an overflowing arrival must first give pending
6947    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
6948    /// one entry out of the queue, so admission proceeds without any eviction.
6949    #[test]
6950    fn first_audit_overflow_reserves_before_destructive_eviction() {
6951        let obs = Arc::new(FirstAuditObservability::default());
6952        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6953        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
6954
6955        for i in 0..FIRST_AUDIT_PENDING_CAP {
6956            let b = u8::try_from(i + 1).expect("test peer count fits u8");
6957            scheduler.enqueue(live_nomination(b), &obs);
6958        }
6959        let overflowing = live_nomination(250);
6960        assert!(scheduler.would_displace(&overflowing));
6961
6962        // The drainer's pre-overflow sequence: reserve, then enqueue.
6963        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
6964        assert!(
6965            !scheduler.would_displace(&overflowing),
6966            "a successful reservation frees the slot"
6967        );
6968        scheduler.enqueue(overflowing, &obs);
6969
6970        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
6971        assert_eq!(
6972            obs.capacity_evicted.load(Ordering::Relaxed),
6973            0,
6974            "no destructive eviction when a launch opportunity existed"
6975        );
6976    }
6977
6978    /// Displacement stamps no suppression state: a displaced peer's next
6979    /// nomination re-enters like any newcomer (it is NOT window-deduped or
6980    /// treated as a duplicate), so under overload every peer keeps an
6981    /// unpredictable chance of prompt first audit.
6982    #[test]
6983    fn first_audit_displaced_peer_may_be_renominated() {
6984        let obs = Arc::new(FirstAuditObservability::default());
6985        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
6986        let total = FIRST_AUDIT_PENDING_CAP + 1;
6987
6988        for i in 0..total {
6989            let b = u8::try_from(i + 1).expect("test peer count fits u8");
6990            scheduler.enqueue(live_nomination(b), &obs);
6991        }
6992        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
6993        // Find whichever peer the random displacement removed.
6994        let displaced = (1..=total)
6995            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
6996            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
6997            .expect("exactly one admitted peer was displaced");
6998
6999        scheduler.enqueue(live_nomination(displaced), &obs);
7000
7001        assert!(
7002            scheduler.pending.peek(&test_peer(displaced)).is_some(),
7003            "the displaced peer re-enters the sample"
7004        );
7005        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
7006        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
7007        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
7008        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
7009    }
7010
7011    /// The periodic sweep collects expired pending entries even when the token
7012    /// bucket is empty — the reserve path returns at the budget gate and never
7013    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
7014    /// honest under fleet-wide starvation.
7015    #[test]
7016    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
7017        let obs = Arc::new(FirstAuditObservability::default());
7018        let mono = Instant::now();
7019        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7020
7021        let dead_quote = SystemTime::now()
7022            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
7023            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
7024            .expect("past wall time");
7025        scheduler.enqueue(
7026            MonetizedPinEvent {
7027                peer: test_peer(1),
7028                pin: [1; 32],
7029                key_count: 100,
7030                quote_ts: dead_quote,
7031            },
7032            &obs,
7033        );
7034        scheduler.enqueue(
7035            MonetizedPinEvent {
7036                peer: test_peer(2),
7037                pin: [2; 32],
7038                key_count: 100,
7039                quote_ts: SystemTime::now(),
7040            },
7041            &obs,
7042        );
7043        assert_eq!(scheduler.pending_len(), 2);
7044
7045        // Empty the bucket so the reserve path is budget-gated (fleet-wide
7046        // starvation) and cannot collect the dead entry itself.
7047        scheduler.limiter.tokens = 0;
7048        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
7049        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
7050        assert_eq!(
7051            scheduler.pending_len(),
7052            2,
7053            "budget-gated reserve scans nothing"
7054        );
7055
7056        let wall_now = SystemTime::now();
7057        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
7058        assert_eq!(scheduler.pending_len(), 1);
7059        assert!(
7060            scheduler.pending.peek(&test_peer(2)).is_some(),
7061            "the live entry survives the sweep"
7062        );
7063        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
7064        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
7065        assert!(
7066            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
7067            "the age gauge reflects only live work after the sweep"
7068        );
7069    }
7070
7071    #[test]
7072    #[allow(clippy::too_many_lines)]
7073    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
7074        let obs = Arc::new(FirstAuditObservability::default());
7075        let mono = Instant::now();
7076        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7077
7078        // A pre-existing window sentinel for an UNRELATED peer must survive the
7079        // cancel byte-for-byte (cancel never touches `recent`).
7080        let sentinel_peer = test_peer(0xAA);
7081        scheduler.limiter.promote(sentinel_peer, 500, mono);
7082        let sentinel_before = scheduler
7083            .limiter
7084            .recent
7085            .peek(&sentinel_peer)
7086            .copied()
7087            .expect("sentinel present");
7088
7089        let peer = test_peer(1);
7090        let a = MonetizedPinEvent {
7091            peer,
7092            pin: [1; 32],
7093            key_count: 100,
7094            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
7095        };
7096        scheduler.enqueue(a, &obs);
7097
7098        let tokens_before = scheduler.tokens();
7099        let lane_before = scheduler.oldest_first_lane;
7100        let launched_before = obs.launched.load(Ordering::Relaxed);
7101        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7102
7103        // Reserve A (jitter 0 so it is immediately due).
7104        let inflight0 = obs.inflight.load(Ordering::Relaxed);
7105        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
7106        assert_eq!(scheduler.reserved_peer(), Some(peer));
7107        assert_eq!(
7108            scheduler.tokens(),
7109            tokens_before - 1,
7110            "reserve consumes a token"
7111        );
7112        assert_eq!(
7113            obs.inflight.load(Ordering::Relaxed),
7114            1,
7115            "reserve holds a slot"
7116        );
7117
7118        // A same-peer, same-count successor arrives DURING the reservation. It
7119        // must be retained (bypasses the window for the reserved peer) and must
7120        // NOT create a second reservation.
7121        let b = MonetizedPinEvent {
7122            peer,
7123            pin: [2; 32],
7124            key_count: 100,
7125            quote_ts: SystemTime::now(),
7126        };
7127        scheduler.enqueue(b, &obs);
7128        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
7129        assert!(
7130            !scheduler.try_reserve(
7131                mono,
7132                obs.inflight.load(Ordering::Relaxed),
7133                Duration::ZERO,
7134                &cooldown,
7135                &obs
7136            ),
7137            "no second reservation while one is outstanding"
7138        );
7139
7140        // Resolve A with an injected wall time PAST A's answerability cutoff.
7141        let reservation = scheduler
7142            .take_due_reservation(mono)
7143            .expect("A is due at jitter 0");
7144        let wall_fail = a
7145            .quote_ts
7146            .checked_add(GOSSIP_ANSWERABILITY_TTL)
7147            .and_then(|t| t.checked_add(Duration::from_secs(1)))
7148            .expect("past-cutoff wall time");
7149        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
7150        assert!(
7151            promoted.is_none(),
7152            "answerability lapsed -> cancelled, not promoted"
7153        );
7154
7155        // State-neutral cancel.
7156        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
7157        assert!(
7158            scheduler.limiter.recent.peek(&peer).is_none(),
7159            "cancel stamps no per-peer window"
7160        );
7161        assert_eq!(
7162            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
7163            Some(sentinel_before),
7164            "unrelated window sentinel untouched"
7165        );
7166        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
7167        assert_eq!(
7168            scheduler.tokens(),
7169            tokens_before,
7170            "token refunded on cancel"
7171        );
7172        assert_eq!(
7173            obs.inflight.load(Ordering::Relaxed),
7174            0,
7175            "in-flight slot released"
7176        );
7177        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
7178        assert_eq!(
7179            obs.launched.load(Ordering::Relaxed),
7180            launched_before,
7181            "no launch counted"
7182        );
7183        assert_eq!(
7184            obs.outside_answerability_window.load(Ordering::Relaxed),
7185            1,
7186            "the cancel reason is recorded"
7187        );
7188
7189        // The successor is still pending and is now fully schedulable: a fresh
7190        // reserve makes B the next reservation (proving eligibility, not merely
7191        // that the limiter would admit it).
7192        assert_eq!(
7193            scheduler.pending_len(),
7194            1,
7195            "successor still pending after cancel"
7196        );
7197        assert!(scheduler.reserved.is_none());
7198        assert!(scheduler.try_reserve(
7199            mono,
7200            obs.inflight.load(Ordering::Relaxed),
7201            Duration::ZERO,
7202            &cooldown,
7203            &obs
7204        ));
7205        assert_eq!(
7206            scheduler.reserved_peer(),
7207            Some(peer),
7208            "the retained successor becomes the next reservation"
7209        );
7210    }
7211
7212    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
7213    /// race, the reserved event is requeued ONLY if no same-peer successor is
7214    /// already pending. A successor arrived after the reservation, so it is the
7215    /// newer nomination (e.g. a count jump) and must not be overwritten by the
7216    /// older reserved event.
7217    #[test]
7218    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
7219        let obs = Arc::new(FirstAuditObservability::default());
7220        let mono = Instant::now();
7221        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7222        let peer = test_peer(1);
7223
7224        // Reserve A.
7225        let a = MonetizedPinEvent {
7226            peer,
7227            pin: [1; 32],
7228            key_count: 100,
7229            quote_ts: SystemTime::now(),
7230        };
7231        scheduler.enqueue(a, &obs);
7232        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
7233        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
7234
7235        // A newer same-peer successor B (a count jump) arrives during the
7236        // reservation and is retained.
7237        let b = MonetizedPinEvent {
7238            peer,
7239            pin: [2; 32],
7240            key_count: 400,
7241            quote_ts: SystemTime::now(),
7242        };
7243        scheduler.enqueue(b, &obs);
7244        assert_eq!(scheduler.pending_len(), 1);
7245
7246        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
7247        // is already stamped for the peer, so promotion loses the race.
7248        let reservation = scheduler.take_due_reservation(mono).expect("due");
7249        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7250        cooldown.insert(peer, mono); // freshly on cooldown
7251        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
7252        assert!(promoted.is_none(), "cooldown race -> not promoted");
7253
7254        // B (newer) is preserved; A did NOT overwrite it.
7255        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
7256        assert_eq!(
7257            scheduler.pending.peek(&peer).map(|e| e.pin),
7258            Some([2; 32]),
7259            "the newer successor B is retained, not the older reserved A"
7260        );
7261        assert!(scheduler.first_audited.is_empty());
7262        assert!(scheduler.limiter.recent.peek(&peer).is_none());
7263    }
7264
7265    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
7266    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
7267    /// and saturates to `0` for a future-dated quote (clock skew) without
7268    /// panicking. A climbing value is the pending-work-aging-out signal.
7269    #[test]
7270    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
7271        let now = SystemTime::now();
7272        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
7273        assert_eq!(
7274            scheduler.oldest_pending_quote_age_ms(now),
7275            0,
7276            "empty pending -> zero"
7277        );
7278
7279        // Two peers: quotes 10s and 2s old. The gauge must track the older.
7280        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
7281            let _ = coalesce_first_audit_event(
7282                &mut scheduler.pending,
7283                MonetizedPinEvent {
7284                    peer: test_peer(peer_id),
7285                    pin,
7286                    key_count: 100,
7287                    quote_ts: now - Duration::from_secs(secs),
7288                },
7289                true,
7290                &mut scheduler.rng,
7291            );
7292        }
7293        assert_eq!(
7294            scheduler.oldest_pending_quote_age_ms(now),
7295            10_000,
7296            "tracks the oldest (10s), not the newest (2s)"
7297        );
7298
7299        // A future-dated quote (clock skew) saturates to zero, never panics.
7300        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
7301        let _ = coalesce_first_audit_event(
7302            &mut skewed.pending,
7303            MonetizedPinEvent {
7304                peer: test_peer(3),
7305                pin: [3; 32],
7306                key_count: 100,
7307                quote_ts: now + Duration::from_secs(5),
7308            },
7309            true,
7310            &mut skewed.rng,
7311        );
7312        assert_eq!(
7313            skewed.oldest_pending_quote_age_ms(now),
7314            0,
7315            "future quote_ts saturates to zero"
7316        );
7317    }
7318
7319    /// A flood of strictly-lower-count same-peer nominations must neither
7320    /// displace the retained higher pin NOR disturb its recency position (each
7321    /// is suppressed via `peek`, no `push`), and each must be counted as
7322    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
7323    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
7324    /// (the documented `lru` contract that also drives the reserve scan's lane
7325    /// ordering), deliberately independent of the overflow policy: eviction is
7326    /// random-victim, so no assertion may require a particular peer to be
7327    /// displaced.
7328    #[test]
7329    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
7330        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
7331            LruCache::new(NonZeroUsize::new(2).unwrap());
7332        let mut rng = StdRng::seed_from_u64(11);
7333        let victim = test_peer(1);
7334        let other = test_peer(2);
7335        // Victim (high count) inserted first (older), then `other` (newer/MRU).
7336        let _ = coalesce_first_audit_event(
7337            &mut pending,
7338            MonetizedPinEvent {
7339                peer: victim,
7340                pin: [1; 32],
7341                key_count: 400,
7342                quote_ts: SystemTime::now(),
7343            },
7344            true,
7345            &mut rng,
7346        );
7347        let _ = coalesce_first_audit_event(
7348            &mut pending,
7349            MonetizedPinEvent {
7350                peer: other,
7351                pin: [9; 32],
7352                key_count: 100,
7353                quote_ts: SystemTime::now(),
7354            },
7355            true,
7356            &mut rng,
7357        );
7358        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
7359        assert_eq!(
7360            order_before,
7361            vec![other, victim],
7362            "sanity: `other` is MRU, the victim is LRU"
7363        );
7364
7365        // Flood the victim with cheaper nominations.
7366        let mut suppressed = 0u64;
7367        for i in 0..8u8 {
7368            let out = coalesce_first_audit_event(
7369                &mut pending,
7370                MonetizedPinEvent {
7371                    peer: victim,
7372                    pin: [i; 32],
7373                    key_count: 50,
7374                    quote_ts: SystemTime::now(),
7375                },
7376                true,
7377                &mut rng,
7378            );
7379            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
7380            suppressed += 1;
7381        }
7382        assert_eq!(suppressed, 8);
7383        // Victim pin/count unchanged.
7384        assert_eq!(
7385            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
7386            Some(([1; 32], 400))
7387        );
7388        // Recency untouched: the iteration order (which the reserve lanes
7389        // consume) is byte-for-byte what it was before the flood.
7390        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
7391        assert_eq!(
7392            order_after, order_before,
7393            "the suppressed-lower flood must not have changed any recency position"
7394        );
7395    }
7396
7397    /// The cooldown-race requeue counts a genuine different-peer capacity
7398    /// eviction (the ADR promises capacity loss is observable).
7399    #[test]
7400    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
7401        let obs = Arc::new(FirstAuditObservability::default());
7402        let mono = Instant::now();
7403        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7404        // Pending capacity 1 so a requeue of a different peer must evict.
7405        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
7406        let reserved_peer = test_peer(1);
7407        let other_peer = test_peer(2);
7408
7409        // Reserve peer 1.
7410        scheduler.enqueue(
7411            MonetizedPinEvent {
7412                peer: reserved_peer,
7413                pin: [1; 32],
7414                key_count: 100,
7415                quote_ts: SystemTime::now(),
7416            },
7417            &obs,
7418        );
7419        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
7420        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
7421
7422        // A DIFFERENT peer fills the single pending slot during the reservation.
7423        scheduler.enqueue(
7424            MonetizedPinEvent {
7425                peer: other_peer,
7426                pin: [2; 32],
7427                key_count: 100,
7428                quote_ts: SystemTime::now(),
7429            },
7430            &obs,
7431        );
7432        assert_eq!(scheduler.pending_len(), 1);
7433
7434        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
7435        let reservation = scheduler.take_due_reservation(mono).expect("due");
7436        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7437        cooldown.insert(reserved_peer, mono);
7438        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
7439        assert!(scheduler
7440            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
7441            .is_none());
7442        assert_eq!(
7443            obs.capacity_evicted.load(Ordering::Relaxed),
7444            cap_before + 1,
7445            "the requeue eviction of a different peer is counted"
7446        );
7447        assert_eq!(
7448            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
7449            Some([1; 32])
7450        );
7451    }
7452
7453    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
7454    /// nomination arriving while an inflated pin is PENDING must not displace it.
7455    /// The inflated pin stays and is the one launched.
7456    #[test]
7457    fn first_audit_pending_lower_count_does_not_replace_higher() {
7458        let obs = Arc::new(FirstAuditObservability::default());
7459        let mono = Instant::now();
7460        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7461        let peer = test_peer(1);
7462
7463        // Inflated (high-count) sidecar pin lands in pending.
7464        scheduler.enqueue(
7465            MonetizedPinEvent {
7466                peer,
7467                pin: [1; 32],
7468                key_count: 400,
7469                quote_ts: SystemTime::now(),
7470            },
7471            &obs,
7472        );
7473        // A cheaper same-peer settlement arrives right after.
7474        scheduler.enqueue(
7475            MonetizedPinEvent {
7476                peer,
7477                pin: [2; 32],
7478                key_count: 100,
7479                quote_ts: SystemTime::now(),
7480            },
7481            &obs,
7482        );
7483
7484        assert_eq!(scheduler.pending_len(), 1);
7485        assert_eq!(
7486            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
7487            Some(([1; 32], 400)),
7488            "the inflated pin must not be erased by the cheaper successor"
7489        );
7490        // The dropped cheaper nomination is counted through the enqueue path.
7491        assert_eq!(
7492            obs.suppressed_lower.load(Ordering::Relaxed),
7493            1,
7494            "the attempted cheaper-pin self-erasure is observable"
7495        );
7496
7497        // It reserves and promotes as the inflated pin/count.
7498        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
7499        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
7500        let reservation = scheduler.take_due_reservation(mono).expect("due");
7501        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7502        let (event, _slot) = scheduler
7503            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
7504            .expect("promotes");
7505        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
7506    }
7507
7508    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
7509    /// loses the cooldown race must be requeued OVER a lower-count same-peer
7510    /// successor that arrived during its jitter, and must remain launchable once
7511    /// the shared cooldown expires — the cheaper successor cannot suppress it.
7512    #[test]
7513    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
7514        let obs = Arc::new(FirstAuditObservability::default());
7515        let mono = Instant::now();
7516        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7517        let peer = test_peer(1);
7518
7519        // Reserve the inflated pin.
7520        scheduler.enqueue(
7521            MonetizedPinEvent {
7522                peer,
7523                pin: [1; 32],
7524                key_count: 400,
7525                quote_ts: SystemTime::now(),
7526            },
7527            &obs,
7528        );
7529        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
7530        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
7531
7532        // A cheaper successor arrives during the reservation (bypasses the
7533        // window as the reserved peer) and sits in pending.
7534        scheduler.enqueue(
7535            MonetizedPinEvent {
7536                peer,
7537                pin: [2; 32],
7538                key_count: 100,
7539                quote_ts: SystemTime::now(),
7540            },
7541            &obs,
7542        );
7543        assert_eq!(scheduler.pending_len(), 1);
7544
7545        // Resolve: answerability passes but the shared cooldown is already
7546        // stamped, so the reservation loses the race and requeues.
7547        let reservation = scheduler.take_due_reservation(mono).expect("due");
7548        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7549        cooldown.insert(peer, mono);
7550        assert!(scheduler
7551            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
7552            .is_none());
7553
7554        // The inflated pin (400) replaced the cheaper successor (100).
7555        assert_eq!(scheduler.pending_len(), 1);
7556        assert_eq!(
7557            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
7558            Some(([1; 32], 400)),
7559            "the inflated reserved pin must survive the requeue over the cheaper successor"
7560        );
7561        assert!(scheduler.first_audited.is_empty());
7562        assert!(scheduler.limiter.recent.peek(&peer).is_none());
7563
7564        // Once the shared cooldown expires, the inflated pin reserves and
7565        // promotes with its intended pin/count.
7566        let later = mono
7567            .checked_add(Duration::from_secs(
7568                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
7569            ))
7570            .expect("later");
7571        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
7572        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
7573        let reservation = scheduler.take_due_reservation(later).expect("due");
7574        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
7575        let (event, _slot) = scheduler
7576            .resolve(
7577                reservation,
7578                SystemTime::now(),
7579                later,
7580                &mut cooldown_later,
7581                &obs,
7582            )
7583            .expect("promotes after cooldown");
7584        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
7585    }
7586
7587    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
7588    /// launch lane, driven through the real scheduler (reserve -> resolve ->
7589    /// promote), so a stream of fresh nominations cannot keep every launch on
7590    /// the newest lane and starve the oldest.
7591    #[test]
7592    fn first_audit_lane_alternates_across_promotions() {
7593        let obs = Arc::new(FirstAuditObservability::default());
7594        let mono = Instant::now();
7595        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
7596        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
7597
7598        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
7599        let oldest_peer = test_peer(1);
7600        let newest_peer = test_peer(2);
7601        scheduler.enqueue(
7602            MonetizedPinEvent {
7603                peer: oldest_peer,
7604                pin: [1; 32],
7605                key_count: 100,
7606                quote_ts: SystemTime::now(),
7607            },
7608            &obs,
7609        );
7610        scheduler.enqueue(
7611            MonetizedPinEvent {
7612                peer: newest_peer,
7613                pin: [2; 32],
7614                key_count: 100,
7615                quote_ts: SystemTime::now(),
7616            },
7617            &obs,
7618        );
7619
7620        let mut launched_peers = Vec::new();
7621        for _ in 0..2 {
7622            assert!(scheduler.try_reserve(
7623                mono,
7624                obs.inflight.load(Ordering::Relaxed),
7625                Duration::ZERO,
7626                &cooldown,
7627                &obs
7628            ));
7629            let reservation = scheduler.take_due_reservation(mono).expect("due");
7630            // Answerable wall time == the quote's own time (age 0).
7631            let (event, _slot) = scheduler
7632                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
7633                .expect("fresh in-window quote promotes");
7634            launched_peers.push(event.peer);
7635        }
7636
7637        // First launch takes the newest lane (lane starts false = newest), the
7638        // second takes the oldest lane: strict alternation.
7639        assert_eq!(
7640            launched_peers,
7641            vec![newest_peer, oldest_peer],
7642            "consecutive promotions alternate newest-then-oldest lane"
7643        );
7644    }
7645
7646    #[test]
7647    fn first_audit_count_jump_boundaries() {
7648        // Exactly 1.5x is NOT a jump; strictly above is.
7649        assert!(!first_audit_count_jump(100, 150));
7650        assert!(first_audit_count_jump(100, 151));
7651        // Anything beats an audited zero; zero never jumps.
7652        assert!(first_audit_count_jump(0, 1));
7653        assert!(!first_audit_count_jump(0, 0));
7654        // Equal max counts must not jump (and must not overflow).
7655        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
7656    }
7657
7658    /// A verified payment's quote list includes the local node's own quote, so
7659    /// the verifier emits a monetized-pin event for the local peer on every
7660    /// payment it verifies. The node cannot network-audit itself, so the
7661    /// scheduler must drop such an event at ingress: never queued, and hence
7662    /// never launched nor marked first-audited.
7663    #[test]
7664    fn first_audit_queue_drops_self_targeting_events() {
7665        let obs = Arc::new(FirstAuditObservability::default());
7666        let self_peer = test_peer(1);
7667        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
7668        let self_event = MonetizedPinEvent {
7669            peer: self_peer,
7670            pin: [7; 32],
7671            key_count: 1,
7672            quote_ts: SystemTime::now(),
7673        };
7674
7675        scheduler.enqueue(self_event, &obs);
7676        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
7677        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
7678        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
7679
7680        // A remote peer's event still queues normally under the same filter.
7681        let remote_event = MonetizedPinEvent {
7682            peer: test_peer(2),
7683            pin: [8; 32],
7684            ..self_event
7685        };
7686        scheduler.enqueue(remote_event, &obs);
7687        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
7688        assert_eq!(scheduler.pending_len(), 1);
7689        assert_eq!(
7690            obs.self_target_skipped.load(Ordering::Relaxed),
7691            1,
7692            "remote event must not count as a self-target skip"
7693        );
7694    }
7695
7696    #[test]
7697    fn fresh_offer_runs_store_admission_payment_checks() {
7698        let context = fresh_offer_payment_context();
7699        assert_eq!(context, VerificationContext::FreshReplication);
7700        // Fresh replication must keep verifying exactly like a direct client
7701        // PUT (store-strength cache, same live checks); the variant only
7702        // exists so price-floor telemetry can tell the two paths apart.
7703        assert!(context.is_store_admission());
7704    }
7705
7706    #[test]
7707    fn paid_notify_uses_paid_list_admission_payment_checks() {
7708        assert_eq!(
7709            paid_notify_payment_context(),
7710            VerificationContext::PaidListAdmission
7711        );
7712    }
7713
7714    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
7715    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
7716    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
7717    #[test]
7718    fn monetized_quote_audit_window_fails_closed_both_ends() {
7719        let now = SystemTime::now();
7720        // Fresh (just quoted) and small future/past skew -> audited.
7721        assert!(quote_within_audit_window(now, now));
7722        assert!(quote_within_audit_window(
7723            now + Duration::from_secs(60),
7724            now
7725        ));
7726        assert!(quote_within_audit_window(
7727            now - Duration::from_secs(3600),
7728            now
7729        ));
7730        // Far future (badly-skewed / replayed) -> skipped.
7731        assert!(!quote_within_audit_window(
7732            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
7733            now
7734        ));
7735        // Older than the window -> skipped (pin may have aged out).
7736        assert!(!quote_within_audit_window(
7737            now - GOSSIP_ANSWERABILITY_TTL,
7738            now
7739        ));
7740    }
7741
7742    #[test]
7743    fn audit_timeout_preserves_active_bootstrap_claim() {
7744        assert!(!audit_failure_clears_bootstrap_claim(
7745            &AuditFailureReason::Timeout
7746        ));
7747    }
7748
7749    fn strike_peer(b: u8) -> PeerId {
7750        let mut bytes = [0u8; 32];
7751        bytes[0] = b;
7752        PeerId::from_bytes(bytes)
7753    }
7754
7755    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
7756    // cooldown must collapse a gossip flood into at most one audit per window.
7757
7758    #[test]
7759    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
7760        let peer = strike_peer(1);
7761        let mut map: HashMap<PeerId, Instant> = HashMap::new();
7762        let t0 = Instant::now();
7763        // First gossip in the window passes; a burst of further gossips at the
7764        // same instant are all suppressed.
7765        assert!(cooldown_allows_audit(&mut map, &peer, t0));
7766        let mut passed = 1;
7767        for _ in 0..100 {
7768            if cooldown_allows_audit(&mut map, &peer, t0) {
7769                passed += 1;
7770            }
7771        }
7772        assert_eq!(
7773            passed, 1,
7774            "a flood at one instant must trigger exactly one audit"
7775        );
7776    }
7777
7778    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
7779    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
7780    // consumes the window. This is the property the isolated cooldown tests above
7781    // cannot see: they never sample the lottery, so a regression that reordered
7782    // the gates (sample probability first, only stamp the cooldown on a win)
7783    // would still pass them while breaking flood-resistance: a flood would then
7784    // re-roll the lottery on EVERY message until one won, multiplying audits.
7785    //
7786    // We model the exact production gate order (attempt-window, lottery,
7787    // shared cooldown) with a lottery driven by a fixed outcome instead of
7788    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
7789    // messages all WIN. With the production order, the losing first ticket
7790    // burns the ATTEMPT window and every later winner in the same window is
7791    // blocked, so there are 0 audits this window. If the gates were flipped,
7792    // the second message's winning ticket would slip through. The window only
7793    // reopens after it elapses.
7794    //
7795    // FLIPS IF: the lottery is sampled before the attempt-window
7796    // check-and-stamp (a losing ticket no longer consumes the window),
7797    // re-enabling a flood-amplified audit storm.
7798    #[test]
7799    fn losing_lottery_still_consumes_attempt_window() {
7800        // Calls the SHIPPED `audit_launch_decision` (the same function
7801        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
7802        // production fails this test — not a local reimplementation.
7803        let peer = strike_peer(3);
7804        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
7805        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
7806        let t0 = Instant::now();
7807
7808        // First flooded message at t0 LOSES the lottery, but the attempt window
7809        // is stamped BEFORE the lottery is consulted, so the window is consumed.
7810        assert!(
7811            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
7812            "a losing ticket launches no audit"
7813        );
7814
7815        // 99 more flooded messages at the same instant would all WIN the lottery,
7816        // yet every one must be blocked by the attempt window the loser stamped.
7817        // (If production sampled the lottery FIRST, these would each get a fresh
7818        // roll and audits would multiply — this assertion catches that reorder.)
7819        let mut audits = 0;
7820        for _ in 0..99 {
7821            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
7822                audits += 1;
7823            }
7824        }
7825        assert_eq!(
7826            audits, 0,
7827            "a losing first ticket must consume the attempt window so no later \
7828             flooded message in the same window can audit"
7829        );
7830
7831        // The window only reopens after it elapses; the next winning ticket
7832        // then launches exactly one audit and stamps the SHARED cooldown.
7833        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
7834        assert!(
7835            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
7836            "after the window a winning ticket audits again"
7837        );
7838        assert!(
7839            launched.contains_key(&peer),
7840            "a real launch stamps the shared cooldown"
7841        );
7842    }
7843
7844    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
7845    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
7846    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
7847    /// first audit deferred until its answerability window expires.
7848    ///
7849    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
7850    /// loss (the pre-split behavior, where both paths shared one map).
7851    #[test]
7852    fn losing_lottery_does_not_suppress_monetized_first_audit() {
7853        let peer = strike_peer(4);
7854        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
7855        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
7856        let t0 = Instant::now();
7857
7858        // A losing ticket consumes the gossip attempt window...
7859        assert!(!audit_launch_decision(
7860            &mut attempts,
7861            &mut launched,
7862            &peer,
7863            t0,
7864            false
7865        ));
7866        // ...but leaves the shared map untouched, so the first-audit reserve
7867        // gate (read-only) and the authoritative promotion check-and-stamp both
7868        // still allow the paid audit to launch immediately.
7869        assert!(
7870            cooldown_would_allow(&launched, &peer, t0),
7871            "reserve gate must not see a losing ticket as audit coverage"
7872        );
7873        assert!(
7874            cooldown_allows_audit(&mut launched, &peer, t0),
7875            "promotion must not be deferred by a losing ticket"
7876        );
7877
7878        // Conversely a WINNING ticket (real audit sent) does suppress the
7879        // first audit for the window, which is the intended shared semantics.
7880        let peer_won = strike_peer(5);
7881        assert!(audit_launch_decision(
7882            &mut attempts,
7883            &mut launched,
7884            &peer_won,
7885            t0,
7886            true
7887        ));
7888        assert!(
7889            !cooldown_would_allow(&launched, &peer_won, t0),
7890            "a real gossip audit still covers the peer for the window"
7891        );
7892    }
7893
7894    #[test]
7895    fn cooldown_lets_audit_through_after_the_window() {
7896        let peer = strike_peer(2);
7897        let mut map: HashMap<PeerId, Instant> = HashMap::new();
7898        let t0 = Instant::now();
7899        assert!(cooldown_allows_audit(&mut map, &peer, t0));
7900        // Within the window: suppressed.
7901        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
7902        assert!(!cooldown_allows_audit(&mut map, &peer, within));
7903        // Past the window: allowed again.
7904        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
7905        assert!(cooldown_allows_audit(&mut map, &peer, after));
7906    }
7907
7908    #[test]
7909    fn cooldown_is_per_peer_independent() {
7910        let mut map: HashMap<PeerId, Instant> = HashMap::new();
7911        let t0 = Instant::now();
7912        // Different peers each get their own first-audit pass at the same instant.
7913        for i in 0..20u8 {
7914            assert!(
7915                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
7916                "peer {i} should be auditable independently"
7917            );
7918        }
7919    }
7920
7921    #[test]
7922    fn audit_on_gossip_constants_match_adr() {
7923        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
7924        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
7925        // values above 5 would silently never be requested).
7926        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
7927        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
7928        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
7929    }
7930
7931    // (d) A confirmed storage-integrity failure penalizes immediately and
7932    // revokes credit; it is not a timeout.
7933    #[test]
7934    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
7935        assert!(audit_failure_clears_bootstrap_claim(
7936            &AuditFailureReason::DigestMismatch
7937        ));
7938        assert!(audit_failure_revokes_holder_credit(
7939            &AuditFailureReason::DigestMismatch
7940        ));
7941    }
7942
7943    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
7944    /// uses: confirmed failures revoke credit, `Timeout` does not.
7945    #[test]
7946    fn confirmed_failures_revoke_credit_timeout_does_not() {
7947        for reason in [
7948            AuditFailureReason::MalformedResponse,
7949            AuditFailureReason::DigestMismatch,
7950            AuditFailureReason::KeyAbsent,
7951            AuditFailureReason::Rejected,
7952        ] {
7953            assert!(
7954                audit_failure_revokes_holder_credit(&reason),
7955                "confirmed failure {reason:?} must revoke holder credit"
7956            );
7957        }
7958        assert!(
7959            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
7960            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
7961        );
7962    }
7963
7964    /// Wiring test for the security fix: the helper the handler calls
7965    /// actually strips a credited peer on a confirmed failure
7966    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
7967    /// Records genuine credit first so neither assertion is vacuous;
7968    /// this fails if `forget_peer` stops being called, or if the
7969    /// `Timeout` exclusion is dropped (both verified by mutation).
7970    #[test]
7971    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
7972        let peer = test_peer(0xAB);
7973        let key = test_key(1);
7974        let hash = [0xCD; 32];
7975
7976        // Confirmed failure -> credit revoked.
7977        let mut provers = RecentProvers::new();
7978        provers.record_proof(key, peer, hash, Instant::now());
7979        assert!(
7980            provers.is_credited_holder(&key, &peer, &hash),
7981            "precondition: peer credited before failure"
7982        );
7983        apply_audit_failure_credit_revocation(
7984            &mut provers,
7985            &peer,
7986            &AuditFailureReason::DigestMismatch,
7987        );
7988        assert!(
7989            !provers.is_credited_holder(&key, &peer, &hash),
7990            "DigestMismatch must strip the peer's holder credit"
7991        );
7992
7993        // Timeout -> credit retained.
7994        let mut provers_timeout = RecentProvers::new();
7995        provers_timeout.record_proof(key, peer, hash, Instant::now());
7996        apply_audit_failure_credit_revocation(
7997            &mut provers_timeout,
7998            &peer,
7999            &AuditFailureReason::Timeout,
8000        );
8001        assert!(
8002            provers_timeout.is_credited_holder(&key, &peer, &hash),
8003            "Timeout must retain holder credit (deliberate liveness cushion)"
8004        );
8005    }
8006
8007    #[test]
8008    fn decoded_audit_failures_clear_active_bootstrap_claim() {
8009        for reason in [
8010            AuditFailureReason::MalformedResponse,
8011            AuditFailureReason::DigestMismatch,
8012            AuditFailureReason::KeyAbsent,
8013            AuditFailureReason::Rejected,
8014        ] {
8015            assert!(
8016                audit_failure_clears_bootstrap_claim(&reason),
8017                "decoded non-bootstrap failure {reason:?} should clear active claim"
8018            );
8019        }
8020    }
8021
8022    #[test]
8023    fn first_failed_key_label_truncates_to_16_hex_chars() {
8024        // The high-order 8 bytes of the XorName determine the label so an
8025        // operator can group audit-failures on the same chunk prefix.
8026        let mut key = [0u8; 32];
8027        key[0] = 0x18;
8028        key[7] = 0xff;
8029        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
8030        // to verify they are NOT included in the label.
8031        for byte in &mut key[8..] {
8032            *byte = 0xAA;
8033        }
8034        let label = first_failed_key_label(&[key]);
8035        // Only the first 8 bytes are encoded, low-order bytes are dropped.
8036        assert_eq!(label, "0x18000000000000ff");
8037        assert_eq!(label.len(), "0x".len() + 16);
8038    }
8039
8040    #[test]
8041    fn first_failed_key_label_falls_back_when_empty() {
8042        // Should never happen in production (audit failure handling rejects
8043        // empty sets), but the formatter must still produce a valid label
8044        // so the log line doesn't contain a misleading default.
8045        assert_eq!(first_failed_key_label(&[]), "0x");
8046    }
8047
8048    #[test]
8049    fn first_failed_key_label_uses_first_key_only() {
8050        let first = [0x11u8; 32];
8051        let second = [0x22u8; 32];
8052        assert_eq!(
8053            first_failed_key_label(&[first, second]),
8054            format!("0x{}", hex::encode(&first[..8]))
8055        );
8056    }
8057}