Skip to main content

ant_node/replication/
mod.rs

1//! Replication subsystem for the Autonomi network.
2//!
3//! Implements Kademlia-style replication with:
4//! - Fresh replication with `PoP` verification
5//! - Neighbor sync with round-robin cycle management
6//! - Batched quorum verification
7//! - Storage audit protocol (anti-outsourcing)
8//! - `PaidForList` persistence and convergence
9//! - Responsibility pruning with hysteresis
10
11// The replication engine intentionally holds `RwLock` read guards across await
12// boundaries (e.g. reading sync_history while calling audit_tick). Clippy's
13// nursery lint `significant_drop_tightening` flags these, but the guards must
14// remain live for the duration of the call.
15#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod possession;
29pub mod protocol;
30pub mod pruning;
31pub mod quorum;
32pub mod recent_provers;
33pub mod scheduling;
34pub mod slice;
35pub mod storage_commitment_audit;
36pub mod subtree;
37pub mod types;
38
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::fmt;
41use std::num::NonZeroUsize;
42use std::ops::ControlFlow;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::Arc;
46use std::time::{Duration, Instant, SystemTime};
47
48use lru::LruCache;
49use std::pin::Pin;
50
51use crate::logging::{debug, error, info, warn};
52use futures::stream::FuturesUnordered;
53use futures::{future::join_all, Future, StreamExt};
54use parking_lot::Mutex;
55use rand::rngs::StdRng;
56use rand::{Rng, SeedableRng};
57use tokio::sync::broadcast::error::RecvError;
58use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
59use tokio::task::JoinHandle;
60use tokio_util::sync::CancellationToken;
61use tokio_util::task::TaskTracker;
62
63use crate::ant_protocol::XorName;
64use crate::error::{Error, Result};
65use crate::payment::{
66    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
67    MIN_PAYMENT_PROOF_SIZE_BYTES,
68};
69use crate::replication::audit::AuditTickResult;
70use crate::replication::audit_coordinator::AuditChallengeCoordinator;
71use crate::replication::audit_metrics::{
72    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
73    ReplicationResponderClass, ResponderAdmissionCeiling,
74};
75use crate::replication::commitment::{commitment_hash, StorageCommitment};
76use crate::replication::commitment_state::{
77    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
78};
79use crate::replication::config::{
80    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
81    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
82    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
83    MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
84    REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
85    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
86};
87use crate::replication::paid_list::PaidList;
88use crate::replication::protocol::{
89    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
90    VerificationResponse,
91};
92use crate::replication::quorum::KeyVerificationOutcome;
93use crate::replication::recent_provers::RecentProvers;
94use crate::replication::scheduling::{CapacityDisplacement, ReplicationQueues};
95use crate::replication::types::{
96    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98    VerificationState,
99};
100use crate::storage::LmdbStorage;
101use saorsa_core::identity::{NodeIdentity, PeerId};
102use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
103use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
104
105/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
106/// because it was full (Amendment 2). Process-global because the producer is
107/// the payment verifier (a different module) and the drop happens before the
108/// per-drainer `received` counter. A non-zero value is the rollout signal that
109/// nomination ingress is saturating — benign (penalty-free, lottery/next-
110/// payment covered) but worth watching. `Closed` (engine shut down) is not
111/// counted: it is not a saturation signal.
112static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
113
114/// Record one ingress-full drop. Called by the payment verifier's `try_send`
115/// sites; read by the drainer's periodic summary.
116pub(crate) fn note_monetized_ingress_drop() {
117    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
118}
119
120#[derive(Default)]
121struct FirstAuditObservability {
122    received: AtomicU64,
123    queued: AtomicU64,
124    coalesced: AtomicU64,
125    duplicates: AtomicU64,
126    capacity_evicted: AtomicU64,
127    /// An event targeting the local peer itself, dropped at ingress: the node
128    /// cannot network-audit itself (no dialable address for the local peer).
129    self_target_skipped: AtomicU64,
130    /// A strictly-lower-count same-peer nomination that was dropped so a
131    /// higher-count pending pin survived. A sustained rise is the signal of an
132    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
133    suppressed_lower: AtomicU64,
134    cooldown_deferred_attempts: AtomicU64,
135    rate_deferred_attempts: AtomicU64,
136    window_deduped: AtomicU64,
137    launched: AtomicU64,
138    passed: AtomicU64,
139    timed_out: AtomicU64,
140    failed: AtomicU64,
141    bootstrap_claims: AtomicU64,
142    idle: AtomicU64,
143    insufficient_keys: AtomicU64,
144    outside_answerability_window: AtomicU64,
145    inflight: AtomicU64,
146}
147
148/// Test-only snapshot of the first-audit scheduler counters.
149///
150/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
151/// self-targeting monetized pin was dropped and never launched) instead of
152/// scraping log lines.
153#[cfg(any(test, feature = "test-utils"))]
154#[derive(Debug, Clone, Copy)]
155pub struct FirstAuditStats {
156    /// Events ingested from the monetized-pin channel.
157    pub received: u64,
158    /// Events accepted into the pending first-audit queue.
159    pub queued: u64,
160    /// Events dropped because they targeted the local peer.
161    pub self_target_skipped: u64,
162    /// Audits launched.
163    pub launched: u64,
164    /// Launched audits that passed.
165    pub passed: u64,
166    /// Launched audits that timed out (non-response lane).
167    pub timed_out: u64,
168    /// Launched audits that ended in a confirmed failure.
169    pub failed: u64,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum FirstAuditTerminalOutcome {
174    Passed,
175    Timeout,
176    Failed,
177    BootstrapClaim,
178    Idle,
179    InsufficientKeys,
180}
181
182impl FirstAuditTerminalOutcome {
183    #[cfg(any(feature = "logging", test))]
184    const fn as_str(self) -> &'static str {
185        match self {
186            Self::Passed => "passed",
187            Self::Timeout => "timeout",
188            Self::Failed => "failed",
189            Self::BootstrapClaim => "bootstrap_claim",
190            Self::Idle => "idle",
191            Self::InsufficientKeys => "insufficient_keys",
192        }
193    }
194}
195
196fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
197    match result {
198        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
199        AuditTickResult::Failed {
200            evidence:
201                FailureEvidence::AuditFailure {
202                    reason: AuditFailureReason::Timeout,
203                    ..
204                },
205            ..
206        } => FirstAuditTerminalOutcome::Timeout,
207        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
208        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
209        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
210        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
211    }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum FirstAuditQueueOutcome {
216    /// New peer inserted with free capacity.
217    Queued,
218    /// Collapsed with an existing same-peer entry; the incoming won (higher
219    /// count, or equal count and newer) and replaced it.
220    Coalesced,
221    /// Collapsed with an existing same-peer entry; the incoming LOST because it
222    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
223    /// in place. This is the attempted cheaper-pin self-erasure signal.
224    SuppressedLower,
225    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
226    /// lost the freshness tie (it was not the newer of the two) and the
227    /// existing entry was retained. Benign, not an attack signal.
228    RetainedOnTie,
229    /// A DIFFERENT peer's entry was displaced from the capped pending queue
230    /// (random victim) to make room.
231    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
232}
233
234/// Coalesce a monetized nomination into the per-peer pending queue with a
235/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
236/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
237///
238/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
239/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
240/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
241/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
242/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
243/// cannot promote the retained pin's lane position.
244///
245/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
246/// last, so it wins an equal-count tie for freshness) from a cooldown-race
247/// requeue of an older reserved event (the pending successor is newer, so it
248/// wins the tie).
249fn coalesce_first_audit_event(
250    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
251    incoming: MonetizedPinEvent,
252    incoming_is_newer: bool,
253    rng: &mut StdRng,
254) -> FirstAuditQueueOutcome {
255    if let Some(existing) = pending.peek(&incoming.peer) {
256        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
257        // the retained pin's recency (the security-relevant self-erasure case).
258        if incoming.key_count < existing.key_count {
259            return FirstAuditQueueOutcome::SuppressedLower;
260        }
261        // Equal count -> keep the fresher; an older incoming loses a benign tie.
262        if incoming.key_count == existing.key_count && !incoming_is_newer {
263            return FirstAuditQueueOutcome::RetainedOnTie;
264        }
265        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
266        // the value and bumps MRU; replacing an existing key never evicts a
267        // different peer.
268        let _ = pending.push(incoming.peer, incoming);
269        return FirstAuditQueueOutcome::Coalesced;
270    }
271    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
272    // never the LRU: deterministic keep-newest would let an ordered batch of
273    // `cap` distinct-peer nominations flush a chosen target before any launch
274    // lane sees it, cutting the eviction cost from probabilistic to exact. A
275    // random victim caps an attacker's per-nomination eviction probability at
276    // `1/cap` regardless of arrival order or timing, so suppressing a specific
277    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
278    // nominations and is never certain (ADR-0004 Amendment 4).
279    if pending.len() >= pending.cap().get() {
280        let victim = {
281            let idx = rng.gen_range(0..pending.len());
282            pending.iter().nth(idx).map(|(p, _)| *p)
283        };
284        if let Some(victim_peer) = victim {
285            if let Some(evicted) = pending.pop(&victim_peer) {
286                let _ = pending.push(incoming.peer, incoming);
287                return FirstAuditQueueOutcome::CapacityEvicted {
288                    peer: victim_peer,
289                    pin: evicted.pin,
290                };
291            }
292        }
293    }
294    match pending.push(incoming.peer, incoming) {
295        None => FirstAuditQueueOutcome::Queued,
296        // Unreachable: the random-displacement branch above guarantees
297        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
298        // exists). Kept so any future logic error surfaces as an ACCOUNTED
299        // eviction rather than silent loss — but note this arm would be
300        // LRU-order, not random, so it must stay unreachable.
301        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
302            peer: evicted_peer,
303            pin: evicted.pin,
304        },
305    }
306}
307
308/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
309/// prefiltering a nomination's answerability at schedule time, covering the
310/// spawn/dispatch latency between the timer firing and the wire challenge so a
311/// jitter==MAX pin is not admitted only to fail the authoritative check by a
312/// few milliseconds. Tiny against the multi-hour answerability window.
313const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
314
315/// A first audit the limiter recently launched at a peer: when, and the
316/// committed key count that was audited (for the count-jump override).
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318struct RecentFirstAudit {
319    launched_at: Instant,
320    key_count: u32,
321}
322
323/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
324/// panicking or cancelled audit task can never leak a slot and wedge the
325/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
326struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
327
328impl FirstAuditInflightSlot {
329    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
330        observability.inflight.fetch_add(1, Ordering::Relaxed);
331        Self(Arc::clone(observability))
332    }
333}
334
335impl Drop for FirstAuditInflightSlot {
336    fn drop(&mut self) {
337        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
338    }
339}
340
341/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
342/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
343/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
344/// overflow-free integer math). A jump re-nominates a peer despite a recent
345/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
346/// only, so no gossip-lottery audit can ever cover it.
347const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
348    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
349        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
350}
351
352/// The launch limiter's verdict for one pending monetized pin.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum LimiterVerdict {
355    /// Within budget and window: the caller may reserve a launch (and consumes
356    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
357    Admit,
358    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
359    /// pin pending and retry on a later tick.
360    RateDeferred,
361    /// The peer had a first audit within
362    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
363    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
364    /// gossip-lottery re-audit path is unaffected).
365    WindowDeduped,
366}
367
368/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
369/// (launch rate), an in-flight cap, and a per-peer re-audit window that
370/// survives pin rotation.
371///
372/// This is the load-bearing aggregate bound the original scheduler lacked:
373/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
374/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
375/// `now`/`inflight` values so every decision is unit-testable without a
376/// runtime.
377struct FirstAuditLimiter {
378    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
379    tokens: u32,
380    /// Refill anchor. While the bucket is full this tracks `now` (a full
381    /// bucket accrues nothing); while below capacity it advances only by
382    /// whole refill intervals so fractional elapsed time is never lost.
383    last_refill: Instant,
384    /// Peers given a first audit recently, with the audited key count.
385    /// Bounded like the drainer's other per-peer maps.
386    recent: LruCache<PeerId, RecentFirstAudit>,
387}
388
389impl FirstAuditLimiter {
390    fn new(now: Instant) -> Self {
391        Self {
392            tokens: config::FIRST_AUDIT_BUDGET_BURST,
393            last_refill: now,
394            recent: LruCache::new(
395                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
396            ),
397        }
398    }
399
400    /// Whether the per-peer re-audit window admits a nomination for `peer`
401    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
402    /// call at ENQUEUE time — suppressed nominations never occupy pending
403    /// slots — without disturbing LRU recency.
404    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
405        self.recent.peek(peer).map_or(true, |prev| {
406            now.saturating_duration_since(prev.launched_at)
407                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
408                || first_audit_count_jump(prev.key_count, key_count)
409        })
410    }
411
412    /// Refill the token bucket for the time elapsed up to `now`.
413    fn refill(&mut self, now: Instant) {
414        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
415            // Full bucket accrues nothing; keep the anchor current so the
416            // next consumption starts its interval from here.
417            self.last_refill = now;
418            return;
419        }
420        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
421        let elapsed = now.saturating_duration_since(self.last_refill);
422        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
423        if earned == 0 {
424            return;
425        }
426        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
427        if earned >= capacity_gap {
428            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
429            self.last_refill = now;
430        } else {
431            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
432            self.tokens = self
433                .tokens
434                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
435            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
436            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
437        }
438    }
439
440    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
441    /// caller runs the remaining (per-peer cooldown) gate and calls
442    /// [`Self::commit_launch`] only for a launch that actually happens, so a
443    /// deferral elsewhere never burns budget or stamps the window.
444    fn assess(
445        &mut self,
446        peer: &PeerId,
447        key_count: u32,
448        now: Instant,
449        inflight: u64,
450    ) -> LimiterVerdict {
451        if !self.window_allows(peer, key_count, now) {
452            return LimiterVerdict::WindowDeduped;
453        }
454        self.refill(now);
455        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
456            return LimiterVerdict::RateDeferred;
457        }
458        LimiterVerdict::Admit
459    }
460
461    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
462    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
463    /// only at [`Self::promote`], after the authoritative post-jitter
464    /// answerability check, so a reservation that is later cancelled leaves no
465    /// suppression behind.
466    fn reserve_token(&mut self) {
467        self.tokens = self.tokens.saturating_sub(1);
468    }
469
470    /// Return a token consumed by a reservation that was cancelled before it
471    /// launched (answerability lapsed or a concurrent gossip audit won the
472    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
473    /// the bucket.
474    fn refund_token(&mut self) {
475        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
476    }
477
478    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
479    /// (promotion). Separated from token consumption so suppression is only
480    /// ever recorded for a real send.
481    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
482        self.recent.put(
483            peer,
484            RecentFirstAudit {
485                launched_at: now,
486                key_count,
487            },
488        );
489    }
490
491    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
492    /// and stamp the window in one call. Production splits these across
493    /// reservation and promotion; the limiter's own budget/window unit tests do
494    /// not model the jitter reservation and use this shorthand.
495    #[cfg(test)]
496    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
497        self.reserve_token();
498        self.promote(peer, key_count, now);
499    }
500}
501
502/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
503/// across the ENTIRE launch-jitter window ending at
504/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
505/// for it cannot later require aborting an out-of-window challenge. The
506/// too-future bound is enforced at `now` (a jitter delay only ages a pin
507/// forward, never toward the future); the too-old bound is enforced at the
508/// latest possible send time. This is a conservative admission prefilter; the
509/// authoritative answerability check still runs at promotion against the real
510/// send-time wall clock, so A1 (no false conviction) holds regardless of how
511/// jitter and the answerability margin are sized. `checked_add` overflow fails
512/// closed (skip the pin).
513fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
514    let Some(latest_send) = now
515        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
516        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
517    else {
518        return false;
519    };
520    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
521}
522
523/// Open the single first-audit reservation from `pending` if none is
524/// outstanding: samples the launch jitter, snapshots the shared cooldown
525/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
526/// shared implementation for both drainer call sites — the per-wake launch
527/// phase and the pre-overflow opportunity inside the ingress batch — so the
528/// two cannot drift.
529async fn open_first_audit_reservation(
530    scheduler: &mut FirstAuditScheduler,
531    cooldown: &RwLock<HashMap<PeerId, Instant>>,
532    observability: &Arc<FirstAuditObservability>,
533) {
534    if scheduler.has_reservation() {
535        return;
536    }
537    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
538        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
539    ));
540    let inflight = observability.inflight.load(Ordering::Relaxed);
541    let reserved = {
542        let cooldown = cooldown.read().await;
543        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
544    };
545    if reserved {
546        if let Some(peer) = scheduler.reserved_peer() {
547            debug!(
548                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
549                scheduler.pending_len()
550            );
551        }
552    }
553}
554
555/// A far-future `Instant` used to effectively DISABLE the promotion-timer
556/// select arm when no reservation is outstanding. The drainer still wakes at
557/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
558/// needs to be comfortably past the next tick.
559fn first_audit_far_future() -> Instant {
560    Instant::now()
561        .checked_add(Duration::from_secs(3600))
562        .unwrap_or_else(Instant::now)
563}
564
565/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
566/// its in-flight slot and launch token from schedule time until the jitter
567/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
568/// only if the authoritative post-jitter answerability + cooldown checks pass at
569/// promotion, so a cancelled reservation leaves NO suppression behind.
570struct FirstAuditReservation {
571    event: MonetizedPinEvent,
572    ready_at: Instant,
573    inflight: FirstAuditInflightSlot,
574}
575
576/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
577/// pending queue, the dedup set, the launch limiter, the alternating lane, and
578/// the single outstanding reservation. All mutation is single-threaded in the
579/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
580/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
581/// state machine is unit-testable with injected clocks.
582struct FirstAuditScheduler {
583    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
584    /// (a real send), never at reservation, so a cancelled reservation can be
585    /// re-nominated.
586    first_audited: LruCache<[u8; 32], ()>,
587    /// Highest-count-per-peer pending nominations not yet launched. Capped at
588    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
589    /// one effective answerability window); at capacity a uniformly RANDOM
590    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
591    /// of a specific entry can never be forced deterministically. One further
592    /// entry may be held in `reserved` outside this queue — a deliberate
593    /// one-entry guard slot, so total schedulable occupancy is at most
594    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
595    pending: LruCache<PeerId, MonetizedPinEvent>,
596    /// Token bucket + per-peer re-audit window.
597    limiter: FirstAuditLimiter,
598    /// The single outstanding reservation (E′ serializes reservations so the
599    /// per-launch lane alternation is preserved and at most one jitter timer is
600    /// live).
601    reserved: Option<FirstAuditReservation>,
602    /// Alternating launch lane, flipped on every PROMOTION (real launch).
603    oldest_first_lane: bool,
604    /// The local node's own peer ID. A verified payment's quote list includes
605    /// the node's own quote, so the verifier emits a monetized-pin event for
606    /// the local peer on every payment it verifies. The node cannot
607    /// network-audit itself (there is no dialable address for the local peer,
608    /// so the challenge fails instantly and is miscounted as a timeout), while
609    /// any other payee that verifies the same payment schedules its own first
610    /// audit of this node's pin — a self-dial adds no coverage either way.
611    /// Such an event is dropped at ingress: never queued, and hence never
612    /// launched nor marked first-audited.
613    self_peer: PeerId,
614    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
615    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
616    /// production seeds from OS entropy at construction.
617    rng: StdRng,
618}
619
620impl FirstAuditScheduler {
621    fn new(now: Instant, self_peer: PeerId) -> Self {
622        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
623        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
624        Self {
625            first_audited: LruCache::new(dedup_cap),
626            pending: LruCache::new(pending_cap),
627            limiter: FirstAuditLimiter::new(now),
628            reserved: None,
629            oldest_first_lane: false,
630            self_peer,
631            rng: StdRng::from_entropy(),
632        }
633    }
634
635    /// Observability getter: used by the scheduler summary log and unit tests,
636    /// both absent from a release `--no-default-features` build, so it is dead
637    /// only in that configuration.
638    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
639    fn pending_len(&self) -> usize {
640        self.pending.len()
641    }
642
643    /// Observability getter (see [`Self::pending_len`]).
644    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
645    fn tokens(&self) -> u32 {
646        self.limiter.tokens
647    }
648
649    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
650    /// signed quote timestamp of the oldest pin still awaiting a first audit:
651    /// how close the longest-waiting pending pin is to aging out of the
652    /// answerability window. A value climbing toward the window means pending
653    /// work is expiring unaudited instead of launching; a small, steady value
654    /// means the queue is draining promptly. Returns `0` when `pending` is empty
655    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
656    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
657    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
658        self.pending
659            .iter()
660            .map(|(_, e)| e.quote_ts)
661            .min()
662            .and_then(|oldest| now.duration_since(oldest).ok())
663            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
664    }
665
666    /// Drop every pending nomination that has aged past the answerability
667    /// horizon. `try_reserve` collects expired entries only while it can scan —
668    /// under token starvation it returns at the budget gate first — so without
669    /// a periodic sweep dead entries squat the capped pending queue (displacing
670    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
671    /// telemetry. Each removal is accounted as `outside_answerability_window`,
672    /// exactly like a scan-time expiry. Returns how many entries were dropped;
673    /// survivor recency is untouched.
674    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
675        let expired: Vec<PeerId> = self
676            .pending
677            .iter()
678            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
679            .map(|(peer, _)| *peer)
680            .collect();
681        for peer in &expired {
682            self.pending.pop(peer);
683        }
684        if !expired.is_empty() {
685            obs.outside_answerability_window.fetch_add(
686                u64::try_from(expired.len()).unwrap_or(u64::MAX),
687                Ordering::Relaxed,
688            );
689        }
690        expired.len()
691    }
692
693    fn has_reservation(&self) -> bool {
694        self.reserved.is_some()
695    }
696
697    /// Whether admitting `event` would displace a DIFFERENT peer's pending
698    /// entry: the queue is at capacity and `event.peer` has no incumbent to
699    /// coalesce into. The drainer checks this before enqueueing so pending
700    /// work gets a reservation opportunity BEFORE destructive overflow
701    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
702    /// of `pending`, freeing the slot without any eviction.
703    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
704        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
705    }
706
707    /// When the outstanding reservation becomes eligible for promotion.
708    fn reserved_ready_at(&self) -> Option<Instant> {
709        self.reserved.as_ref().map(|r| r.ready_at)
710    }
711
712    /// The peer of the outstanding reservation, if any.
713    fn reserved_peer(&self) -> Option<PeerId> {
714        self.reserved.as_ref().map(|r| r.event.peer)
715    }
716
717    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
718    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
719    /// if already first-audited; the window screen is bypassed for the currently
720    /// reserved peer (so a successor is retained across the reservation, never
721    /// window-dropped); otherwise window-screened. Coalescing is
722    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
723    /// displaces a higher-count pending pin. An incumbent that has aged past
724    /// the answerability horizon is dropped (and accounted as an expiry) before
725    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
726    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
727    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
728    /// displacement is accounted as `capacity_evicted` and stamps no
729    /// suppression, so a displaced peer's next nomination is judged like any
730    /// newcomer. The drainer additionally offers a reservation opportunity
731    /// via [`Self::would_displace`] before calling this on an overflowing
732    /// arrival.
733    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
734        if event.peer == self.self_peer {
735            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
736            return;
737        }
738        if self.first_audited.contains(&event.pin) {
739            obs.duplicates.fetch_add(1, Ordering::Relaxed);
740            return;
741        }
742        let reserved_peer = self.reserved_peer();
743        let is_reserved_peer = reserved_peer == Some(event.peer);
744        if !is_reserved_peer
745            && !self
746                .limiter
747                .window_allows(&event.peer, event.key_count, Instant::now())
748        {
749            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
750            return;
751        }
752        // A pending incumbent past the answerability horizon can never launch,
753        // yet its (possibly higher) key count would still win the coalesce
754        // against a live incoming — e.g. a fresh post-prune lower-count pin —
755        // and under token starvation no reserve scan runs to collect it. Drop
756        // it first so the incoming is judged on its own merits.
757        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
758            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
759        });
760        if stale_incumbent {
761            self.pending.pop(&event.peer);
762            obs.outside_answerability_window
763                .fetch_add(1, Ordering::Relaxed);
764        }
765        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
766        // tie.
767        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
768            FirstAuditQueueOutcome::Queued => {
769                obs.queued.fetch_add(1, Ordering::Relaxed);
770            }
771            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
772                obs.coalesced.fetch_add(1, Ordering::Relaxed);
773            }
774            FirstAuditQueueOutcome::SuppressedLower => {
775                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
776            }
777            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
778                obs.queued.fetch_add(1, Ordering::Relaxed);
779                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
780            }
781        }
782    }
783
784    /// Attempt to create the single reservation from `pending` (E′ reserve).
785    /// Scans in the current lane order and reserves the FIRST eligible pin:
786    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
787    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
788    /// flip the lane — those happen only at promotion. Returns whether a
789    /// reservation was made. `cooldown` is a read-only snapshot (the
790    /// authoritative check-and-stamp is at promotion).
791    fn try_reserve(
792        &mut self,
793        mono_now: Instant,
794        inflight: u64,
795        jitter: Duration,
796        cooldown: &HashMap<PeerId, Instant>,
797        obs: &Arc<FirstAuditObservability>,
798    ) -> bool {
799        if self.reserved.is_some() || self.pending.is_empty() {
800            return false;
801        }
802        self.limiter.refill(mono_now);
803        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
804            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
805            return false;
806        }
807        // MRU->LRU order; reverse for the oldest-first lane so the preferred
808        // end is at the front.
809        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
810            .pending
811            .iter()
812            .enumerate()
813            .map(|(i, (p, e))| (i, *p, *e))
814            .collect();
815        self.pending.clear();
816        if self.oldest_first_lane {
817            ordered.reverse();
818        }
819        let mut chosen: Option<MonetizedPinEvent> = None;
820        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
821        for (idx, peer, event) in ordered {
822            if chosen.is_some() {
823                kept.push((idx, peer, event));
824                continue;
825            }
826            if self.first_audited.contains(&event.pin) {
827                obs.duplicates.fetch_add(1, Ordering::Relaxed);
828                continue; // drop: already audited
829            }
830            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
831                obs.outside_answerability_window
832                    .fetch_add(1, Ordering::Relaxed);
833                continue; // drop: cannot stay answerable through the jitter
834            }
835            // Window + budget + inflight. Tokens do not decrease during the
836            // scan (reserve happens after the loop) and `inflight` is fixed, so
837            // after the upfront budget gate `assess` never returns RateDeferred
838            // here; a defensive RateDeferred keeps the pin.
839            match self
840                .limiter
841                .assess(&peer, event.key_count, mono_now, inflight)
842            {
843                LimiterVerdict::WindowDeduped => {
844                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
845                    continue; // drop: recently first-audited, no count jump
846                }
847                LimiterVerdict::RateDeferred => {
848                    kept.push((idx, peer, event));
849                    continue; // keep (defensive; unreachable after upfront gate)
850                }
851                LimiterVerdict::Admit => {}
852            }
853            if !cooldown_would_allow(cooldown, &peer, mono_now) {
854                obs.cooldown_deferred_attempts
855                    .fetch_add(1, Ordering::Relaxed);
856                kept.push((idx, peer, event));
857                continue; // keep: on shared cooldown, retry later
858            }
859            chosen = Some(event);
860        }
861        // Restore relative recency (oldest re-put first -> newest stays MRU).
862        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
863        for (_, peer, event) in kept {
864            self.pending.put(peer, event);
865        }
866        let Some(event) = chosen else {
867            return false;
868        };
869        self.limiter.reserve_token();
870        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
871        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
872        self.reserved = Some(FirstAuditReservation {
873            event,
874            ready_at,
875            inflight: inflight_slot,
876        });
877        true
878    }
879
880    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
881    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
882        if self
883            .reserved
884            .as_ref()
885            .is_some_and(|r| mono_now >= r.ready_at)
886        {
887            self.reserved.take()
888        } else {
889            None
890        }
891    }
892
893    /// Authoritative promotion of a due reservation (E′). The caller holds the
894    /// shared cooldown write lock and passes the real send-time `wall_now` and
895    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
896    /// launch, or `None` when the launch was cancelled (answerability lapsed
897    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
898    /// On both `None` paths the token is refunded, the in-flight slot released,
899    /// and NO suppression is recorded.
900    ///
901    /// Known operational residual: suppression is stamped here, at promotion,
902    /// while the wire challenge is sent by the detached task the caller spawns
903    /// with the returned event. A task-start or encoding failure between the
904    /// two therefore leaves a stamped-but-unsent window. No remote input can
905    /// force that failure (it requires local task-spawn/alloc failure), so it
906    /// is accepted rather than closed; closing it would require stamping from
907    /// inside the spawned task and re-introduce the cancel-leaves-suppression
908    /// race this design exists to prevent.
909    fn resolve(
910        &mut self,
911        reservation: FirstAuditReservation,
912        wall_now: SystemTime,
913        mono_now: Instant,
914        cooldown: &mut HashMap<PeerId, Instant>,
915        obs: &Arc<FirstAuditObservability>,
916    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
917        let FirstAuditReservation {
918            event, inflight, ..
919        } = reservation;
920        // Authoritative answerability at the REAL send time.
921        if !quote_within_audit_window(event.quote_ts, wall_now) {
922            self.limiter.refund_token();
923            obs.outside_answerability_window
924                .fetch_add(1, Ordering::Relaxed);
925            drop(inflight);
926            return None; // cancelled; nothing stamped, nothing to roll back
927        }
928        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
929        // concurrent gossip audit requeues the reserved event through the SAME
930        // security-aware coalescing: the reserved event is OLDER than any
931        // same-peer successor (`incoming_is_newer = false`), so a higher-count
932        // reserved event still wins over a lower-count successor (the inflated
933        // pin must be audited), while an equal/higher successor is preserved.
934        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
935            self.limiter.refund_token();
936            obs.cooldown_deferred_attempts
937                .fetch_add(1, Ordering::Relaxed);
938            drop(inflight);
939            // Account for the requeue outcome (the nomination itself was already
940            // counted at ingress, so `queued` is not re-incremented): a capacity
941            // eviction of a DIFFERENT peer and a suppressed reserved event are
942            // both observable per the ADR funnel.
943            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
944                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
945                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
946                }
947                FirstAuditQueueOutcome::SuppressedLower => {
948                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
949                }
950                FirstAuditQueueOutcome::Queued
951                | FirstAuditQueueOutcome::Coalesced
952                | FirstAuditQueueOutcome::RetainedOnTie => {}
953            }
954            return None;
955        }
956        // Promote: stamp durable suppression, flip the lane, count the launch.
957        self.limiter.promote(event.peer, event.key_count, mono_now);
958        self.first_audited.put(event.pin, ());
959        self.oldest_first_lane = !self.oldest_first_lane;
960        obs.launched.fetch_add(1, Ordering::Relaxed);
961        Some((event, inflight))
962    }
963}
964
965// ---------------------------------------------------------------------------
966// Constants
967// ---------------------------------------------------------------------------
968
969/// Prefix used by saorsa-core's request-response mechanism.
970const RR_PREFIX: &str = "/rr/";
971
972/// Bounded handoff from the P2P broadcast receiver to serial non-audit
973/// replication processing.
974///
975/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
976/// bulk/non-audit messages here. If this fills, the message is **dropped** —
977/// `start_message_handler` must never block on a full queue, because a stalled
978/// receiver laps the P2P broadcast ring and silently loses messages it never
979/// observed. Every serial-lane class has protocol recovery, so a drop costs a
980/// retry rather than the message.
981///
982/// This bounds a message COUNT, but a queued item is an owned decoded message
983/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
984/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
985/// for: the lane carries small requests and challenges alongside
986/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
987/// right for both. Responses never reach here — `replication_payload_from_event`
988/// filters them out and their requesters correlate them. ADR-0005 decision 12
989/// records the trade and why byte accounting is the correct eventual fix.
990const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
991
992/// Maximum fresh-replication offers processed concurrently, away from the
993/// serial non-audit loop.
994///
995/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
996/// write. Four workers keep that latency off the responder dispatch path while
997/// keeping concurrent EVM/storage pressure small and predictable.
998const FRESH_OFFER_WORKER_LIMIT: usize = 4;
999
1000/// Maximum fresh offers admitted at once, counting both those running on a
1001/// worker and those queued for one.
1002///
1003/// An admitted offer holds its payload until it completes, so this bounds
1004/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1005/// Offers past the bound are refused rather than queued or handled inline —
1006/// handling one on the message loop stalls every other non-audit message behind
1007/// a payment verification and a multi-MiB write. A refusal is not free: the
1008/// sender does not read it, so it resurfaces as a missing key at the delayed
1009/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1010/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1011/// bound is sized to make refusal rare rather than cheap.
1012const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1013
1014/// Distinct payment proofs queued for one fresh-offer key.
1015///
1016/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1017/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1018/// chunk out to the close group, so a receiver sees the same key from about that
1019/// many senders. They differ only in their proof — the bytes are provably
1020/// identical, since `fresh_offer_structural_rejection` has confirmed
1021/// `key == BLAKE3(data)` before any of them is queued.
1022///
1023/// Sizing the queue to the number of legitimate senders is what lets a failing
1024/// proof fall through to the next one instead of costing the node the record.
1025///
1026/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1027/// admitted, and a proof the handler has popped has spent its slot rather than
1028/// returned it. That distinction is what bounds the work an attacker can buy —
1029/// at most this many on-chain verifications per key, after which the entry
1030/// refuses everyone until it closes. Gating on the queue's instantaneous length
1031/// instead would let a stream of distinct sources refill each popped slot and
1032/// run unbounded sequential verifications while holding one of the four worker
1033/// slots. One attempt per source additionally means a single peer can only ever
1034/// consume one of these.
1035const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1036
1037/// Fresh-offer slots kept reachable by sources that hold none.
1038///
1039/// The property worth guaranteeing is that one peer cannot *starve* others, not
1040/// that any peer is held to a small quota. Expressing the bound as a reserve
1041/// rather than a quota is what keeps those two apart.
1042const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1043
1044/// Maximum fresh offers admitted from one source peer.
1045///
1046/// Without a per-source bound, one peer can hold every slot in the global pool
1047/// and every honest offer arriving in that window is refused — and because a
1048/// refusal is later read as absence by the sender's delayed possession check,
1049/// those refusals land as audit-severity trust penalties on the *refuser*.
1050/// That makes an unbounded global pool a targeted eviction primitive.
1051///
1052/// The bound is deliberately far looser than the other responder classes'
1053/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1054/// the opposite shape. Those are request/response: a requester needs only a
1055/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1056/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1057/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1058/// for request/response traffic therefore binds on completely legitimate
1059/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1060/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1061/// ceiling and none to the global pool.
1062///
1063/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1064/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1065/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1066// The cast is from a compile-time constant difference of two small literals
1067// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1068// relationship visible in the code rather than only in a test.
1069#[allow(clippy::cast_possible_truncation)]
1070const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1071    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1072
1073/// Maximum paid-list notifications served concurrently.
1074///
1075/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1076/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1077/// Two workers keep cross-peer progress without multiplying concurrent EVM
1078/// and DHT lookup pressure.
1079const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1080
1081/// Maximum paid-list notifications admitted across workers and their waiters.
1082///
1083/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1084/// is one-way: the protocol defines no response and the sender never retries,
1085/// so a refused notify is information permanently lost to this node until a
1086/// later verification cycle happens to re-derive the key's paid status from a
1087/// paid-list quorum. A tight admission bound therefore does not shed load, it
1088/// discards durable state — which is why the class's real protection is
1089/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1090/// is actually expensive, rather than this queue depth.
1091///
1092/// A client PUT fans one notify per key out to the whole paid close group, so
1093/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1094/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1095/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1096/// carry no chunk payload.
1097const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1098
1099/// Maximum admitted paid-list notifications from one source peer.
1100///
1101/// A quarter of the pool. One peer legitimately supplies a whole upload's
1102/// worth of notifies, so this must comfortably exceed a typical file's chunk
1103/// count in flight; it exists to stop a single source evicting every other
1104/// peer's durable paid-list evidence, not to ration ordinary traffic.
1105const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1106
1107/// Maximum fetch responses served concurrently.
1108///
1109/// Each successful response can upload a 4 MiB chunk. Matching
1110/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1111/// simultaneous chunk data, which avoids saturating typical home upload links.
1112const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1113
1114/// Maximum fetch requests admitted across workers and their bounded waiters.
1115///
1116/// Four worker waves absorb short bursts without retaining chunk bytes—the
1117/// request contains only a key—while the dequeue deadline sheds work before a
1118/// sustained flood can keep the node serving requests whose callers timed out.
1119const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1120
1121/// Maximum admitted fetch requests from one source peer.
1122///
1123/// Two requests let one peer pipeline useful reads while leaving at least one
1124/// of the three workers available to other peers under a single-source flood.
1125const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1126
1127/// Maximum verification batches served concurrently.
1128///
1129/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1130/// workers isolate that synchronous work from message dispatch without turning
1131/// large batches into an I/O fan-out throughput contest.
1132const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1133
1134/// Maximum verification batches admitted across workers and bounded waiters.
1135///
1136/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1137/// deadline prevents queued batches from consuming lookup capacity after their
1138/// requesters have stopped waiting.
1139const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1140
1141/// Maximum admitted verification batches from one source peer.
1142///
1143/// Senders already aggregate a peer's keys into one batch. One outstanding
1144/// batch therefore preserves useful work while reserving the other worker and
1145/// the bounded queue for different peers.
1146const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1147
1148/// Maximum neighbor-sync requests served concurrently across source peers.
1149///
1150/// Building a response scans local keys and performs DHT lookups, so two
1151/// workers allow cross-peer progress without multiplying that expensive scan
1152/// into broad network and storage contention.
1153const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1154
1155/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1156///
1157/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1158/// payloads bounded; expired waiters are shed before any key scan begins.
1159const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1160
1161/// Maximum admitted neighbor-sync requests from one source peer.
1162///
1163/// Sync history must be updated before repair proofs for the same peer. A
1164/// single slot preserves that ordering while independent peers remain parallel.
1165const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1166
1167/// Match an inbound topic against the replication protocol ids, in both the bare
1168/// gossip form and the `/rr/<id>` request-response form.
1169///
1170/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1171/// was the RR form. The matched id is carried into the handler so it can enforce
1172/// that subtree messages only arrive on the subtree id.
1173fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1174    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1175        if topic == id {
1176            return Some((id, false));
1177        }
1178        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1179            if rest == id {
1180                return Some((id, true));
1181            }
1182        }
1183    }
1184    None
1185}
1186
1187/// Whether a decoded body belongs on the protocol id it arrived on:
1188/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1189/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1190///
1191/// The receive guard drops any mismatch (a cross-version or misrouted message);
1192/// sharing this one predicate between the guard and its regression test means a
1193/// change to the rule cannot pass the test unnoticed.
1194fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1195    protocol == response_protocol_for(body)
1196}
1197
1198/// The protocol id a body belongs on — the single source of truth for BOTH
1199/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1200/// response selector in `send_replication_response_checked`.
1201///
1202/// Sharing one function makes the subtree/core isolation symmetric.
1203fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1204    if body.is_subtree_audit() {
1205        SUBTREE_AUDIT_PROTOCOL_ID
1206    } else {
1207        REPLICATION_PROTOCOL_ID
1208    }
1209}
1210
1211fn fresh_offer_payment_context() -> VerificationContext {
1212    VerificationContext::FreshReplication
1213}
1214
1215fn paid_notify_payment_context() -> VerificationContext {
1216    VerificationContext::PaidListAdmission
1217}
1218
1219/// Boxed future type for in-flight fetch tasks.
1220type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1221
1222/// Fresh-offer keys currently being handled, each with the proofs still to try.
1223///
1224/// Concurrent duplicates are routine: a client PUT is confirmed by
1225/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1226/// commonly arrives from several senders at once. Collapsing them onto one
1227/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1228/// and an on-chain verification per copy.
1229///
1230/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1231/// refusing every later offer outright made the first arrival the only arrival:
1232/// if its proof failed, the record was lost even though a valid proof for the
1233/// same bytes was queued behind it, and the resulting absence was charged to
1234/// this node by the delayed possession check. So the entry holds the bytes once
1235/// and queues each sender's proof, and the handler works down that queue. A
1236/// later offer therefore costs a proof, not a payload — sound only because
1237/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1238/// every one of them before it is queued, which is what makes their bytes
1239/// provably identical.
1240///
1241/// Entries are exact keys rather than hash shards. A node only receives offers
1242/// for keys it is close to, so the accepted key set clusters tightly around its
1243/// own ID — any index derived from the key would land nearly every offer on one
1244/// shard and serialize unrelated keys behind each other. Exact keys keep them
1245/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1246/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1247///
1248/// The critical section is a map insert, pop, or remove and is never held across
1249/// an await, so this is a blocking mutex rather than an async one.
1250type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1251
1252/// One sender's unverified claim to have paid for a key already in flight.
1253///
1254/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1255/// content-address check ran before this attempt was queued.
1256struct FreshOfferAttempt {
1257    source: PeerId,
1258    proof_of_payment: Vec<u8>,
1259    request_id: u64,
1260    rr_message_id: Option<String>,
1261}
1262
1263/// Proofs still to try for one in-flight key, and who supplied them.
1264///
1265/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1266/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1267struct FreshOfferEntry {
1268    /// Untried proofs in arrival order. The handler holds the current one.
1269    pending: VecDeque<FreshOfferAttempt>,
1270    /// Sources already represented, so one peer cannot fill the queue alone.
1271    sources: HashSet<PeerId>,
1272    /// Proofs admitted over this entry's whole life, **never decremented**.
1273    ///
1274    /// The budget has to be spent by admissions rather than held by the queue.
1275    /// The handler pops a proof before verifying it, so gating on
1276    /// `pending.len()` would let a fresh source refill the slot that pop just
1277    /// freed, and a stream of distinct sources could then run unbounded
1278    /// sequential payment verifications while holding one of only four worker
1279    /// slots. Counting admissions makes the cap a lifetime budget instead.
1280    admitted: usize,
1281}
1282
1283/// How an arriving fresh offer joined the work already in flight for its key.
1284enum FreshOfferAdmission {
1285    /// Opened the entry. This offer's handler owns the key and drives every
1286    /// queued proof, including proofs that arrive later.
1287    Opened(Box<FreshOfferEntryGuard>),
1288    /// Merged into an entry another offer opened; its handler reaches this proof
1289    /// if the ones ahead of it fail.
1290    Joined,
1291    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1292    Full,
1293    /// This source already has a proof queued for this key.
1294    DuplicateSource,
1295}
1296
1297// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1298// `debug!`, which compiles to nothing without the feature.
1299#[cfg(feature = "logging")]
1300impl FreshOfferAdmission {
1301    /// Why the offer added nothing to the work already queued for its key.
1302    ///
1303    /// Local logging only — the wire reason stays uniform so a probing peer
1304    /// cannot tell a full queue from a repeat of its own proof.
1305    const fn surplus_reason(&self) -> &'static str {
1306        match self {
1307            Self::DuplicateSource => "this source already has a proof queued",
1308            Self::Full => "the key already holds its full complement of proofs",
1309            Self::Opened(_) | Self::Joined => "not surplus",
1310        }
1311    }
1312}
1313
1314/// RAII ownership of one in-flight fresh-offer key.
1315///
1316/// Clears the entry on drop, so an early return, an error, or a panic cannot
1317/// strand a key as permanently in flight. Also owns the single copy of the
1318/// offered bytes that every queued proof is tried against.
1319struct FreshOfferEntryGuard {
1320    in_flight: FreshOfferInFlight,
1321    key: XorName,
1322    /// The bytes every attempt for this key shares, held exactly once.
1323    data: Vec<u8>,
1324    /// Arrival of the offer that opened the entry.
1325    received_at: Instant,
1326    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1327    /// a *later* offer has since opened for the same key.
1328    holds_entry: bool,
1329}
1330
1331impl FreshOfferEntryGuard {
1332    /// Open an entry for this offer's key, or queue its proof behind the entry
1333    /// already open.
1334    ///
1335    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1336    /// on every other outcome they are dropped here rather than held for the
1337    /// lifetime of the entry.
1338    fn admit(
1339        in_flight: &FreshOfferInFlight,
1340        offer: protocol::FreshReplicationOffer,
1341        source: PeerId,
1342        request_id: u64,
1343        rr_message_id: Option<String>,
1344        received_at: Instant,
1345    ) -> FreshOfferAdmission {
1346        let key = offer.key;
1347        let attempt = FreshOfferAttempt {
1348            source,
1349            proof_of_payment: offer.proof_of_payment,
1350            request_id,
1351            rr_message_id,
1352        };
1353
1354        let mut in_flight_map = in_flight.lock();
1355        if let Some(entry) = in_flight_map.get_mut(&key) {
1356            if entry.sources.contains(&source) {
1357                return FreshOfferAdmission::DuplicateSource;
1358            }
1359            // Lifetime budget, not queue depth: a proof the handler has already
1360            // popped has spent its slot, not returned it.
1361            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1362                return FreshOfferAdmission::Full;
1363            }
1364            entry.admitted = entry.admitted.saturating_add(1);
1365            entry.sources.insert(source);
1366            entry.pending.push_back(attempt);
1367            return FreshOfferAdmission::Joined;
1368        }
1369
1370        let mut sources = HashSet::new();
1371        sources.insert(source);
1372        let mut pending = VecDeque::new();
1373        pending.push_back(attempt);
1374        in_flight_map.insert(
1375            key,
1376            FreshOfferEntry {
1377                pending,
1378                sources,
1379                admitted: 1,
1380            },
1381        );
1382        drop(in_flight_map);
1383        FreshOfferAdmission::Opened(Box::new(Self {
1384            in_flight: Arc::clone(in_flight),
1385            key,
1386            data: offer.data,
1387            received_at,
1388            holds_entry: true,
1389        }))
1390    }
1391
1392    /// The bytes every proof for this key is tried against.
1393    fn data(&self) -> &[u8] {
1394        &self.data
1395    }
1396
1397    /// When the first offer for this key arrived.
1398    fn received_at(&self) -> Instant {
1399        self.received_at
1400    }
1401
1402    /// Take the next untried proof, releasing the key when none remain.
1403    ///
1404    /// Popping and releasing happen under one lock so a proof arriving exactly
1405    /// as the queue empties is never silently discarded: it either lands in this
1406    /// entry and is returned here, or finds no entry and opens its own.
1407    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1408        let mut in_flight = self.in_flight.lock();
1409        let Some(entry) = in_flight.get_mut(&self.key) else {
1410            self.holds_entry = false;
1411            return None;
1412        };
1413        if let Some(attempt) = entry.pending.pop_front() {
1414            return Some(attempt);
1415        }
1416        in_flight.remove(&self.key);
1417        self.holds_entry = false;
1418        None
1419    }
1420
1421    /// Release the key and return the proofs that were never tried, so their
1422    /// senders can be told the outcome the key reached without them.
1423    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1424        let mut in_flight = self.in_flight.lock();
1425        self.holds_entry = false;
1426        in_flight
1427            .remove(&self.key)
1428            .map(|entry| entry.pending.into_iter().collect())
1429            .unwrap_or_default()
1430    }
1431}
1432
1433impl Drop for FreshOfferEntryGuard {
1434    fn drop(&mut self) {
1435        if self.holds_entry {
1436            self.in_flight.lock().remove(&self.key);
1437        }
1438    }
1439}
1440
1441/// Shared dependencies for one verification worker cycle.
1442struct VerificationCycleContext<'a> {
1443    p2p_node: &'a Arc<P2PNode>,
1444    paid_list: &'a Arc<PaidList>,
1445    storage: &'a Arc<LmdbStorage>,
1446    queues: &'a Arc<RwLock<ReplicationQueues>>,
1447    config: &'a ReplicationConfig,
1448    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1449    is_bootstrapping: &'a Arc<RwLock<bool>>,
1450    bootstrap_complete_notify: &'a Arc<Notify>,
1451    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1452    /// peer's Present claim to Unresolved unless they're a credited
1453    /// holder of the key (i.e. they recently passed a commitment-bound
1454    /// audit on it under their currently-credited commitment hash).
1455    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1456    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1457    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1458}
1459
1460/// Fetch worker polling interval in milliseconds.
1461const FETCH_WORKER_POLL_MS: u64 = 100;
1462
1463/// Verification worker polling interval in milliseconds.
1464const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1465
1466/// Verification cycle duration that is worth surfacing at info level.
1467const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1468
1469/// Standard trust event weight for per-operation success/failure signals.
1470///
1471/// Used for individual replication fetch outcomes, integrity check failures,
1472/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1473/// is reserved for confirmed audit failures.
1474const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1475/// Bound trust updates from one verification cycle. A malicious peer can
1476/// advertise thousands of bad singleton keys at once; a few independent
1477/// contradictions are enough for the trust engine without flooding it.
1478const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1479
1480/// Bootstrap drain check interval in seconds.
1481const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1482
1483/// Grace period `shutdown()` waits for each long-lived background task to
1484/// observe the cancellation token and terminate before aborting it.
1485///
1486/// Detached tasks are drained without a timeout because storage-capable work
1487/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1488/// if its async waiter is dropped.
1489const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1490
1491/// How often the responder rebuilds + rotates its storage commitment.
1492///
1493/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1494/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1495/// rotation-anchored: the responder stays answerable for the current
1496/// commitment plus every root it recently gossiped that is still in-window
1497/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1498/// its last emission (see `commitment_state`). So the rotation cadence does
1499/// not by itself bound answerability — a gossiped commitment stays
1500/// answerable across rotations until its gossip TTL lapses.
1501///
1502/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1503/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1504/// comfortably exceeds the gap between our rotation and the next gossip
1505/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1506/// Idle audit-skip pattern from being the common case.
1507///
1508/// Why not faster: the v12 pin is bound to a specific point-in-time
1509/// commitment, so rotation isn't security-critical for pin freshness —
1510/// only for keeping the committed key set current as the responder
1511/// writes new keys. 1 hour is plenty for that, and slow enough that
1512/// honest auditors mostly hit `current` or `previous` rather than the
1513/// "rotated past" case.
1514const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1515
1516/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1517/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1518/// durable well before it could matter to a restart, while the write-on-change
1519/// guard keeps idle nodes from needless disk writes.
1520const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1521
1522/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1523/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1524/// default that keeps log volume negligible.
1525const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1526
1527/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1528/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1529/// for first audit only if its SIGNED `quote_ts` lands in
1530/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1531/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1532/// badly-skewed or replayed quote) and one too old (the responder may have aged
1533/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1534/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1535/// within this margin); a legit first audit fires moments after payment
1536/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1537/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1538/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1539const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1540
1541/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1542/// inside the answerability window relative to `now`, so first-auditing it cannot
1543/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1544/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1545/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1546/// All comparisons use `duration_since` (no `Duration` overflow).
1547fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1548    let too_future = quote_ts
1549        .duration_since(now)
1550        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1551    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1552    let too_old = now
1553        .duration_since(quote_ts)
1554        .is_ok_and(|age| age >= audit_cutoff);
1555    !(too_future || too_old)
1556}
1557
1558/// Minimum interval between commitment signature verifications for a
1559/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1560///
1561/// A sybil that bypasses the routing-table gate (e.g. by transient
1562/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1563/// per gossip message. This rate limit caps the verify-per-peer rate
1564/// at 1/min, which is comfortably above the legitimate gossip cadence
1565/// (the 10-20 min neighbor-sync round on each peer).
1566const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1567
1568/// Hard cap on the size of `last_commitment_by_peer`.
1569///
1570/// Bounds the per-process memory cost of the auditor's per-peer
1571/// commitment cache. Each entry holds a `StorageCommitment`
1572/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1573/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1574/// realistic close-group neighborhood. When the cap is hit, one
1575/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1576/// order is unspecified; we do not track insertion order). The
1577/// `PeerRemoved` handler proactively drops entries as the DHT
1578/// detects departures, and `ingest_peer_commitment` only admits
1579/// commitments from peers currently in the routing table — together
1580/// the cap is the third line of defence against sybil/churn flooding.
1581const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1582
1583/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1584/// sized to the launch budget instead of the commitment cache.
1585///
1586/// The token bucket can launch at most one audit per
1587/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1588/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1589/// launchable for at most the effective answerability window
1590/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1591/// occupancy beyond `window / interval + burst` is work that cannot launch
1592/// before it expires, so admitting it only builds an aging backlog whose
1593/// telemetry measures the backlog instead of schedulable work.
1594///
1595/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1596/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1597/// rolling sample in which no arrival order lets an attacker deterministically
1598/// flush a chosen target; a fresh pin always enters the sample with an
1599/// unpredictable chance of near-immediate audit, whereas refusing at the door
1600/// would let a sustained payment flood guarantee that every later pin is never
1601/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1602/// ADR-0004 Amendment 4 for the eviction-cost math.
1603///
1604/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1605/// is usable only if the quote stays answerable through `a` plus the maximum
1606/// launch jitter and send slack, so the last usable refill is the largest
1607/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1608/// simulates the shipped predicate instant-by-instant and must agree.
1609#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1610const FIRST_AUDIT_PENDING_CAP: usize = {
1611    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1612        .as_secs()
1613        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1614        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1615        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1616    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1617    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1618    // if the launch interval is ever zeroed: a zero interval makes the budget
1619    // (and this cap) meaningless.
1620    let refills =
1621        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1622    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1623};
1624
1625// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1626// strictly tighter than the commitment-cache bound it replaced.
1627const _: () = {
1628    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1629    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1630};
1631
1632/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1633/// long-running bootstrap node cannot have the set grow without limit
1634/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1635/// the set comfortably outlives normal LRU churn but still caps the
1636/// blast radius of identity-rotation attacks. Once full we refuse new
1637/// inserts (no eviction) — keeps the historic set stable; new v12
1638/// peers above the cap are treated as legacy on rejoin, which matches
1639/// the behaviour before this set existed, not a security regression.
1640const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1641
1642// ---------------------------------------------------------------------------
1643// ReplicationEngine
1644// ---------------------------------------------------------------------------
1645
1646/// The replication engine manages all replication background tasks and state.
1647pub struct ReplicationEngine {
1648    /// Replication configuration (shared across spawned tasks).
1649    config: Arc<ReplicationConfig>,
1650    /// P2P networking node.
1651    p2p_node: Arc<P2PNode>,
1652    /// Local chunk storage.
1653    storage: Arc<LmdbStorage>,
1654    /// Persistent paid-for-list.
1655    paid_list: Arc<PaidList>,
1656    /// Payment verifier for `PoP` validation.
1657    payment_verifier: Arc<PaymentVerifier>,
1658    /// Replication pipeline queues.
1659    queues: Arc<RwLock<ReplicationQueues>>,
1660    /// Neighbor sync cycle state.
1661    sync_state: Arc<RwLock<NeighborSyncState>>,
1662    /// Per-peer sync history (for `RepairOpportunity`).
1663    ///
1664    /// This map grows with peer churn and is intentionally unbounded: entries
1665    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1666    /// naturally bounded by the routing table's k-bucket capacity.
1667    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1668    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1669    ///
1670    /// Records when each peer was last audited so a burst of gossiped
1671    /// commitment changes cannot spawn back-to-back audits of the same peer.
1672    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1673    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1674    /// Gossip-private lottery attempt window (one roll per peer per window,
1675    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1676    /// ticket never stamps the shared map and thus never defers a monetized
1677    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1678    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679    /// Completed local neighbor-sync cycle epoch for proof maturity.
1680    sync_cycle_epoch: Arc<RwLock<u64>>,
1681    /// Per-key repair proof tracking for audit eligibility.
1682    repair_proofs: Arc<RwLock<RepairProofs>>,
1683    /// Bootstrap state tracking.
1684    bootstrap_state: Arc<RwLock<BootstrapState>>,
1685    /// Whether this node is currently bootstrapping.
1686    is_bootstrapping: Arc<RwLock<bool>>,
1687    /// Trigger for early neighbor sync (signalled on topology changes).
1688    sync_trigger: Arc<Notify>,
1689    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1690    bootstrap_complete_notify: Arc<Notify>,
1691    /// Node identity (for signing storage commitments).
1692    ///
1693    /// Phase 3 of the v12 storage-bound audit design. The responder
1694    /// uses this to sign its periodically-built `StorageCommitment`.
1695    identity: Arc<NodeIdentity>,
1696    /// Responder-side commitment state (two-slot atomic rotation).
1697    ///
1698    /// Periodically rebuilt from the live LMDB key set; gossiped on
1699    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1700    /// commitment-bound audit handler.
1701    commitment_state: Arc<ResponderCommitmentState>,
1702    /// Path to the persisted responder retention snapshot
1703    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1704    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1705    /// removing audit grace safe (an unanswerable in-window pin is then provable
1706    /// misbehaviour, not an honest crash-restart).
1707    retention_path: PathBuf,
1708    /// Auditor-side per-peer commitment record (last known commitment +
1709    /// sticky `commitment_capable` flag).
1710    ///
1711    /// Populated whenever an inbound gossip carries a verified
1712    /// commitment from the sender. Used by `audit_tick` to snapshot
1713    /// `expected_commitment_hash` into outbound challenges, and by
1714    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1715    /// proof should be honoured. The sticky `commitment_capable` flag
1716    /// flips true on first successful ingest and never reverts (§2
1717    /// step 5).
1718    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1719    /// Sticky set of peer IDs we have EVER seen carrying a v12
1720    /// commitment, independent of whether their commitment bytes are
1721    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1722    /// closure consults this set to keep treating churned-out
1723    /// previously-v12 peers as v12-capable (rather than degrading them
1724    /// to "legacy" credit-unconditionally) when they re-appear on the
1725    /// network before their next gossip arrives. Bounded growth: even
1726    /// at one million peers seen over the node's lifetime, the set is
1727    /// 32 MB.
1728    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1729    /// Auditor-side holder-eligibility cache (v12 §6).
1730    ///
1731    /// Recorded on successful commitment-bound audit; read by future
1732    /// quorum / paid-list eligibility checks (phase-3 stretch).
1733    recent_provers: Arc<RwLock<RecentProvers>>,
1734    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1735    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1736    /// failure) so a peer we've never successfully verified can't burn
1737    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1738    /// Lives separately from `last_commitment_by_peer` because that
1739    /// map's records only exist after a successful verify.
1740    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1741    /// Limits concurrent outbound replication sends to prevent bandwidth
1742    /// saturation on home broadband connections.
1743    send_semaphore: Arc<Semaphore>,
1744    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1745    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1746    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1747    /// message loop so disk
1748    /// reads don't block replication; the semaphore restores a global
1749    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1750    /// / multi-MiB byte serves.
1751    audit_responder_semaphore: Arc<Semaphore>,
1752    /// Per-source in-flight audit-responder counts, capped at
1753    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1754    /// flood-fair: one peer spamming challenges could occupy every slot and
1755    /// starve honest auditors, whose dropped challenges then convert to
1756    /// audit timeouts against HONEST peers (codex-r2 A). This
1757    /// per-peer cap guarantees no single source can hold more than its share,
1758    /// so a flood self-throttles without denying service to everyone else.
1759    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1760    /// Windowed per-origin capacity and processing-time telemetry for every
1761    /// request sharing the audit responder pool.
1762    audit_responder_metrics: Arc<AuditResponderMetrics>,
1763    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1764    ///
1765    /// Responsible-chunk audits, prune confirmations, and possession checks
1766    /// all use this before sending so local bursts wait instead of breaching
1767    /// the responder's deployed per-source admission cap.
1768    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1769    /// Worker permits for bandwidth-bound fetch responses.
1770    fetch_responder_worker_semaphore: Arc<Semaphore>,
1771    /// Admission permits bounding fetch workers and queued waiters together.
1772    fetch_responder_admission_semaphore: Arc<Semaphore>,
1773    /// Per-source fetch responder counts for flood-fair admission.
1774    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1775    /// Worker permits for lookup-heavy verification batches.
1776    verification_responder_worker_semaphore: Arc<Semaphore>,
1777    /// Admission permits bounding verification workers and queued waiters.
1778    verification_responder_admission_semaphore: Arc<Semaphore>,
1779    /// Per-source verification responder counts for flood-fair admission.
1780    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1781    /// Worker permits for expensive inbound neighbor-sync requests.
1782    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1783    /// Admission permits bounding sync workers and queued waiters together.
1784    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1785    /// Per-source sync responder counts; capped at one to preserve ordering.
1786    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1787    /// Bounded worker permits for expensive fresh-offer handling.
1788    fresh_offer_worker_semaphore: Arc<Semaphore>,
1789    /// Admission permits bounding offers running on a worker or queued for one.
1790    fresh_offer_admission_semaphore: Arc<Semaphore>,
1791    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1792    /// and turn honest senders' refusals into trust penalties on this node.
1793    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1794    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1795    /// duplicates collapse onto one verification and one write.
1796    fresh_offer_in_flight: FreshOfferInFlight,
1797    /// Bounded worker permits for paid-list notification proof verification.
1798    paid_notify_worker_semaphore: Arc<Semaphore>,
1799    /// Admission permits bounding notifies on a worker or queued for one.
1800    paid_notify_admission_semaphore: Arc<Semaphore>,
1801    /// Per-source paid-notify counts for flood-fair admission.
1802    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1803    /// Resource controls for the HEAVY subtree-audit round 1: its own
1804    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1805    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1806    /// sessions binding a slice challenge to a matching round 1.
1807    subtree_round1: SubtreeRound1Limiter,
1808    /// Receiver for fresh-write events from the chunk PUT handler.
1809    ///
1810    /// When present, `start()` spawns a drainer task that calls
1811    /// `replicate_fresh` for each event.
1812    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1813    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1814    /// drainer pushes the responsible close-group peers here after each fresh
1815    /// replication; the possession-check scheduler drains the paired receiver.
1816    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1817    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1818    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1819    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1820    /// for a deterministic first audit. The matching receiver is drained by
1821    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1822    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1823    /// like launches; a dropped nomination is penalty-free — the peer's
1824    /// gossiped commitments stay lottery-covered and its next settled payment
1825    /// re-nominates the paid pin.
1826    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1827    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1828    /// `start_first_audit_drainer`.
1829    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1830    /// Counters shared with the first-audit drainer task, so the scheduler's
1831    /// decisions (queued / launched / self-target skipped / outcome) stay
1832    /// observable from the engine after the drainer takes the receiver.
1833    first_audit_observability: Arc<FirstAuditObservability>,
1834    /// Shutdown token.
1835    shutdown: CancellationToken,
1836    /// Background task handles.
1837    task_handles: Vec<JoinHandle<()>>,
1838    /// Tracks detached, short-lived work spawned by background producers.
1839    ///
1840    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1841    /// tasks, and delayed possession checks may retain storage or P2P state
1842    /// after their producer exits, so shutdown drains them before those
1843    /// resources may be reopened.
1844    detached_task_tracker: TaskTracker,
1845}
1846
1847impl ReplicationEngine {
1848    /// Create a new replication engine.
1849    ///
1850    /// # Errors
1851    ///
1852    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1853    /// or if the configuration fails validation.
1854    #[allow(clippy::too_many_arguments)]
1855    pub async fn new(
1856        config: ReplicationConfig,
1857        p2p_node: Arc<P2PNode>,
1858        storage: Arc<LmdbStorage>,
1859        payment_verifier: Arc<PaymentVerifier>,
1860        identity: Arc<NodeIdentity>,
1861        root_dir: &Path,
1862        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1863        shutdown: CancellationToken,
1864    ) -> Result<Self> {
1865        config.validate().map_err(Error::Config)?;
1866
1867        let paid_list = Arc::new(
1868            PaidList::new(root_dir)
1869                .await
1870                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1871        );
1872
1873        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1874        let config = Arc::new(config);
1875        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1876
1877        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1878        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1879        // now capacity-limited — ingress queue here, pending set (LRU), and
1880        // launch rate (token bucket).
1881        let (monetized_pin_tx, monetized_pin_rx) =
1882            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1883
1884        let engine = Self {
1885            config: Arc::clone(&config),
1886            p2p_node,
1887            storage,
1888            paid_list,
1889            payment_verifier,
1890            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1891            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1892            sync_history: Arc::new(RwLock::new(HashMap::new())),
1893            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1894            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1895            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1896            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1897            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1898            is_bootstrapping: Arc::new(RwLock::new(true)),
1899            sync_trigger: Arc::new(Notify::new()),
1900            bootstrap_complete_notify: Arc::new(Notify::new()),
1901            identity,
1902            commitment_state: Arc::new(ResponderCommitmentState::new()),
1903            retention_path: root_dir.join("commitment_retention.bin"),
1904            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1905            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1906            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1907            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1908            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1909            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1910            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1911            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1912            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1913            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1914                FETCH_RESPONDER_WORKER_LIMIT,
1915            )),
1916            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1917                FETCH_RESPONDER_MAX_OUTSTANDING,
1918            )),
1919            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1920            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1921                VERIFICATION_RESPONDER_WORKER_LIMIT,
1922            )),
1923            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1924                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1925            )),
1926            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1927            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1928                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1929            )),
1930            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1931                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1932            )),
1933            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1934            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1935            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1936            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1937            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1938            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1939            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1940            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1941            subtree_round1: SubtreeRound1Limiter::new(
1942                config.subtree_round1_responder_cooldown,
1943                config.subtree_round1_max_concurrent,
1944            ),
1945            fresh_write_rx: Some(fresh_write_rx),
1946            possession_check_tx,
1947            possession_check_rx: Some(possession_check_rx),
1948            monetized_pin_tx,
1949            monetized_pin_rx: Some(monetized_pin_rx),
1950            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1951            shutdown,
1952            task_handles: Vec::new(),
1953            detached_task_tracker: TaskTracker::new(),
1954        };
1955        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1956        // spawns, so an honest restarted node is answerable for its pre-restart
1957        // pins from the first audit it serves, and the persist loop never races
1958        // an empty snapshot over the good on-disk file.
1959        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1960        Ok(engine)
1961    }
1962
1963    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1964    /// (commitments that backed a payment) for a first audit. Cloneable; the
1965    /// engine drains the matching receiver. Bounded: senders must `try_send`
1966    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1967    #[must_use]
1968    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1969        self.monetized_pin_tx.clone()
1970    }
1971
1972    /// Get a reference to the `PaidList`.
1973    #[must_use]
1974    pub fn paid_list(&self) -> &Arc<PaidList> {
1975        &self.paid_list
1976    }
1977
1978    /// Get a reference to the responder's commitment state. Used by audit
1979    /// handlers to look up commitments by hash; used by the rotation tick
1980    /// to install fresh ones.
1981    #[must_use]
1982    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1983        &self.commitment_state
1984    }
1985
1986    /// Get a reference to the auditor's last-commitment-by-peer table.
1987    #[must_use]
1988    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1989        &self.last_commitment_by_peer
1990    }
1991
1992    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
1993    /// will be read by quorum / paid-list eligibility checks.
1994    #[must_use]
1995    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
1996        &self.recent_provers
1997    }
1998
1999    /// Test-only: rebuild + rotate this node's storage commitment now over its
2000    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2001    /// just stored without waiting for the rotation cadence.
2002    ///
2003    /// # Errors
2004    ///
2005    /// Propagates any error from reading the local key set or building/signing
2006    /// the commitment.
2007    #[cfg(any(test, feature = "test-utils"))]
2008    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2009        rebuild_and_rotate_commitment(
2010            &self.storage,
2011            &self.identity,
2012            &self.commitment_state,
2013            &self.p2p_node,
2014            &self.config,
2015        )
2016        .await
2017    }
2018
2019    /// Test-only: directly seed this node's cached commitment for `peer`,
2020    /// simulating "we received `peer`'s gossiped commitment" without depending
2021    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2022    /// peer's commitment deterministically.
2023    #[cfg(any(feature = "test-utils", test))]
2024    pub async fn inject_peer_commitment_for_test(
2025        &self,
2026        peer: &PeerId,
2027        commitment: StorageCommitment,
2028    ) {
2029        let now = Instant::now();
2030        self.last_commitment_by_peer
2031            .write()
2032            .await
2033            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2034        self.ever_capable_peers.write().await.insert(*peer);
2035    }
2036
2037    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2038    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2039    /// window and clears any shared cooldown stamped by an earlier gossip
2040    /// launch. The locks follow the production gossip-audit lock order.
2041    #[cfg(any(test, feature = "test-utils"))]
2042    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2043        let now = Instant::now();
2044        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2045        let mut launched = self.audit_on_gossip_cooldown.write().await;
2046        lottery_attempts.insert(*peer, now);
2047        launched.remove(peer);
2048    }
2049
2050    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2051    /// commitment this node has cached for it (from gossip), over the live wire.
2052    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2053    /// in a real two-node setting without waiting for the gossip cadence.
2054    ///
2055    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2056    /// peer yet (gossip hasn't reached us). Gated to test builds.
2057    #[cfg(any(test, feature = "test-utils"))]
2058    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2059        let target = {
2060            let map = self.last_commitment_by_peer.read().await;
2061            map.get(peer)
2062                .and_then(PeerCommitmentRecord::last_commitment)
2063                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2064        };
2065        let Some((pin, key_count)) = target else {
2066            return audit::AuditTickResult::Idle;
2067        };
2068        let credit = storage_commitment_audit::AuditCredit {
2069            recent_provers: &self.recent_provers,
2070        };
2071        storage_commitment_audit::run_subtree_audit(
2072            &self.p2p_node,
2073            &self.config,
2074            peer,
2075            pin,
2076            key_count,
2077            Some(&credit),
2078        )
2079        .await
2080    }
2081
2082    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2083    /// tests assert what the live drainer decided for an injected
2084    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2085    #[cfg(any(test, feature = "test-utils"))]
2086    #[must_use]
2087    pub fn first_audit_stats(&self) -> FirstAuditStats {
2088        let o = &self.first_audit_observability;
2089        FirstAuditStats {
2090            received: o.received.load(Ordering::Relaxed),
2091            queued: o.queued.load(Ordering::Relaxed),
2092            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2093            launched: o.launched.load(Ordering::Relaxed),
2094            passed: o.passed.load(Ordering::Relaxed),
2095            timed_out: o.timed_out.load(Ordering::Relaxed),
2096            failed: o.failed.load(Ordering::Relaxed),
2097        }
2098    }
2099
2100    /// Test-only: run the possession check immediately for `key` against
2101    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2102    ///
2103    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2104    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2105    /// deterministically without waiting for the scheduled check.
2106    #[cfg(any(test, feature = "test-utils"))]
2107    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2108        possession::run_possession_check(
2109            key,
2110            peers,
2111            &self.p2p_node,
2112            &self.storage,
2113            &self.config,
2114            &self.sync_state,
2115            &self.audit_challenge_coordinator,
2116            &self.shutdown,
2117        )
2118        .await;
2119    }
2120
2121    /// Test-only: place `key` directly into the fetch queue as though a
2122    /// verification cycle had just promoted it, with `sources` as its
2123    /// verified holders. Returns whether the key was enqueued.
2124    ///
2125    /// Bypasses admission, verification, and the promotion-time
2126    /// responsibility pre-filter, modelling a promotion decision that has
2127    /// since gone stale (topology churn between promotion and download).
2128    /// The only guard left standing is the per-attempt recheck inside
2129    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2130    /// exercise.
2131    #[cfg(any(test, feature = "test-utils"))]
2132    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2133        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2134        self.queues
2135            .write()
2136            .await
2137            .enqueue_fetch(key, distance, sources)
2138    }
2139
2140    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2141    /// (pending verification, fetch queue, or in-flight fetch).
2142    #[cfg(any(test, feature = "test-utils"))]
2143    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2144        self.queues.read().await.contains_key(key)
2145    }
2146
2147    /// Start all background tasks.
2148    ///
2149    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2150    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2151    /// missed by the bootstrap-sync gate.
2152    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2153        if !self.task_handles.is_empty() {
2154            error!("ReplicationEngine::start() called while already running — ignoring");
2155            return;
2156        }
2157        info!("Starting replication engine");
2158
2159        self.start_message_handler();
2160        self.start_neighbor_sync_loop();
2161        self.start_self_lookup_loop();
2162        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2163        // chunks they SHOULD store (responsibility + prior hint).
2164        self.start_audit_loop();
2165        // Audit #1 (storage-commitment) is gossip-triggered in the message
2166        // handler when a peer's commitment is ingested, not on a periodic tick.
2167        self.start_commitment_rotation_loop();
2168        self.start_retention_persist_loop();
2169        self.start_fetch_worker();
2170        self.start_verification_worker();
2171        self.start_bootstrap_sync(dht_events);
2172        self.start_fresh_write_drainer();
2173        self.start_possession_check_scheduler();
2174        // ADR-0004: deterministic first audit of commitments that backed a
2175        // payment (surfaced by the verifier cross-check).
2176        self.start_first_audit_drainer();
2177        // V2-623: periodic cumulative per-variant traffic accounting.
2178        self.start_traffic_summary_loop();
2179        #[cfg(feature = "logging")]
2180        self.start_audit_responder_summary_loop();
2181
2182        info!(
2183            "Replication engine started with {} background tasks",
2184            self.task_handles.len()
2185        );
2186    }
2187
2188    /// Returns `true` if the node is still in the replication bootstrap phase.
2189    ///
2190    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2191    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2192    pub async fn is_bootstrapping(&self) -> bool {
2193        *self.is_bootstrapping.read().await
2194    }
2195
2196    /// Wait until the replication bootstrap phase completes.
2197    ///
2198    /// Returns immediately if bootstrap has already completed. Useful for
2199    /// readiness probes, health checks, and test harnesses that need the
2200    /// node to be fully operational before proceeding.
2201    ///
2202    /// Returns `true` if bootstrap completed within the timeout, `false`
2203    /// if the timeout elapsed first.
2204    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2205        // Register the notification future *before* checking the flag so that
2206        // a transition between the read and the await is not missed.
2207        let notified = self.bootstrap_complete_notify.notified();
2208        tokio::pin!(notified);
2209        notified.as_mut().enable();
2210
2211        if !*self.is_bootstrapping.read().await {
2212            return true;
2213        }
2214
2215        tokio::time::timeout(timeout, notified).await.is_ok()
2216    }
2217
2218    /// Cancel all background tasks and wait for them to terminate.
2219    ///
2220    /// This must be awaited before dropping the engine when the caller needs
2221    /// the `Arc<LmdbStorage>` references held by background tasks to be
2222    /// released (e.g. before reopening the same LMDB environment).
2223    ///
2224    /// When this returns, no engine-spawned task still holds
2225    /// `Arc<LmdbStorage>` or `Arc<PaidList>`, and no LMDB blocking operation
2226    /// (read or write, on either the chunk store or the paid-list
2227    /// environment) is still running.  Engine tasks race their work against
2228    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2229    /// LMDB transaction running detached, so this method additionally waits
2230    /// for both storage layers to go quiescent before returning.
2231    pub async fn shutdown(&mut self) {
2232        self.shutdown.cancel();
2233        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2234            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2235                Ok(Ok(())) => {}
2236                Ok(Err(e)) if e.is_cancelled() => {}
2237                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2238                Err(_) => {
2239                    warn!(
2240                        "Replication task {i} did not stop within {}s, aborting",
2241                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2242                    );
2243                    handle.abort();
2244                    // `abort` only requests cancellation. Await the handle so
2245                    // synchronous sections finish and the task drops every
2246                    // storage/P2P clone before we claim producer quiescence.
2247                    match handle.await {
2248                        Ok(()) => {}
2249                        Err(e) if e.is_cancelled() => {}
2250                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2251                    }
2252                }
2253            }
2254        }
2255
2256        // Close the responder worker pools. Detached tasks still queued for a
2257        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2258        // rather than waiting for a slot that will never free up — without
2259        // this, work admitted just before shutdown would queue behind the last
2260        // in-flight batch and hold the drain below open for its full duration.
2261        self.fresh_offer_worker_semaphore.close();
2262        self.paid_notify_worker_semaphore.close();
2263        self.fetch_responder_worker_semaphore.close();
2264        self.verification_responder_worker_semaphore.close();
2265        self.neighbor_sync_responder_worker_semaphore.close();
2266
2267        // All producers have stopped, so close and drain their detached work.
2268        // A started storage operation must run to completion: dropping an async
2269        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2270        // while an LMDB transaction still owns the environment.
2271        //
2272        // Deliberately unbounded: the LMDB contract requires every worker to
2273        // release its `Arc<LmdbStorage>` before the caller may reopen the
2274        // environment, and a timeout here could return with one still held.
2275        // What makes that safe is that every detached task is now guaranteed to
2276        // finish — the pools above are closed, stale work is shed at dequeue,
2277        // and the one genuinely unbounded await (payment verification) races
2278        // `self.shutdown` via `verify_payment_until_shutdown`.
2279        self.detached_task_tracker.close();
2280        self.detached_task_tracker.wait().await;
2281
2282        // Every producer is gone, but a select! racing the shutdown token may
2283        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2284        // (fetch `storage.put`, prune `storage.delete` /
2285        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2286        // detached blocking closure owns a cloned `Env`; wait for both
2287        // environments to go quiescent — bounded by one in-flight transaction
2288        // per op — so the caller may reopen them.
2289        self.storage.wait_idle().await;
2290        self.paid_list.wait_idle().await;
2291    }
2292
2293    /// Trigger an early neighbor sync round.
2294    ///
2295    /// Useful after topology changes (new nodes joining, network heal after
2296    /// partition) when the caller wants replication to converge faster than
2297    /// the regular 10-20 minute cadence.
2298    pub fn trigger_neighbor_sync(&self) {
2299        self.sync_trigger.notify_one();
2300    }
2301
2302    /// Execute fresh replication for a newly stored record, then schedule the
2303    /// delayed possession check for the responsible close-group peers
2304    /// (ADR-0003). The production PUT path schedules via the fresh-write
2305    /// drainer; this direct entry point schedules here so callers (and tests)
2306    /// that drive replication directly still get the possession check.
2307    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2308        let peers = fresh::replicate_fresh(
2309            key,
2310            data,
2311            proof_of_payment,
2312            &self.p2p_node,
2313            &self.paid_list,
2314            &self.config,
2315            &self.send_semaphore,
2316        )
2317        .await;
2318        if !peers.is_empty() {
2319            let _ = self
2320                .possession_check_tx
2321                .send(possession::PossessionCheckEvent { key: *key, peers });
2322        }
2323    }
2324
2325    // =======================================================================
2326    // Background task launchers
2327    // =======================================================================
2328
2329    /// Spawn a task that drains the fresh-write channel and triggers
2330    /// replication for each newly-stored chunk.
2331    fn start_fresh_write_drainer(&mut self) {
2332        let Some(mut rx) = self.fresh_write_rx.take() else {
2333            return;
2334        };
2335        let p2p = Arc::clone(&self.p2p_node);
2336        let paid_list = Arc::clone(&self.paid_list);
2337        let config = Arc::clone(&self.config);
2338        let send_semaphore = Arc::clone(&self.send_semaphore);
2339        let possession_tx = self.possession_check_tx.clone();
2340        let shutdown = self.shutdown.clone();
2341
2342        let handle = tokio::spawn(async move {
2343            loop {
2344                tokio::select! {
2345                    () = shutdown.cancelled() => break,
2346                    event = rx.recv() => {
2347                        let Some(event) = event else { break };
2348                        let peers = fresh::replicate_fresh(
2349                            &event.key,
2350                            &event.data,
2351                            &event.payment_proof,
2352                            &p2p,
2353                            &paid_list,
2354                            &config,
2355                            &send_semaphore,
2356                        )
2357                        .await;
2358                        // Schedule the delayed possession check (ADR-0003) for
2359                        // the responsible close-group peers. A closed receiver
2360                        // (engine shutting down) is ignored.
2361                        if !peers.is_empty() {
2362                            let _ = possession_tx.send(possession::PossessionCheckEvent {
2363                                key: event.key,
2364                                peers,
2365                            });
2366                        }
2367                    }
2368                }
2369            }
2370            debug!("Fresh-write drainer shut down");
2371        });
2372        self.task_handles.push(handle);
2373    }
2374
2375    /// Spawn the possession-check scheduler (ADR-0003).
2376    ///
2377    /// Drains scheduled possession-check events and, for each, waits a
2378    /// randomised 5-15 minute settle delay before probing every responsible
2379    /// peer for actual possession. A peer that fails to prove possession or does
2380    /// not answer is penalised at `AuditChallenge` severity.
2381    fn start_possession_check_scheduler(&mut self) {
2382        let Some(mut rx) = self.possession_check_rx.take() else {
2383            return;
2384        };
2385        let p2p = Arc::clone(&self.p2p_node);
2386        let storage = Arc::clone(&self.storage);
2387        let config = Arc::clone(&self.config);
2388        let sync_state = Arc::clone(&self.sync_state);
2389        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2390        let shutdown = self.shutdown.clone();
2391        let detached_task_tracker = self.detached_task_tracker.clone();
2392
2393        let handle = tokio::spawn(async move {
2394            loop {
2395                tokio::select! {
2396                    () = shutdown.cancelled() => break,
2397                    event = rx.recv() => {
2398                        let Some(event) = event else { break };
2399                        // Spawn a per-chunk delayed check so the drain loop
2400                        // keeps pace with the write rate. Each check sleeps the
2401                        // randomised settle delay, then probes every peer.
2402                        let p2p = Arc::clone(&p2p);
2403                        let storage = Arc::clone(&storage);
2404                        let config = Arc::clone(&config);
2405                        let sync_state = Arc::clone(&sync_state);
2406                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2407                        let shutdown = shutdown.clone();
2408                        let delay_min = config.possession_check_delay_min;
2409                        let delay_max = config.possession_check_delay_max;
2410                        detached_task_tracker.spawn(async move {
2411                            let delay = possession::random_delay(delay_min, delay_max);
2412                            // Race shutdown against the whole settle-then-probe
2413                            // sequence, not just the sleep. Once a check starts it
2414                            // may park on the per-target audit coordinator, which
2415                            // has no deadline of its own: with the settle delay
2416                            // inside the branch BODY the select is already resolved,
2417                            // so those waiters would drain only at the probe timeout
2418                            // (roughly `queued / per-target-limit` probes deep) while
2419                            // `detached_task_tracker.wait()` — deliberately unbounded
2420                            // for the LMDB contract — held shutdown open.
2421                            //
2422                            // Dropping this future mid-probe is safe and is the same
2423                            // shape the neighbor-sync round uses: a parked coordinator
2424                            // acquire releases its counted reference via
2425                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2426                            // covered by the storage-quiescence wait in `shutdown`.
2427                            tokio::select! {
2428                                () = shutdown.cancelled() => {}
2429                                () = async {
2430                                    tokio::time::sleep(delay).await;
2431                                    possession::run_possession_check(
2432                                        event.key,
2433                                        event.peers,
2434                                        &p2p,
2435                                        &storage,
2436                                        &config,
2437                                        &sync_state,
2438                                        &audit_challenge_coordinator,
2439                                        &shutdown,
2440                                    )
2441                                    .await;
2442                                } => {}
2443                            }
2444                        });
2445                    }
2446                }
2447            }
2448            debug!("Possession-check scheduler shut down");
2449        });
2450        self.task_handles.push(handle);
2451    }
2452
2453    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2454    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2455    /// as the gossip path, under the same per-peer cooldown and concurrency
2456    /// caps, but with the probability lottery BYPASSED (the lottery governs
2457    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2458    /// deterministic first audit; a peer minting fresh pins faster than the
2459    /// cooldown forfeits the older ones' coverage, never the newest's (the
2460    /// channel surfaces newest pins as they are monetized).
2461    #[allow(clippy::too_many_lines)]
2462    fn start_first_audit_drainer(&mut self) {
2463        let Some(mut rx) = self.monetized_pin_rx.take() else {
2464            return;
2465        };
2466        let gossip_audit = GossipAuditTrigger {
2467            p2p_node: Arc::clone(&self.p2p_node),
2468            config: Arc::clone(&self.config),
2469            recent_provers: Arc::clone(&self.recent_provers),
2470            sync_state: Arc::clone(&self.sync_state),
2471            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2472            detached_task_tracker: self.detached_task_tracker.clone(),
2473            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2474        };
2475        let shutdown = self.shutdown.clone();
2476        let observability = Arc::clone(&self.first_audit_observability);
2477        let self_peer = *self.p2p_node.peer_id();
2478
2479        let handle = tokio::spawn(async move {
2480            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2481            // scheduler. Payments only NOMINATE pins; the token bucket launches
2482            // them at a fixed per-node rate, and durable suppression is stamped
2483            // only at PROMOTION (after an authoritative post-jitter answerability
2484            // + cooldown check), so a cancelled reservation leaves nothing behind.
2485            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2486            // Periodic retry tick so budget/cooldown-deferred pins get retried
2487            // even when no new nomination arrives. `Skip` collapses a backlog.
2488            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2489            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2490            let mut last_summary = Instant::now();
2491            loop {
2492                // The reservation's jitter deadline is a wake source: if a
2493                // reservation is outstanding, sleep until it is due; otherwise
2494                // a far-future deadline effectively disables that arm and only
2495                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2496                // newly reserved (earlier) deadline is honoured next turn.
2497                let promotion_due = scheduler
2498                    .reserved_ready_at()
2499                    .unwrap_or_else(first_audit_far_future);
2500                tokio::select! {
2501                    () = shutdown.cancelled() => break,
2502                    event = rx.recv() => match event {
2503                        Some(e) => {
2504                            observability.received.fetch_add(1, Ordering::Relaxed);
2505                            // Pre-overflow reservation opportunity: before an
2506                            // arrival may displace a DIFFERENT peer, let the
2507                            // queue launch — a successful reservation frees the
2508                            // slot without eviction. One reservation can be
2509                            // outstanding at a time, so this consumes at most
2510                            // one slot per jitter window; arrivals beyond it
2511                            // fall through to random displacement (ADR-0004
2512                            // Amendment 4).
2513                            if scheduler.would_displace(&e) {
2514                                open_first_audit_reservation(
2515                                    &mut scheduler,
2516                                    &gossip_audit.cooldown,
2517                                    &observability,
2518                                )
2519                                .await;
2520                            }
2521                            scheduler.enqueue(e, &observability);
2522                            // Drain a bounded burst so a flood cannot starve the
2523                            // launch phase.
2524                            let mut drained = 1usize;
2525                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2526                                match rx.try_recv() {
2527                                    Ok(e) => {
2528                                        observability.received.fetch_add(1, Ordering::Relaxed);
2529                                        if scheduler.would_displace(&e) {
2530                                            open_first_audit_reservation(
2531                                                &mut scheduler,
2532                                                &gossip_audit.cooldown,
2533                                                &observability,
2534                                            )
2535                                            .await;
2536                                        }
2537                                        scheduler.enqueue(e, &observability);
2538                                        drained += 1;
2539                                    }
2540                                    Err(_) => break,
2541                                }
2542                            }
2543                        }
2544                        None => break,
2545                    },
2546                    _ = tick.tick() => {}
2547                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2548                }
2549
2550                // 1) Promote a due reservation. Resolved after EVERY wake (not
2551                //    only when the timer arm wins) so a continuously-ready `rx`
2552                //    cannot indefinitely delay a due promotion. The authoritative
2553                //    answerability + cooldown check-and-stamp happens here under
2554                //    the shared cooldown write lock, immediately before the send.
2555                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2556                    let promoted = {
2557                        let mut cooldown = gossip_audit.cooldown.write().await;
2558                        scheduler.resolve(
2559                            reservation,
2560                            SystemTime::now(),
2561                            Instant::now(),
2562                            &mut cooldown,
2563                            &observability,
2564                        )
2565                    };
2566                    if let Some((event, inflight_slot)) = promoted {
2567                        debug!(
2568                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2569                            event.peer, hex::encode(event.pin), event.key_count,
2570                            observability.inflight.load(Ordering::Relaxed)
2571                        );
2572                        let trigger = gossip_audit.clone();
2573                        let audit_observability = Arc::clone(&observability);
2574                        // Track the launch so `shutdown()`'s detached drain
2575                        // covers it. This task outlives the drainer loop that
2576                        // spawned it — the loop breaks on the shutdown token
2577                        // while the audit is still awaiting its response — so a
2578                        // bare spawn would let an in-flight subtree audit keep
2579                        // running, and keep its `Arc<P2PNode>`, past the point
2580                        // `shutdown()` claims every engine task has stopped.
2581                        let tracker = trigger.detached_task_tracker.clone();
2582                        tracker.spawn(async move {
2583                            // The jitter already elapsed as the reservation's
2584                            // timer; the slot is held for the audit's duration
2585                            // and released on drop (panic-safe).
2586                            let inflight_slot = inflight_slot;
2587                            let started = Instant::now();
2588                            let credit = storage_commitment_audit::AuditCredit {
2589                                recent_provers: &trigger.recent_provers,
2590                            };
2591                            let result = storage_commitment_audit::run_subtree_audit(
2592                                &trigger.p2p_node,
2593                                &trigger.config,
2594                                &event.peer,
2595                                event.pin,
2596                                event.key_count,
2597                                Some(&credit),
2598                            )
2599                            .await;
2600                            let outcome = first_audit_terminal_outcome(&result);
2601                            match outcome {
2602                                FirstAuditTerminalOutcome::Passed => {
2603                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2604                                }
2605                                FirstAuditTerminalOutcome::Timeout => {
2606                                    audit_observability
2607                                        .timed_out
2608                                        .fetch_add(1, Ordering::Relaxed);
2609                                }
2610                                FirstAuditTerminalOutcome::Failed => {
2611                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2612                                }
2613                                FirstAuditTerminalOutcome::BootstrapClaim => {
2614                                    audit_observability
2615                                        .bootstrap_claims
2616                                        .fetch_add(1, Ordering::Relaxed);
2617                                }
2618                                FirstAuditTerminalOutcome::Idle => {
2619                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2620                                }
2621                                FirstAuditTerminalOutcome::InsufficientKeys => {
2622                                    audit_observability
2623                                        .insufficient_keys
2624                                        .fetch_add(1, Ordering::Relaxed);
2625                                }
2626                            }
2627                            drop(inflight_slot);
2628                            debug!(
2629                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2630                                outcome.as_str(),
2631                                event.peer, hex::encode(event.pin), event.key_count,
2632                                started.elapsed().as_millis(),
2633                                audit_observability.inflight.load(Ordering::Relaxed)
2634                            );
2635                            handle_subtree_audit_result(
2636                                &result,
2637                                &trigger.p2p_node,
2638                                &trigger.sync_state,
2639                                &trigger.recent_provers,
2640                                &trigger.config,
2641                            )
2642                            .await;
2643                        });
2644                    }
2645                }
2646
2647                // 2) Open the single reservation from the pending queue if none
2648                //    is outstanding (read-only cooldown snapshot; the
2649                //    authoritative stamp is at promotion). Serializing
2650                //    reservations preserves per-launch lane alternation and keeps
2651                //    at most one jitter timer live.
2652                open_first_audit_reservation(
2653                    &mut scheduler,
2654                    &gossip_audit.cooldown,
2655                    &observability,
2656                )
2657                .await;
2658
2659                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2660                    // Token-independent hygiene: collect entries that aged past
2661                    // the answerability horizon while the budget gate kept the
2662                    // reserve scan from running, so the summary below reports
2663                    // only live work.
2664                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2665                    if swept > 0 {
2666                        debug!(
2667                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2668                            scheduler.pending_len()
2669                        );
2670                    }
2671                    info!(
2672                        "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={}",
2673                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2674                        observability.received.load(Ordering::Relaxed),
2675                        observability.queued.load(Ordering::Relaxed),
2676                        observability.coalesced.load(Ordering::Relaxed),
2677                        observability.suppressed_lower.load(Ordering::Relaxed),
2678                        observability.duplicates.load(Ordering::Relaxed),
2679                        observability.capacity_evicted.load(Ordering::Relaxed),
2680                        observability.self_target_skipped.load(Ordering::Relaxed),
2681                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2682                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2683                        observability.window_deduped.load(Ordering::Relaxed),
2684                        observability.launched.load(Ordering::Relaxed),
2685                        observability.passed.load(Ordering::Relaxed),
2686                        observability.timed_out.load(Ordering::Relaxed),
2687                        observability.failed.load(Ordering::Relaxed),
2688                        observability.bootstrap_claims.load(Ordering::Relaxed),
2689                        observability.idle.load(Ordering::Relaxed),
2690                        observability.insufficient_keys.load(Ordering::Relaxed),
2691                        observability.outside_answerability_window.load(Ordering::Relaxed),
2692                        scheduler.pending_len(),
2693                        FIRST_AUDIT_PENDING_CAP,
2694                        u8::from(scheduler.has_reservation()),
2695                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2696                        observability.inflight.load(Ordering::Relaxed),
2697                        scheduler.tokens(),
2698                    );
2699                    last_summary = Instant::now();
2700                }
2701            }
2702            debug!("First-audit drainer shut down");
2703        });
2704        self.task_handles.push(handle);
2705    }
2706
2707    #[allow(clippy::too_many_lines)]
2708    fn start_message_handler(&mut self) {
2709        let mut p2p_events = self.p2p_node.subscribe_events();
2710        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2711        let p2p = Arc::clone(&self.p2p_node);
2712        let storage = Arc::clone(&self.storage);
2713        let paid_list = Arc::clone(&self.paid_list);
2714        let payment_verifier = Arc::clone(&self.payment_verifier);
2715        let queues = Arc::clone(&self.queues);
2716        let config = Arc::clone(&self.config);
2717        let shutdown = self.shutdown.clone();
2718        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2719        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2720        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2721        let sync_history = Arc::clone(&self.sync_history);
2722        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2723        let repair_proofs = Arc::clone(&self.repair_proofs);
2724        let sync_trigger = Arc::clone(&self.sync_trigger);
2725        let my_commitment_state = Arc::clone(&self.commitment_state);
2726        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2727        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2728        let recent_provers = Arc::clone(&self.recent_provers);
2729        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2730        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2731        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2732        let sync_state = Arc::clone(&self.sync_state);
2733        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2734        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2735        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2736        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2737        let fetch_responder_admission_semaphore =
2738            Arc::clone(&self.fetch_responder_admission_semaphore);
2739        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2740        let verification_responder_worker_semaphore =
2741            Arc::clone(&self.verification_responder_worker_semaphore);
2742        let verification_responder_admission_semaphore =
2743            Arc::clone(&self.verification_responder_admission_semaphore);
2744        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2745        let neighbor_sync_responder_worker_semaphore =
2746            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2747        let neighbor_sync_responder_admission_semaphore =
2748            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2749        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2750        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2751        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2752        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2753        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2754        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2755        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2756        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2757        let detached_task_tracker = self.detached_task_tracker.clone();
2758        let subtree_round1 = self.subtree_round1.clone();
2759
2760        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2761        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2762        let gossip_audit = GossipAuditTrigger {
2763            p2p_node: Arc::clone(&p2p),
2764            config: Arc::clone(&config),
2765            recent_provers: Arc::clone(&recent_provers),
2766            sync_state: Arc::clone(&sync_state),
2767            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2768            detached_task_tracker: detached_task_tracker.clone(),
2769            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2770        };
2771
2772        let handler_context = ReplicationMessageHandlerContext {
2773            p2p_node: Arc::clone(&p2p),
2774            storage,
2775            paid_list,
2776            payment_verifier,
2777            queues,
2778            config: Arc::clone(&config),
2779            is_bootstrapping,
2780            bootstrap_state,
2781            sync_history,
2782            sync_cycle_epoch,
2783            repair_proofs: Arc::clone(&repair_proofs),
2784            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2785            ever_capable_peers,
2786            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2787            my_commitment_state,
2788            gossip_audit,
2789            audit_responder_semaphore,
2790            audit_responder_inflight,
2791            audit_responder_metrics,
2792            subtree_round1,
2793            fetch_responder_worker_semaphore,
2794            fetch_responder_admission_semaphore,
2795            fetch_responder_inflight,
2796            verification_responder_worker_semaphore,
2797            verification_responder_admission_semaphore,
2798            verification_responder_inflight,
2799            neighbor_sync_responder_worker_semaphore,
2800            neighbor_sync_responder_admission_semaphore,
2801            neighbor_sync_responder_inflight,
2802            fresh_offer_worker_semaphore,
2803            fresh_offer_admission_semaphore,
2804            fresh_offer_responder_inflight,
2805            fresh_offer_in_flight,
2806            paid_notify_worker_semaphore,
2807            paid_notify_admission_semaphore,
2808            paid_notify_responder_inflight,
2809            shutdown: shutdown.clone(),
2810            detached_task_tracker,
2811        };
2812
2813        let (replication_tx, mut replication_rx) =
2814            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2815        let serial_context = handler_context.clone();
2816        let serial_shutdown = shutdown.clone();
2817        let serial_handle = tokio::spawn(async move {
2818            loop {
2819                tokio::select! {
2820                    () = serial_shutdown.cancelled() => break,
2821                    inbound = replication_rx.recv() => {
2822                        let Some(inbound) = inbound else { break };
2823                        let source = inbound.source;
2824                        match handle_replication_message(
2825                            &source,
2826                            inbound.msg,
2827                            &serial_context,
2828                            inbound.received_at,
2829                            inbound.rr_message_id.as_deref(),
2830                        )
2831                        .await
2832                        {
2833                            Ok(()) => {}
2834                            Err(e) => {
2835                                debug!("Replication message from {source} error: {e}");
2836                            }
2837                        }
2838                    }
2839                }
2840            }
2841            debug!("Replication non-audit serial handler shut down");
2842        });
2843        self.task_handles.push(serial_handle);
2844
2845        let handle = tokio::spawn(async move {
2846            loop {
2847                tokio::select! {
2848                    () = shutdown.cancelled() => break,
2849                    event = p2p_events.recv() => {
2850                        let event = match event {
2851                            Ok(event) => event,
2852                            Err(error) => match handle_replication_event_recv_error(&error) {
2853                                ControlFlow::Continue(()) => continue,
2854                                ControlFlow::Break(()) => break,
2855                            },
2856                        };
2857                        let Some((source, payload, inbound_protocol, rr_message_id)) =
2858                            replication_payload_from_event(event)
2859                        else {
2860                            continue;
2861                        };
2862                        let received_at = Instant::now();
2863                        let msg = match ReplicationMessage::decode(&payload) {
2864                            Ok(msg) => msg,
2865                            Err(e) => {
2866                                debug!("Replication message from {source} decode error: {e}");
2867                                continue;
2868                            }
2869                        };
2870                        if !body_matches_protocol(&msg.body, inbound_protocol) {
2871                            debug!(
2872                                "Dropping replication body (variant {}) on protocol \
2873                                 {inbound_protocol}: wrong id for its family \
2874                                 (cross-version or misrouted)",
2875                                msg.body.variant_index()
2876                            );
2877                            continue;
2878                        }
2879                        if let Some(class) = audit_responder_class(&msg.body) {
2880                            handler_context
2881                                .audit_responder_metrics
2882                                .record_received(source, class);
2883                        }
2884                        let inbound = InboundReplicationMessage {
2885                            source,
2886                            msg,
2887                            rr_message_id,
2888                            received_at,
2889                        };
2890                        if matches!(
2891                            inbound.msg.body,
2892                            ReplicationMessageBody::AuditChallenge(_)
2893                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
2894                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
2895                        ) {
2896                            let source = inbound.source;
2897                            match handle_replication_message(
2898                                &source,
2899                                inbound.msg,
2900                                &handler_context,
2901                                inbound.received_at,
2902                                inbound.rr_message_id.as_deref(),
2903                            )
2904                            .await
2905                            {
2906                                Ok(()) => {}
2907                                Err(e) => {
2908                                    debug!("Replication message from {source} error: {e}");
2909                                }
2910                            }
2911                            continue;
2912                        }
2913                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2914                            if dropped.audit_responder_class.is_some() {
2915                                handler_context
2916                                    .audit_responder_metrics
2917                                    .record_serial_queue_drop(dropped.source);
2918                            }
2919                            // Every serial-lane class has protocol recovery: syncs rerun,
2920                            // fetches retry, verification re-asks, and a dropped fresh
2921                            // offer is refilled by neighbor sync (the possession check
2922                            // penalises the absence but never re-offers). Responses are
2923                            // covered by their requester's deadline/retry path. Never run
2924                            // a bulk handler here: event receipt must remain non-blocking.
2925                            warn!(
2926                                message_class = dropped.message_class,
2927                                source = %dropped.source,
2928                                queue_depth = dropped.queue_depth,
2929                                reason = dropped.reason.as_str(),
2930                                "Replication serial-queue message dropped"
2931                            );
2932                        }
2933                    }
2934                    // Gap 4: Topology churn handling (Section 13).
2935                    //
2936                    // The DHT routing table emits KClosestPeersChanged when the
2937                    // K-closest peer set actually changes, which is the precise
2938                    // signal for triggering neighbor sync. This replaces the
2939                    // previous approach of checking every PeerConnected /
2940                    // PeerDisconnected event against the close group.
2941                    dht_event = dht_events.recv() => {
2942                        let dht_event = match dht_event {
2943                            Ok(event) => event,
2944                            Err(RecvError::Lagged(missed)) => {
2945                                // Under heavy churn the broadcast buffer can overflow
2946                                // and drop routing-table events — the moment
2947                                // convergence matters most. A dropped
2948                                // KClosestPeersChanged means its entrants were never
2949                                // queued and its departures were never pruned, so
2950                                // draining priority_order cannot recover either.
2951                                // Resync from ground truth instead: snapshot the
2952                                // current close-peer set, prune pending peers that
2953                                // left it during the lost window (retain_sync_peers,
2954                                // as the normal topology-change path does), and queue
2955                                // every member. Dedup (queue_priority_peers) and
2956                                // per-peer cooldown (select_next_sync_peer) drop peers
2957                                // already queued or recently synced, so only genuine
2958                                // entrants surface.
2959                                warn!(
2960                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
2961                                );
2962                                let self_id = *p2p.peer_id();
2963                                let neighbors = neighbor_sync::snapshot_close_neighbors(
2964                                    &p2p,
2965                                    &self_id,
2966                                    config.neighbor_sync_scope,
2967                                )
2968                                .await;
2969                                let neighbor_set =
2970                                    neighbors.iter().copied().collect::<HashSet<_>>();
2971                                let (requeued, sync_removals) = {
2972                                    let mut state = sync_state.write().await;
2973                                    let sync_removals =
2974                                        state.retain_sync_peers(&neighbor_set);
2975                                    let requeued = state.queue_priority_peers(neighbors);
2976                                    (requeued, sync_removals)
2977                                };
2978                                if sync_removals > 0 {
2979                                    debug!(
2980                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
2981                                    );
2982                                }
2983                                if requeued > 0 {
2984                                    debug!(
2985                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
2986                                    );
2987                                    sync_trigger.notify_one();
2988                                }
2989                                continue;
2990                            }
2991                            Err(RecvError::Closed) => {
2992                                // A closed broadcast channel never yields again;
2993                                // continuing would spin the select! loop forever.
2994                                warn!(
2995                                    "DHT event stream closed on replication branch; stopping message handler"
2996                                );
2997                                break;
2998                            }
2999                        };
3000                        match dht_event {
3001                            DhtNetworkEvent::KClosestPeersChanged { old, new } => {
3002                                let old_peers = old
3003                                    .iter()
3004                                    .take(config.neighbor_sync_scope)
3005                                    .copied()
3006                                    .collect::<HashSet<_>>();
3007                                let new_scoped = new
3008                                    .iter()
3009                                    .take(config.neighbor_sync_scope)
3010                                    .copied()
3011                                    .collect::<Vec<_>>();
3012                                let new_peers =
3013                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3014                                let entrants = new_scoped
3015                                    .iter()
3016                                    .copied()
3017                                    .filter(|peer| !old_peers.contains(peer))
3018                                    .collect::<Vec<_>>();
3019                                let entrant_count = entrants.len();
3020                                let (priority_insertions, sync_removals) = {
3021                                    let mut state = sync_state.write().await;
3022                                    let sync_removals = state.retain_sync_peers(&new_peers);
3023                                    let priority_insertions = state.queue_priority_peers(entrants);
3024                                    (priority_insertions, sync_removals)
3025                                };
3026                                if priority_insertions > 0 {
3027                                    debug!(
3028                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3029                                    );
3030                                } else {
3031                                    debug!(
3032                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3033                                    );
3034                                }
3035                                sync_trigger.notify_one();
3036                            }
3037                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3038                                sync_state.write().await.remove_peer(&peer_id);
3039                                repair_proofs.write().await.remove_peer(&peer_id);
3040                                update_bootstrap_after_peer_removed(
3041                                    &peer_id,
3042                                    &handler_context.bootstrap_state,
3043                                    &handler_context.queues,
3044                                    &handler_context.is_bootstrapping,
3045                                    &bootstrap_complete_notify,
3046                                )
3047                                .await;
3048                                // v12: drop the commitment bytes and the
3049                                // recent-prover credit so a churn / sybil
3050                                // attacker cannot leave behind one
3051                                // StorageCommitment per identity in
3052                                // `last_commitment_by_peer`. Also drop the
3053                                // sig-verify rate-limit timestamp.
3054                                last_commitment_by_peer.write().await.remove(&peer_id);
3055                                recent_provers.write().await.forget_peer(&peer_id);
3056                                sig_verify_attempts.write().await.remove(&peer_id);
3057                                // Same for the gossip-audit cooldown (ADR-0002)
3058                                // and the lottery-attempt window.
3059                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3060                                gossip_lottery_attempts.write().await.remove(&peer_id);
3061                                // The sticky `commitment_capable` flag is
3062                                // preserved orthogonally via
3063                                // `ever_capable_peers` — even after this
3064                                // removal, a re-joining peer continues to
3065                                // be treated as v12-capable rather than
3066                                // legacy (§3 shield).
3067                            }
3068                            _ => {}
3069                        }
3070                    }
3071                }
3072            }
3073            debug!("Replication message handler shut down");
3074        });
3075        self.task_handles.push(handle);
3076    }
3077
3078    fn start_neighbor_sync_loop(&mut self) {
3079        let p2p = Arc::clone(&self.p2p_node);
3080        let storage = Arc::clone(&self.storage);
3081        let paid_list = Arc::clone(&self.paid_list);
3082        let queues = Arc::clone(&self.queues);
3083        let config = Arc::clone(&self.config);
3084        let shutdown = self.shutdown.clone();
3085        let sync_state = Arc::clone(&self.sync_state);
3086        let sync_history = Arc::clone(&self.sync_history);
3087        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3088        let repair_proofs = Arc::clone(&self.repair_proofs);
3089        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3090        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3091        let sync_trigger = Arc::clone(&self.sync_trigger);
3092        let commitment_state = Arc::clone(&self.commitment_state);
3093        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3094        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3095        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3096        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3097        let detached_task_tracker = self.detached_task_tracker.clone();
3098        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3099        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3100        // here too so a peer that only ever answers — never initiates sync —
3101        // is still audited; otherwise it could fully evade auditing.
3102        let gossip_audit = GossipAuditTrigger {
3103            p2p_node: Arc::clone(&p2p),
3104            config: Arc::clone(&config),
3105            recent_provers: Arc::clone(&self.recent_provers),
3106            sync_state: Arc::clone(&sync_state),
3107            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3108            detached_task_tracker,
3109            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3110        };
3111
3112        let handle = tokio::spawn(async move {
3113            loop {
3114                // Park for the periodic tick or an explicit trigger ONLY when no
3115                // priority (topology-change) peers are queued. `sync_trigger` is a
3116                // coalescing `Notify`, so a churn burst that queues many entrants
3117                // produces a single wakeup; parking after draining one batch would
3118                // leave the rest waiting up to a full periodic tick. `priority_order`
3119                // is the durable record of pending work, so drain it back-to-back —
3120                // each round removes the peers it selects (`select_next_sync_peer`),
3121                // so the drain terminates once the queue empties.
3122                if !sync_state.read().await.has_priority_peers() {
3123                    let interval = config.random_neighbor_sync_interval();
3124                    tokio::select! {
3125                        () = shutdown.cancelled() => break,
3126                        () = tokio::time::sleep(interval) => {}
3127                        () = sync_trigger.notified() => {
3128                            debug!("Neighbor sync triggered by topology change");
3129                        }
3130                    }
3131                }
3132                // Wrap the sync round in a select so shutdown cancels
3133                // in-progress network operations rather than waiting for
3134                // the full round to complete.
3135                tokio::select! {
3136                    () = shutdown.cancelled() => break,
3137                    () = run_neighbor_sync_round(
3138                        &p2p,
3139                        &storage,
3140                        &paid_list,
3141                        &queues,
3142                        &config,
3143                        &sync_state,
3144                        &sync_history,
3145                        &sync_cycle_epoch,
3146                        &repair_proofs,
3147                        &is_bootstrapping,
3148                        &bootstrap_state,
3149                        &commitment_state,
3150                        &last_commitment_by_peer,
3151                        &ever_capable_peers,
3152                        &sig_verify_attempts,
3153                        &audit_challenge_coordinator,
3154                        &gossip_audit,
3155                    ) => {}
3156                }
3157            }
3158            debug!("Neighbor sync loop shut down");
3159        });
3160        self.task_handles.push(handle);
3161    }
3162
3163    fn start_self_lookup_loop(&mut self) {
3164        let p2p = Arc::clone(&self.p2p_node);
3165        let config = Arc::clone(&self.config);
3166        let shutdown = self.shutdown.clone();
3167
3168        let handle = tokio::spawn(async move {
3169            loop {
3170                let interval = config.random_self_lookup_interval();
3171                tokio::select! {
3172                    () = shutdown.cancelled() => break,
3173                    () = tokio::time::sleep(interval) => {
3174                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3175                            debug!("Self-lookup failed: {e}");
3176                        }
3177                    }
3178                }
3179            }
3180            debug!("Self-lookup loop shut down");
3181        });
3182        self.task_handles.push(handle);
3183    }
3184
3185    /// Periodic responsible-chunk audit loop (audit #2): every
3186    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3187    /// eligible close peer for the chunks it *should* be storing (by
3188    /// responsibility and prior repair hint), independent of the gossip-triggered
3189    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3190    /// immediately and periodically thereafter.
3191    fn start_audit_loop(&mut self) {
3192        let p2p = Arc::clone(&self.p2p_node);
3193        let storage = Arc::clone(&self.storage);
3194        let config = Arc::clone(&self.config);
3195        let shutdown = self.shutdown.clone();
3196        let sync_history = Arc::clone(&self.sync_history);
3197        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3198        let repair_proofs = Arc::clone(&self.repair_proofs);
3199        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3200        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3201        let sync_state = Arc::clone(&self.sync_state);
3202        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3203
3204        let handle = tokio::spawn(async move {
3205            // Invariant 19: wait for bootstrap to drain before starting audits.
3206            loop {
3207                tokio::select! {
3208                    () = shutdown.cancelled() => return,
3209                    () = tokio::time::sleep(
3210                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3211                    ) => {
3212                        if bootstrap_state.read().await.is_drained() {
3213                            break;
3214                        }
3215                    }
3216                }
3217            }
3218
3219            // Run one audit tick immediately after bootstrap drain.
3220            {
3221                let bootstrapping = *is_bootstrapping.read().await;
3222                let result = {
3223                    let history = sync_history.read().await;
3224                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3225                    audit::audit_tick_with_repair_proofs(
3226                        &p2p,
3227                        &storage,
3228                        &config,
3229                        &history,
3230                        &repair_proofs,
3231                        &audit_challenge_coordinator,
3232                        current_sync_epoch,
3233                        bootstrapping,
3234                    )
3235                    .await
3236                };
3237                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3238            }
3239
3240            // Then run periodically.
3241            loop {
3242                let interval = config.random_audit_tick_interval();
3243                tokio::select! {
3244                    () = shutdown.cancelled() => break,
3245                    () = tokio::time::sleep(interval) => {
3246                        let bootstrapping = *is_bootstrapping.read().await;
3247                        let result = {
3248                            let history = sync_history.read().await;
3249                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3250                            audit::audit_tick_with_repair_proofs(
3251                                &p2p,
3252                                &storage,
3253                                &config,
3254                                &history,
3255                                &repair_proofs,
3256                                &audit_challenge_coordinator,
3257                                current_sync_epoch,
3258                                bootstrapping,
3259                            )
3260                            .await
3261                        };
3262                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3263                    }
3264                }
3265            }
3266            debug!("Audit loop shut down");
3267        });
3268        self.task_handles.push(handle);
3269    }
3270
3271    /// Periodically rebuild + sign + rotate the responder's storage
3272    /// commitment.
3273    ///
3274    /// Phase 3 of the v12 storage-bound audit. Once per
3275    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3276    /// current LMDB key set, builds a Merkle tree (for content-addressed
3277    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3278    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3279    /// into `commitment_state`. Old `previous` slot is dropped by the
3280    /// rotate (per `ResponderCommitmentState::rotate`).
3281    ///
3282    /// Skips if the key set is empty (no commitment to make) — the
3283    /// auditor side falls back to the legacy plain-digest path for
3284    /// peers that have never gossiped a commitment.
3285    fn start_commitment_rotation_loop(&mut self) {
3286        let storage = Arc::clone(&self.storage);
3287        let identity = Arc::clone(&self.identity);
3288        let commitment_state = Arc::clone(&self.commitment_state);
3289        let shutdown = self.shutdown.clone();
3290        let p2p = Arc::clone(&self.p2p_node);
3291        let config = Arc::clone(&self.config);
3292        let sync_trigger = Arc::clone(&self.sync_trigger);
3293        let recent_provers = Arc::clone(&self.recent_provers);
3294
3295        let handle = tokio::spawn(async move {
3296            // Build the first commitment immediately on startup so a
3297            // restarted node can answer commitment-bound audits right
3298            // away — otherwise current() stays None for a full rotation
3299            // interval and audits silently fall back to legacy.
3300            //
3301            // After the first build, trigger an immediate neighbor-sync
3302            // round so the new commitment gossips out within seconds.
3303            // Without this, after a restart remote auditors keep pinning
3304            // the pre-restart (rotated-away) hash until their normal
3305            // sync cadence elapses — up to 1 h in the worst case,
3306            // during which time commitment-bound audits hit "unknown
3307            // commitment hash" -> Idle no-ops.
3308            // ML-DSA signatures are randomized so we cannot reproduce
3309            // the pre-restart hash; the only honest path to recovery
3310            // is fast re-gossip.
3311            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3312            // spawned), so this initial rebuild no-ops when the key set is
3313            // unchanged — preserving the reloaded current pin; otherwise the
3314            // reloaded roots stay answerable as retained slots until their gossip
3315            // TTL lapses. Persistence is handled by the retention-persist loop.
3316            if let Err(e) =
3317                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3318                    .await
3319            {
3320                warn!("Initial commitment build failed: {e}");
3321            } else {
3322                sync_trigger.notify_one();
3323            }
3324            loop {
3325                tokio::select! {
3326                    () = shutdown.cancelled() => break,
3327                    () = tokio::time::sleep(
3328                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3329                    ) => {
3330                        if let Err(e) = rebuild_and_rotate_commitment(
3331                            &storage,
3332                            &identity,
3333                            &commitment_state,
3334                            &p2p,
3335                            &config,
3336                        ).await {
3337                            warn!("Commitment rotation failed: {e}");
3338                        }
3339                        // Piggyback a sweep of expired recent_provers
3340                        // entries on the rotation tick (same cadence,
3341                        // 1 h). is_credited_holder already honours the
3342                        // TTL on read, but the sweep reclaims memory
3343                        // for entries we'll never re-read.
3344                        let dropped = recent_provers.write().await.sweep_expired(
3345                            std::time::Instant::now()
3346                        );
3347                        if dropped > 0 {
3348                            debug!("recent_provers: swept {dropped} expired entries");
3349                        }
3350                    }
3351                }
3352            }
3353            debug!("Commitment rotation loop shut down");
3354        });
3355        self.task_handles.push(handle);
3356    }
3357
3358    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3359    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3360    /// rotations — survives a restart. Flushes once immediately, then every
3361    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3362    fn start_retention_persist_loop(&mut self) {
3363        let commitment_state = Arc::clone(&self.commitment_state);
3364        let retention_path = self.retention_path.clone();
3365        let shutdown = self.shutdown.clone();
3366        let handle = tokio::spawn(async move {
3367            let mut last: Option<Vec<u8>> = None;
3368            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3369            loop {
3370                tokio::select! {
3371                    () = shutdown.cancelled() => {
3372                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3373                            .await;
3374                        break;
3375                    }
3376                    () = tokio::time::sleep(std::time::Duration::from_secs(
3377                        RETENTION_PERSIST_INTERVAL_SECS,
3378                    )) => {
3379                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3380                            .await;
3381                    }
3382                }
3383            }
3384            debug!("Commitment retention persist loop shut down");
3385        });
3386        self.task_handles.push(handle);
3387    }
3388
3389    /// Periodically emit the cumulative replication traffic summaries: the
3390    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3391    /// (V2-684). Both read process-global counter tables maintained by the
3392    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3393    /// state.
3394    fn start_traffic_summary_loop(&mut self) {
3395        let shutdown = self.shutdown.clone();
3396        let handle = tokio::spawn(async move {
3397            loop {
3398                tokio::select! {
3399                    () = shutdown.cancelled() => break,
3400                    () = tokio::time::sleep(std::time::Duration::from_secs(
3401                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3402                    )) => {
3403                        protocol::log_traffic_summary();
3404                        protocol::log_served_peers_summary();
3405                        protocol::log_audit_outcome_summary();
3406                        audit_metrics::log_responder_admission_summary();
3407                    }
3408                }
3409            }
3410            debug!("Replication traffic summary loop shut down");
3411        });
3412        self.task_handles.push(handle);
3413    }
3414
3415    /// Periodically rank remote peers using the shared audit responder pool and
3416    /// report handler-only versus end-to-end latency. Windowed values make a
3417    /// burst visible even after a long-running node has accumulated traffic.
3418    #[cfg(feature = "logging")]
3419    fn start_audit_responder_summary_loop(&mut self) {
3420        let shutdown = self.shutdown.clone();
3421        let metrics = Arc::clone(&self.audit_responder_metrics);
3422        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3423        let handle = tokio::spawn(async move {
3424            let mut window_started = Instant::now();
3425            loop {
3426                tokio::select! {
3427                    () = shutdown.cancelled() => {
3428                        log_audit_responder_summary(
3429                            &metrics,
3430                            &semaphore,
3431                            window_started.elapsed(),
3432                        );
3433                        break;
3434                    }
3435                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3436                        log_audit_responder_summary(
3437                            &metrics,
3438                            &semaphore,
3439                            window_started.elapsed(),
3440                        );
3441                        window_started = Instant::now();
3442                    }
3443                }
3444            }
3445            debug!("Audit responder summary loop shut down");
3446        });
3447        self.task_handles.push(handle);
3448    }
3449
3450    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3451    fn start_fetch_worker(&mut self) {
3452        let p2p = Arc::clone(&self.p2p_node);
3453        let storage = Arc::clone(&self.storage);
3454        let queues = Arc::clone(&self.queues);
3455        let config = Arc::clone(&self.config);
3456        let shutdown = self.shutdown.clone();
3457        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3458        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3459        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3460        let detached_task_tracker = self.detached_task_tracker.clone();
3461        let concurrency = max_parallel_fetch();
3462
3463        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3464
3465        let handle = tokio::spawn(async move {
3466            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3467            // always recover the key — even if the inner task panics.
3468            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3469
3470            loop {
3471                // Fill up to `concurrency` slots from the queue.
3472                {
3473                    let mut q = queues.write().await;
3474                    while in_flight.len() < concurrency {
3475                        let Some(candidate) = q.dequeue_fetch() else {
3476                            break;
3477                        };
3478                        let fetch_key = candidate.key;
3479                        let Some(&source) = candidate.sources.first() else {
3480                            warn!(
3481                                "Fetch candidate {} has no sources; requeueing for verification",
3482                                hex::encode(fetch_key)
3483                            );
3484                            let _ = q.requeue_candidate_for_verification(
3485                                candidate,
3486                                config.verification_request_timeout,
3487                            );
3488                            continue;
3489                        };
3490                        q.start_dequeued_fetch(candidate, source);
3491
3492                        let p2p = Arc::clone(&p2p);
3493                        let storage = Arc::clone(&storage);
3494                        let config = Arc::clone(&config);
3495                        let token = shutdown.clone();
3496                        let tracker = detached_task_tracker.clone();
3497                        in_flight.push(Box::pin(async move {
3498                            // Tracked so shutdown() still awaits the task if
3499                            // this awaiter is dropped (e.g. the worker is
3500                            // aborted): it holds Arc<LmdbStorage> and must
3501                            // not outlive the engine.
3502                            let handle = tracker.spawn(async move {
3503                                // Cancel-aware: abort when the engine shuts down.
3504                                tokio::select! {
3505                                    () = token.cancelled() => FetchOutcome {
3506                                        key: fetch_key,
3507                                        result: FetchResult::SourceFailed,
3508                                    },
3509                                    outcome = execute_single_fetch(
3510                                        p2p, storage, config, fetch_key, source,
3511                                    ) => outcome,
3512                                }
3513                            });
3514                            match handle.await {
3515                                Ok(outcome) => (outcome.key, Some(outcome)),
3516                                Err(e) => {
3517                                    error!(
3518                                        "Fetch task for {} panicked: {e}",
3519                                        hex::encode(fetch_key)
3520                                    );
3521                                    (fetch_key, None)
3522                                }
3523                            }
3524                        }));
3525                    }
3526                } // release queues write lock
3527
3528                if in_flight.is_empty() {
3529                    // No work — wait for new items or shutdown.
3530                    tokio::select! {
3531                        () = shutdown.cancelled() => break,
3532                        () = tokio::time::sleep(
3533                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3534                        ) => continue,
3535                    }
3536                }
3537
3538                // Wait for the next fetch to complete and process the result.
3539                tokio::select! {
3540                    () = shutdown.cancelled() => break,
3541                    Some((key, maybe_outcome)) = in_flight.next() => {
3542                        let mut q = queues.write().await;
3543                        let terminal = if let Some(outcome) = maybe_outcome {
3544                            match apply_fetch_result(
3545                                &mut q,
3546                                &key,
3547                                &outcome.result,
3548                                config.verification_request_timeout,
3549                            ) {
3550                                FetchFollowUp::Terminal => true,
3551                                FetchFollowUp::RequeuedForVerification => false,
3552                                FetchFollowUp::RetryFrom(next_peer) => {
3553                                    // Spawn a new fetch task for the next source.
3554                                    let p2p = Arc::clone(&p2p);
3555                                    let storage = Arc::clone(&storage);
3556                                    let config = Arc::clone(&config);
3557                                    let token = shutdown.clone();
3558                                    let tracker = detached_task_tracker.clone();
3559                                    let fetch_key = key;
3560                                    in_flight.push(Box::pin(async move {
3561                                        // Tracked for the same reason as the
3562                                        // initial fetch spawn above.
3563                                        let handle = tracker.spawn(async move {
3564                                            tokio::select! {
3565                                                () = token.cancelled() => FetchOutcome {
3566                                                    key: fetch_key,
3567                                                    result: FetchResult::SourceFailed,
3568                                                },
3569                                                outcome = execute_single_fetch(
3570                                                    p2p, storage, config, fetch_key, next_peer,
3571                                                ) => outcome,
3572                                            }
3573                                        });
3574                                        match handle.await {
3575                                            Ok(outcome) => (outcome.key, Some(outcome)),
3576                                            Err(e) => {
3577                                                error!(
3578                                                    "Fetch task for {} panicked: {e}",
3579                                                    hex::encode(fetch_key)
3580                                                );
3581                                                (fetch_key, None)
3582                                            }
3583                                        }
3584                                    }));
3585                                    false
3586                                }
3587                            }
3588                        } else {
3589                            // Task panicked — retry verification when this was
3590                            // a verified repair, otherwise reclaim the slot.
3591                            !q.requeue_fetch_for_verification(
3592                                &key,
3593                                config.verification_request_timeout,
3594                            )
3595                        };
3596
3597                        // Shrink bootstrap pending set on terminal exit.
3598                        if terminal {
3599                            drop(q); // release queues lock before acquiring bootstrap_state
3600                            if !bootstrap_state.read().await.is_drained() {
3601                                bootstrap_state.write().await.remove_key(&key);
3602                                let q = queues.read().await;
3603                                if bootstrap::check_bootstrap_drained(
3604                                    &bootstrap_state,
3605                                    &q,
3606                                )
3607                                .await
3608                                {
3609                                    complete_bootstrap(
3610                                        &is_bootstrapping,
3611                                        &bootstrap_complete_notify,
3612                                    ).await;
3613                                }
3614                            }
3615                        }
3616                    }
3617                }
3618            }
3619
3620            // Cancel and drain remaining in-flight fetches on shutdown.
3621            // The CancellationToken is already cancelled by this point, so
3622            // spawned tasks will see cancellation via their select! branches.
3623            while in_flight.next().await.is_some() {}
3624            debug!("Fetch worker shut down");
3625        });
3626        self.task_handles.push(handle);
3627    }
3628
3629    fn start_verification_worker(&mut self) {
3630        let p2p = Arc::clone(&self.p2p_node);
3631        let storage = Arc::clone(&self.storage);
3632        let queues = Arc::clone(&self.queues);
3633        let paid_list = Arc::clone(&self.paid_list);
3634        let config = Arc::clone(&self.config);
3635        let shutdown = self.shutdown.clone();
3636        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3637        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3638        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3639        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3640        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3641        let recent_provers = Arc::clone(&self.recent_provers);
3642
3643        let handle = tokio::spawn(async move {
3644            loop {
3645                tokio::select! {
3646                    () = shutdown.cancelled() => break,
3647                    () = tokio::time::sleep(
3648                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3649                    ) => {
3650                        let ctx = VerificationCycleContext {
3651                            p2p_node: &p2p,
3652                            paid_list: &paid_list,
3653                            storage: &storage,
3654                            queues: &queues,
3655                            config: &config,
3656                            bootstrap_state: &bootstrap_state,
3657                            is_bootstrapping: &is_bootstrapping,
3658                            bootstrap_complete_notify: &bootstrap_complete_notify,
3659                            last_commitment_by_peer: &last_commitment_by_peer,
3660                            ever_capable_peers: &ever_capable_peers,
3661                            recent_provers: &recent_provers,
3662                        };
3663                        run_verification_cycle(ctx).await;
3664                    }
3665                }
3666            }
3667            debug!("Verification worker shut down");
3668        });
3669        self.task_handles.push(handle);
3670    }
3671
3672    /// Gap 3: Run a one-shot bootstrap sync on startup.
3673    ///
3674    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3675    /// (indicating the routing table is populated) before snapshotting
3676    /// close neighbors. Falls back after a timeout so bootstrap nodes
3677    /// (which have no peers and therefore never receive the event) still
3678    /// proceed.
3679    ///
3680    /// After the gate, finds close neighbors, syncs with each in
3681    /// round-robin batches, admits returned hints into the verification
3682    /// pipeline, and tracks discovered keys for bootstrap drain detection.
3683    #[allow(clippy::too_many_lines)]
3684    fn start_bootstrap_sync(
3685        &mut self,
3686        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3687    ) {
3688        let p2p = Arc::clone(&self.p2p_node);
3689        let storage = Arc::clone(&self.storage);
3690        let paid_list = Arc::clone(&self.paid_list);
3691        let queues = Arc::clone(&self.queues);
3692        let config = Arc::clone(&self.config);
3693        let shutdown = self.shutdown.clone();
3694        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3695        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3696        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3697        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3698        let repair_proofs = Arc::clone(&self.repair_proofs);
3699        let my_commitment_state = Arc::clone(&self.commitment_state);
3700        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3701        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3702        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3703
3704        let handle = tokio::spawn(async move {
3705            // Wait for DHT bootstrap to complete before snapshotting
3706            // neighbors. The routing table is empty until saorsa-core
3707            // finishes its FIND_NODE rounds and bucket refreshes.
3708            let gate = bootstrap::wait_for_bootstrap_complete(
3709                dht_events,
3710                config.bootstrap_complete_timeout_secs,
3711                &shutdown,
3712            )
3713            .await;
3714
3715            if gate == bootstrap::BootstrapGateResult::Shutdown {
3716                return;
3717            }
3718
3719            let self_id = *p2p.peer_id();
3720            let neighbors =
3721                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3722                    .await;
3723
3724            if neighbors.is_empty() {
3725                info!("Bootstrap sync: no close neighbors found, marking drained");
3726                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3727                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3728                return;
3729            }
3730
3731            let neighbor_count = neighbors.len();
3732            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3733
3734            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3735            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3736                if shutdown.is_cancelled() {
3737                    break;
3738                }
3739
3740                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3741                    batch,
3742                    &storage,
3743                    &paid_list,
3744                    &p2p,
3745                    config.close_group_size,
3746                    config.paid_list_close_group_size,
3747                )
3748                .await;
3749
3750                // Keep the batch outstanding until every response has been
3751                // admitted and bootstrap accounting is updated. The verification
3752                // worker uses this counter as a batch barrier, so it cannot race
3753                // the source aggregation below.
3754                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3755                let bootstrapping = *is_bootstrapping.read().await;
3756
3757                let sync_futures = batch.iter().map(|peer| {
3758                    let peer = *peer;
3759                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3760                    // Atomically snapshot + mark-gossiped for each emitted
3761                    // bootstrap request so we remain answerable for it.
3762                    let commitment = my_commitment_state
3763                        .current_for_gossip()
3764                        .map(|binding| binding.commitment().clone());
3765                    let p2p = &p2p;
3766                    let config = &config;
3767                    async move {
3768                        let outcome = neighbor_sync::sync_with_peer_with_hints(
3769                            &peer,
3770                            p2p,
3771                            config,
3772                            bootstrapping,
3773                            hints,
3774                            commitment,
3775                        )
3776                        .await;
3777                        (peer, outcome)
3778                    }
3779                });
3780                let completed = join_all(sync_futures).await;
3781
3782                // Process response metadata before exposing any of this batch's
3783                // hints to verification.
3784                for (peer, outcome) in &completed {
3785                    if let Some(outcome) = outcome {
3786                        // Ingest the peer's piggybacked commitment from the
3787                        // response (same verification as the request path).
3788                        // Bootstrap is the FIRST gossip we receive from most
3789                        // peers, so this populates last_commitment_by_peer.
3790                        //
3791                        // We intentionally do NOT trigger a gossip-audit here:
3792                        // during bootstrap this node may itself still be
3793                        // bootstrapping (audits are gated on that), and the
3794                        // close-group/RT view is not yet stable. The peer is
3795                        // audited on the first STEADY-STATE neighbor-sync round
3796                        // after bootstrap drains (request + response paths both
3797                        // trigger), which is within one sync cycle — so caching
3798                        // the commitment here is sufficient and there is no
3799                        // coverage gap (ADR-0002).
3800                        ingest_peer_commitment(
3801                            peer,
3802                            outcome.response.commitment.as_ref(),
3803                            &p2p,
3804                            &last_commitment_by_peer,
3805                            &ever_capable_peers,
3806                            &sig_verify_attempts,
3807                        )
3808                        .await; // sig_verify_attempts in scope from line ~1080
3809
3810                        if !outcome.response.bootstrapping {
3811                            record_sent_replica_hints(
3812                                peer,
3813                                &outcome.sent_replica_hints,
3814                                &repair_proofs,
3815                                &sync_cycle_epoch,
3816                            )
3817                            .await;
3818                        }
3819                    }
3820                }
3821
3822                let pending_keys: HashSet<XorName> = {
3823                    let q = queues.read().await;
3824                    q.pending_keys().into_iter().collect()
3825                };
3826                let admission_futures = completed.iter().map(|(_, outcome)| async {
3827                    match outcome {
3828                        Some(outcome) if !outcome.response.bootstrapping => Some(
3829                            admission::admit_hints(
3830                                &self_id,
3831                                &outcome.response.replica_hints,
3832                                &outcome.response.paid_hints,
3833                                &p2p,
3834                                &config,
3835                                &storage,
3836                                &paid_list,
3837                                &pending_keys,
3838                            )
3839                            .await,
3840                        ),
3841                        _ => None,
3842                    }
3843                });
3844                let admitted = join_all(admission_futures).await;
3845
3846                // Queue every peer's admitted hints under one write lock. Once
3847                // released, source-count ordering sees the complete batch.
3848                let (batch_outcomes, batch_discovered) = {
3849                    let mut q = queues.write().await;
3850                    let outcomes = completed
3851                        .iter()
3852                        .zip(admitted)
3853                        .filter_map(|((peer, _), admitted)| {
3854                            admitted.map(|admitted| {
3855                                (
3856                                    *peer,
3857                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
3858                                )
3859                            })
3860                        })
3861                        .collect::<Vec<_>>();
3862                    let live_discovered = outcomes
3863                        .iter()
3864                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3865                        .filter(|key| q.contains_key(key))
3866                        .collect::<HashSet<_>>();
3867                    (outcomes, live_discovered)
3868                };
3869
3870                publish_bootstrap_admission_outcomes(
3871                    &bootstrap_state,
3872                    &batch_outcomes,
3873                    &batch_discovered,
3874                )
3875                .await;
3876
3877                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3878            }
3879
3880            // Check drain condition.
3881            {
3882                let q = queues.read().await;
3883                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3884                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3885                }
3886            }
3887
3888            info!("Bootstrap sync completed");
3889        });
3890        self.task_handles.push(handle);
3891    }
3892}
3893
3894// ===========================================================================
3895// Free functions for background tasks
3896// ===========================================================================
3897
3898#[cfg(feature = "logging")]
3899fn log_audit_responder_summary(
3900    metrics: &AuditResponderMetrics,
3901    semaphore: &Semaphore,
3902    window: Duration,
3903) {
3904    let snapshot = metrics.take_snapshot();
3905    if snapshot.origins.is_empty() {
3906        return;
3907    }
3908
3909    let total = snapshot.total;
3910    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3911        total.received_by_class;
3912    let global_inflight =
3913        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
3914    info!(
3915        target: "ant_node::replication::audit_responder",
3916        window_ms = window.as_millis(),
3917        source_count = snapshot.origins.len(),
3918        received = total.received(),
3919        digest_received,
3920        subtree_received,
3921        byte_received,
3922        commitment_pin_received,
3923        admitted = total.admitted,
3924        global_pool_drops = total.global_pool_drops,
3925        per_peer_cap_drops = total.per_peer_cap_drops,
3926        serial_queue_drops = total.serial_queue_drops,
3927        completed = total.completed,
3928        send_failures = total.send_failures,
3929        processing_avg_ms = total.processing_avg_ms(),
3930        processing_max_ms = total.processing_max_ms,
3931        total_avg_ms = total.total_avg_ms(),
3932        total_max_ms = total.total_max_ms,
3933        global_inflight,
3934        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
3935        peak_global_inflight = total.peak_global_inflight,
3936        "Audit responder summary"
3937    );
3938
3939    for (index, origin) in snapshot
3940        .origins
3941        .iter()
3942        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
3943        .enumerate()
3944    {
3945        let Some(source) = origin.source else {
3946            continue;
3947        };
3948        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
3949            origin.received_by_class;
3950        info!(
3951            target: "ant_node::replication::audit_responder",
3952            rank = index + 1,
3953            source = %source,
3954            received = origin.received(),
3955            digest_received,
3956            subtree_received,
3957            byte_received,
3958            commitment_pin_received,
3959            admitted = origin.admitted,
3960            global_pool_drops = origin.global_pool_drops,
3961            per_peer_cap_drops = origin.per_peer_cap_drops,
3962            serial_queue_drops = origin.serial_queue_drops,
3963            completed = origin.completed,
3964            send_failures = origin.send_failures,
3965            processing_avg_ms = origin.processing_avg_ms(),
3966            processing_max_ms = origin.processing_max_ms,
3967            total_avg_ms = origin.total_avg_ms(),
3968            total_max_ms = origin.total_max_ms,
3969            peak_global_inflight = origin.peak_global_inflight,
3970            peak_peer_inflight = origin.peak_peer_inflight,
3971            "Audit responder top origin"
3972        );
3973    }
3974}
3975
3976/// Which ceiling rejected an audit-responder admission attempt.
3977///
3978/// Stable, machine-readable so a production log-scrape can bucket drops by
3979/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
3980/// single opaque "capacity reached" line; this splits the two distinct causes
3981/// so the next such investigation can tell a global-pool exhaustion (the whole
3982/// node is saturated) from a per-peer cap hit (one source is self-throttling)
3983/// without re-instrumenting.
3984///
3985/// This branch runs a SINGLE shared audit-responder pool for all challenge
3986/// kinds (responsible / subtree / byte), so there is no separate slow/fast
3987/// pool to distinguish here — the `kind=` log field already separates the
3988/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
3989/// dedicated slow pool is later split out, add its variants here.
3990#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3991enum ResponderRejectReason {
3992    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
3993    /// free; the per-peer cap was not the binding constraint.
3994    GlobalPoolFull,
3995    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
3996    /// share, so the global permit was never attempted.
3997    PerPeerCapFull,
3998}
3999
4000impl ResponderRejectReason {
4001    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4002    /// frozen — production log tooling greps for them.
4003    fn as_str(self) -> &'static str {
4004        match self {
4005            Self::GlobalPoolFull => "global_pool_full",
4006            Self::PerPeerCapFull => "per_peer_cap_full",
4007        }
4008    }
4009}
4010
4011impl From<ResponderRejectReason> for AuditResponderDropReason {
4012    fn from(reason: ResponderRejectReason) -> Self {
4013        match reason {
4014            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4015            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4016        }
4017    }
4018}
4019
4020impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4021    fn from(reason: ResponderRejectReason) -> Self {
4022        match reason {
4023            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4024            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4025        }
4026    }
4027}
4028
4029/// Cumulative fresh-offer admission refusals in this process.
4030///
4031/// **Expected value in healthy operation is zero.** A node that refuses a
4032/// legitimate fresh offer does not merely shed load: the sender transmits
4033/// offers one-way and never reads the refusal, so the chunk's absence
4034/// resurfaces at the sender's delayed possession check and is charged to the
4035/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4036/// means the node is either under-provisioned for its offered load or its
4037/// admission share is mis-sized — and is accruing unearned trust damage either
4038/// way. Operators should alarm on any sustained non-zero rate.
4039///
4040/// Process-global rather than per-engine, which is exactly right in production
4041/// (one node per process) and adequate in multi-node test harnesses, where the
4042/// useful assertion is that *no* node in the fleet refused.
4043#[must_use]
4044pub fn fresh_offer_admission_refusals() -> u64 {
4045    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4046}
4047
4048/// Cumulative paid-list notification admission refusals in this process.
4049///
4050/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4051/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4052/// paid-list evidence outright rather than pushing work back onto a requester.
4053#[must_use]
4054pub fn paid_notify_admission_refusals() -> u64 {
4055    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4056}
4057
4058/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4059///
4060/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4061/// different things: this one says the node was saturated across all sources
4062/// and is genuinely under-provisioned for its offered load.
4063#[must_use]
4064pub fn fresh_offer_refusals_global_pool() -> u64 {
4065    audit_metrics::responder_admission_drops_by_ceiling(
4066        ReplicationResponderClass::FreshOffer,
4067        ResponderAdmissionCeiling::GlobalPool,
4068    )
4069}
4070
4071/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4072///
4073/// For fresh offers this usually indicts the *share's size* rather than the
4074/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4075/// node handling a client's PUT and fanning it out — so a share sized for
4076/// request/response traffic will refuse ordinary uploads.
4077#[must_use]
4078pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4079    audit_metrics::responder_admission_drops_by_ceiling(
4080        ReplicationResponderClass::FreshOffer,
4081        ResponderAdmissionCeiling::PerPeerShare,
4082    )
4083}
4084
4085/// Why an audit-responder admission attempt failed, with the decision-time
4086/// capacity counters that let a drop be logged with full context.
4087///
4088/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4089/// decision was made (the two ceilings are read under different locks, so they
4090/// are not a single atomic view), but they are exact enough to tell a saturated
4091/// node from a single self-throttling flooder.
4092#[derive(Debug, Clone, Copy)]
4093struct ResponderAdmissionFailure {
4094    reason: ResponderRejectReason,
4095    /// Global permits in use across the whole engine at decision time.
4096    global_inflight: usize,
4097    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4098    global_limit: usize,
4099    /// In-flight audit responders already held for `source` at decision time.
4100    peer_inflight: u32,
4101    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4102    peer_limit: u32,
4103}
4104
4105impl fmt::Display for ResponderAdmissionFailure {
4106    /// Renders the stable `reason=... global_inflight=... global_limit=...
4107    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4109        write!(
4110            f,
4111            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4112            self.reason.as_str(),
4113            self.global_inflight,
4114            self.global_limit,
4115            self.peer_inflight,
4116            self.peer_limit,
4117        )
4118    }
4119}
4120
4121/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4122/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4123/// spawned task ties both bounds to the task's exact lifetime — no manual
4124/// decrement to forget on an early return or panic.
4125struct ResponderGuard {
4126    _permit: tokio::sync::OwnedSemaphorePermit,
4127    _peer_slot: PeerResponderSlot,
4128    global_inflight: usize,
4129    peer_inflight: u32,
4130}
4131
4132type AuditResponderGuard = ResponderGuard;
4133type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4134
4135/// Provisional or admitted per-peer responder slot.
4136///
4137/// The slot is claimed before the global permit is attempted. Keeping that
4138/// claim under RAII means cancellation while rolling a failed admission back
4139/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4140/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4141struct PeerResponderSlot {
4142    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4143    peer: PeerId,
4144}
4145
4146#[derive(Clone)]
4147struct ReplicationMessageHandlerContext {
4148    p2p_node: Arc<P2PNode>,
4149    storage: Arc<LmdbStorage>,
4150    paid_list: Arc<PaidList>,
4151    payment_verifier: Arc<PaymentVerifier>,
4152    queues: Arc<RwLock<ReplicationQueues>>,
4153    config: Arc<ReplicationConfig>,
4154    is_bootstrapping: Arc<RwLock<bool>>,
4155    bootstrap_state: Arc<RwLock<BootstrapState>>,
4156    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4157    sync_cycle_epoch: Arc<RwLock<u64>>,
4158    repair_proofs: Arc<RwLock<RepairProofs>>,
4159    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4160    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4161    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4162    my_commitment_state: Arc<ResponderCommitmentState>,
4163    gossip_audit: GossipAuditTrigger,
4164    audit_responder_semaphore: Arc<Semaphore>,
4165    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4166    audit_responder_metrics: Arc<AuditResponderMetrics>,
4167    subtree_round1: SubtreeRound1Limiter,
4168    fetch_responder_worker_semaphore: Arc<Semaphore>,
4169    fetch_responder_admission_semaphore: Arc<Semaphore>,
4170    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4171    verification_responder_worker_semaphore: Arc<Semaphore>,
4172    verification_responder_admission_semaphore: Arc<Semaphore>,
4173    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4174    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4175    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4176    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4177    fresh_offer_worker_semaphore: Arc<Semaphore>,
4178    fresh_offer_admission_semaphore: Arc<Semaphore>,
4179    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4180    fresh_offer_in_flight: FreshOfferInFlight,
4181    paid_notify_worker_semaphore: Arc<Semaphore>,
4182    paid_notify_admission_semaphore: Arc<Semaphore>,
4183    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4184    /// The engine's shutdown token, for detached responder work.
4185    ///
4186    /// Workers on [`Self::detached_task_tracker`] race this around their
4187    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4188    /// where dropping the awaiter would detach a live transaction. This is
4189    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4190    /// terminate: the wait stays safe because it is now guaranteed finite.
4191    shutdown: CancellationToken,
4192    /// Shared tracker for detached work so `shutdown()` can await release of
4193    /// storage and P2P resources after all producer tasks have stopped.
4194    detached_task_tracker: TaskTracker,
4195}
4196
4197struct InboundReplicationMessage {
4198    source: PeerId,
4199    msg: ReplicationMessage,
4200    rr_message_id: Option<String>,
4201    received_at: Instant,
4202}
4203
4204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4205enum SerialQueueDropReason {
4206    Full,
4207    Closed,
4208}
4209
4210#[cfg(feature = "logging")]
4211impl SerialQueueDropReason {
4212    const fn as_str(self) -> &'static str {
4213        match self {
4214            Self::Full => "full",
4215            Self::Closed => "closed",
4216        }
4217    }
4218}
4219
4220#[derive(Debug, Clone, Copy)]
4221#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4222struct SerialQueueDrop {
4223    source: PeerId,
4224    message_class: &'static str,
4225    audit_responder_class: Option<AuditResponderClass>,
4226    queue_depth: usize,
4227    reason: SerialQueueDropReason,
4228}
4229
4230fn try_enqueue_serial_message(
4231    sender: &mpsc::Sender<InboundReplicationMessage>,
4232    inbound: InboundReplicationMessage,
4233) -> std::result::Result<(), SerialQueueDrop> {
4234    let source = inbound.source;
4235    let message_class = replication_message_class(&inbound.msg.body);
4236    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4237    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4238    sender.try_send(inbound).map_err(|error| {
4239        let (reason, dropped) = match error {
4240            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4241            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4242        };
4243        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4244        SerialQueueDrop {
4245            source,
4246            message_class,
4247            audit_responder_class,
4248            queue_depth,
4249            reason,
4250        }
4251    })
4252}
4253
4254const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4255    match body {
4256        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4257        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4258        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4259        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4260        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4261        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4262        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4263        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4264        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4265        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4266        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4267        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4268        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4269        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4270        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4271        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4272        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4273    }
4274}
4275
4276const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4277    match body {
4278        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4279        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4280        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4281        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4282        _ => None,
4283    }
4284}
4285
4286impl AuditResponderClass {
4287    const fn per_peer_limit(self) -> u32 {
4288        match self {
4289            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4290            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4291        }
4292    }
4293}
4294
4295fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4296    match error {
4297        RecvError::Lagged(missed) => {
4298            audit_metrics::record_replication_event_lagged(*missed);
4299            warn!(
4300                "Missed {missed} P2P events on replication branch (broadcast lag); \
4301                 replication messages may have been dropped before dispatch"
4302            );
4303            ControlFlow::Continue(())
4304        }
4305        RecvError::Closed => {
4306            // A closed broadcast channel never yields again, so the branch
4307            // would otherwise be immediately ready on every select! iteration.
4308            warn!("P2P event stream closed on replication branch; stopping message handler");
4309            ControlFlow::Break(())
4310        }
4311    }
4312}
4313
4314fn replication_payload_from_event(
4315    event: P2PEvent,
4316) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4317    let P2PEvent::Message {
4318        topic,
4319        source: Some(source),
4320        data,
4321        ..
4322    } = event
4323    else {
4324        return None;
4325    };
4326
4327    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4328    if !is_rr {
4329        return Some((source, data, matched_id, None));
4330    }
4331    if is_rr {
4332        return P2PNode::parse_request_envelope(&data)
4333            .filter(|(_, is_resp, _)| !is_resp)
4334            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4335    }
4336    None
4337}
4338
4339impl Drop for PeerResponderSlot {
4340    fn drop(&mut self) {
4341        // Decrement (and prune to keep the map bounded) without blocking the
4342        // async runtime: a short lock on a tiny map.
4343        //
4344        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4345        // with no spawn. Otherwise defer to a task — but only if a runtime is
4346        // actually current, so `Drop` during shutdown (no runtime) can never
4347        // panic. A missed decrement at shutdown is harmless: the whole map is
4348        // being dropped with the engine.
4349        let peer = self.peer;
4350        if let Ok(mut map) = self.inflight.try_write() {
4351            if let Some(n) = map.get_mut(&peer) {
4352                *n = n.saturating_sub(1);
4353                if *n == 0 {
4354                    map.remove(&peer);
4355                }
4356            }
4357            return;
4358        }
4359        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4360            let inflight = Arc::clone(&self.inflight);
4361            handle.spawn(async move {
4362                let mut map = inflight.write().await;
4363                if let Some(n) = map.get_mut(&peer) {
4364                    *n = n.saturating_sub(1);
4365                    if *n == 0 {
4366                        map.remove(&peer);
4367                    }
4368                }
4369            });
4370        }
4371    }
4372}
4373
4374/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4375/// and then a global permit. The limits are parameters so independent responder
4376/// classes can reuse the same flood-fair admission and cancellation semantics.
4377async fn admit_bounded_responder(
4378    semaphore: &Arc<Semaphore>,
4379    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4380    source: &PeerId,
4381    global_limit: usize,
4382    peer_limit: u32,
4383) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4384    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4385
4386    let admitted_peer_inflight = {
4387        let mut map = inflight.write().await;
4388        let entry = map.entry(*source).or_insert(0);
4389        if *entry >= peer_limit {
4390            let peer_inflight = *entry;
4391            drop(map);
4392            return Err(ResponderAdmissionFailure {
4393                reason: ResponderRejectReason::PerPeerCapFull,
4394                global_inflight: global_inflight(semaphore),
4395                global_limit,
4396                peer_inflight,
4397                peer_limit,
4398            });
4399        }
4400        *entry += 1;
4401        *entry
4402    };
4403
4404    let peer_slot = PeerResponderSlot {
4405        inflight: Arc::clone(inflight),
4406        peer: *source,
4407    };
4408    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4409        return Err(ResponderAdmissionFailure {
4410            reason: ResponderRejectReason::GlobalPoolFull,
4411            global_inflight: global_inflight(semaphore),
4412            global_limit,
4413            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4414            peer_limit,
4415        });
4416    };
4417
4418    Ok(ResponderGuard {
4419        _permit: permit,
4420        _peer_slot: peer_slot,
4421        global_inflight: global_inflight(semaphore),
4422        peer_inflight: admitted_peer_inflight,
4423    })
4424}
4425
4426/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4427struct SubtreeSession {
4428    commitment_hash: [u8; 32],
4429    nonce: [u8; 32],
4430    inserted: Instant,
4431}
4432
4433/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4434/// read and hash, refilled continuously at
4435/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4436/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4437///
4438/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4439/// identity may ask, so it is refilled by acquiring more identities; this is
4440/// charged for work done regardless of who asked, so it is not.
4441///
4442/// Charged after the fact, with the bytes the proof actually covered: the cost
4443/// of a request is not known until the pinned commitment has been resolved and
4444/// its subtree selected, both of which happen inside the handler. Admission
4445/// therefore asks only whether the balance is positive, and a proof that costs
4446/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4447/// Carrying the debt is what makes the bound real: without it a maximal proof
4448/// would cost the same as a trivial one, since either way the next request only
4449/// has to wait for the balance to climb back above zero. With it, sustained
4450/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4451/// admitted proportionally less often.
4452struct Round1WorkBudget {
4453    /// Signed, so an over-large proof leaves debt to work off.
4454    balance: i64,
4455    last_refill: Instant,
4456}
4457
4458impl Round1WorkBudget {
4459    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4460    /// for longer than the burst takes to refill.
4461    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4462    /// Nanoseconds per second, for the sub-second part of a refill.
4463    const NANOS_PER_SEC: i64 = 1_000_000_000;
4464
4465    fn new() -> Self {
4466        Self {
4467            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4468            last_refill: Instant::now(),
4469        }
4470    }
4471
4472    /// Add the tokens accrued since the last touch, capped at the burst size.
4473    fn refill(&mut self, now: Instant) {
4474        let elapsed = now.saturating_duration_since(self.last_refill);
4475        self.last_refill = now;
4476        let whole_secs = i64::try_from(elapsed.as_secs())
4477            .unwrap_or(i64::MAX)
4478            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4479        let sub_sec = i64::from(elapsed.subsec_nanos())
4480            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4481            / Self::NANOS_PER_SEC;
4482        self.balance = self
4483            .balance
4484            .saturating_add(whole_secs.saturating_add(sub_sec))
4485            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4486    }
4487
4488    /// Whether budget remains for a new round-1 proof.
4489    fn has_budget(&mut self, now: Instant) -> bool {
4490        self.refill(now);
4491        self.balance > 0
4492    }
4493
4494    /// Charge `bytes` of completed proof work, carrying debt down to
4495    /// [`Self::MAX_DEBT`].
4496    fn charge(&mut self, bytes: i64, now: Instant) {
4497        self.refill(now);
4498        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4499    }
4500}
4501
4502/// Resource controls for the HEAVY subtree-audit round 1: a tight
4503/// admission pool separate from the light responsible/slice audits, a per-peer
4504/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4505/// challenge is only served after a matching round 1.
4506///
4507/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4508/// bounds not keyed by peer identity, and so the only one that bounds sustained
4509/// work rather than concurrency or per-identity frequency.
4510#[derive(Clone)]
4511struct SubtreeRound1Limiter {
4512    semaphore: Arc<Semaphore>,
4513    /// Global ceiling on concurrent round-1 proofs (config-driven;
4514    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4515    /// semaphore because the per-peer admission helper needs the same number.
4516    max_concurrent: usize,
4517    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4518    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4519    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4520    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4521    cooldown_interval: Duration,
4522    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4523    /// Identity-independent ceiling on sustained round-1 work.
4524    work: Arc<RwLock<Round1WorkBudget>>,
4525}
4526
4527impl SubtreeRound1Limiter {
4528    /// `max_concurrent` of 0 would wedge the responder into refusing every
4529    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4530    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4531    /// rather than to off.
4532    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4533        let max_concurrent = max_concurrent.max(1);
4534        Self {
4535            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4536            max_concurrent,
4537            inflight: Arc::new(RwLock::new(HashMap::new())),
4538            cooldown: Arc::new(RwLock::new(HashMap::new())),
4539            cooldown_interval,
4540            sessions: Arc::new(RwLock::new(HashMap::new())),
4541            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4542        }
4543    }
4544
4545    /// Charge completed round-1 proof work against the responder-wide budget.
4546    async fn charge_work(&self, content_bytes: i64) {
4547        self.work
4548            .write()
4549            .await
4550            .charge(content_bytes, Instant::now());
4551    }
4552
4553    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4554    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4555    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4556    /// drops the challenge (the remote auditor applies its own graced-timeout
4557    /// policy).
4558    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4559        let guard = admit_bounded_responder(
4560            &self.semaphore,
4561            &self.inflight,
4562            source,
4563            self.max_concurrent,
4564            MAX_SUBTREE_ROUND1_PER_PEER,
4565        )
4566        .await
4567        .ok()?;
4568        // Checked before the per-peer cooldown is stamped, so a peer refused for
4569        // want of budget is not also charged its next allowance.
4570        if !self.work.write().await.has_budget(Instant::now()) {
4571            return None; // guard drops here, releasing the permit + slot
4572        }
4573        let now = Instant::now();
4574        let mut cooldown = self.cooldown.write().await;
4575        if let Some(&last) = cooldown.get(source) {
4576            if now.duration_since(last) < self.cooldown_interval {
4577                return None; // guard drops here, releasing the permit + slot
4578            }
4579        }
4580        // Evict lapsed entries (their cooldown has expired, so they no longer
4581        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4582        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4583        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4584            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4585                cooldown.remove(&oldest);
4586            }
4587        }
4588        cooldown.insert(*source, now);
4589        Some(guard)
4590    }
4591
4592    /// Record a single-use session once a round-1 proof is built and about to be
4593    /// sent, so the matching round 2 is admitted exactly once.
4594    async fn open_session(
4595        &self,
4596        source: PeerId,
4597        challenge_id: u64,
4598        commitment_hash: [u8; 32],
4599        nonce: [u8; 32],
4600    ) {
4601        let now = Instant::now();
4602        let mut sessions = self.sessions.write().await;
4603        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4604        if sessions.len() >= MAX_SUBTREE_SESSIONS {
4605            if let Some(oldest) = sessions
4606                .iter()
4607                .min_by_key(|(_, e)| e.inserted)
4608                .map(|(k, _)| *k)
4609            {
4610                sessions.remove(&oldest);
4611            }
4612        }
4613        sessions.insert(
4614            (source, challenge_id),
4615            SubtreeSession {
4616                commitment_hash,
4617                nonce,
4618                inserted: now,
4619            },
4620        );
4621    }
4622
4623    /// Atomically consume the round-2 session for this exchange. `true` iff a
4624    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4625    /// existed (and is now removed); a miss silently drops round 2 to the graced
4626    /// timeout lane (sessions are ephemeral and can be lost across a restart).
4627    async fn consume_session(
4628        &self,
4629        source: &PeerId,
4630        challenge_id: u64,
4631        commitment_hash: &[u8; 32],
4632        nonce: &[u8; 32],
4633    ) -> bool {
4634        let mut sessions = self.sessions.write().await;
4635        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4636            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4637                && &e.commitment_hash == commitment_hash
4638                && &e.nonce == nonce
4639        });
4640        if matches {
4641            sessions.remove(&(*source, challenge_id));
4642        }
4643        matches
4644    }
4645}
4646
4647/// Outcome of admitting a round-2 slice challenge.
4648enum SliceAdmission {
4649    /// Admitted: the guard holds the global permit and the per-peer slot, and
4650    /// the single-use round-1 session has been consumed.
4651    Admitted(AuditResponderGuard),
4652    /// Refused at a responder ceiling. The round-1 session is left INTACT.
4653    Capacity(AuditResponderAdmissionFailure),
4654    /// No live round-1 session matched this challenge.
4655    NoSession,
4656}
4657
4658/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4659/// the single-use round-1 session.
4660///
4661/// The order is the point: a single-use token must not be spent on work that is
4662/// then refused. Consuming first and testing admission second leaves the session
4663/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4664/// even in principle.
4665///
4666/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4667/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4668/// auditor does not currently re-send round 2 within an audit. The preserved
4669/// session is therefore not yet *recovering* an audit — it keeps a refusal
4670/// truthful (temporary means temporary) and keeps the invariant available for a
4671/// retry, rather than baking "capacity drop is permanent" into the state
4672/// machine. If an application-level retry is ruled out for good, this ordering
4673/// still costs nothing over the alternative.
4674///
4675/// Cost of the ordering: the permit and per-peer slot are held across the
4676/// session probe, which is one in-memory map lookup and no chunk work. The
4677/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4678/// share it could already occupy with well-formed ones, so the admission
4679/// surface is unchanged.
4680async fn admit_slice_challenge(
4681    semaphore: &Arc<Semaphore>,
4682    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4683    round1: &SubtreeRound1Limiter,
4684    source: &PeerId,
4685    challenge: &protocol::SubtreeSliceChallenge,
4686) -> SliceAdmission {
4687    let guard =
4688        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4689            Ok(guard) => guard,
4690            Err(failure) => return SliceAdmission::Capacity(failure),
4691        };
4692    if !round1
4693        .consume_session(
4694            source,
4695            challenge.challenge_id,
4696            &challenge.expected_commitment_hash,
4697            &challenge.nonce,
4698        )
4699        .await
4700    {
4701        // Release the permit and per-peer slot before the caller replies: no
4702        // chunk work follows, so holding them would shrink the pool for nothing.
4703        drop(guard);
4704        return SliceAdmission::NoSession;
4705    }
4706    SliceAdmission::Admitted(guard)
4707}
4708
4709/// Try to admit one audit-responder task for `source`: take a global permit AND
4710/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4711/// its decision-time counters (caller drops the challenge, leaving the remote
4712/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4713/// so one flooder can neither exhaust the global pool's effect on others nor
4714/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4715/// log exactly WHY the drop happened rather than a single opaque "capacity
4716/// reached".
4717async fn admit_audit_responder(
4718    semaphore: &Arc<Semaphore>,
4719    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4720    source: &PeerId,
4721    class: AuditResponderClass,
4722) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4723    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4724    let peer_limit = class.per_peer_limit();
4725    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4726}
4727
4728/// Handle an incoming replication protocol message.
4729///
4730/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4731/// request-response path and the response must be sent via `send_response`
4732/// so saorsa-core can route it back to the waiting `send_request` caller.
4733#[allow(clippy::too_many_lines)]
4734async fn handle_replication_message(
4735    source: &PeerId,
4736    msg: ReplicationMessage,
4737    ctx: &ReplicationMessageHandlerContext,
4738    received_at: Instant,
4739    rr_message_id: Option<&str>,
4740) -> Result<()> {
4741    match msg.body {
4742        ReplicationMessageBody::FreshReplicationOffer(offer) => {
4743            dispatch_fresh_offer(
4744                *source,
4745                offer,
4746                ctx,
4747                msg.request_id,
4748                received_at,
4749                rr_message_id,
4750            )
4751            .await
4752        }
4753        ReplicationMessageBody::PaidNotify(notify) => {
4754            dispatch_paid_notify(*source, notify, ctx, received_at).await
4755        }
4756        ReplicationMessageBody::NeighborSyncRequest(request) => {
4757            let bootstrapping = *ctx.is_bootstrapping.read().await;
4758            // Phase-3 storage-bound audit: store the sender's
4759            // commitment for use as `expected_commitment_hash` in
4760            // future audits. Verify signature before storing so a peer
4761            // cannot inject a forged commitment for someone else.
4762            if let Some(target) = ingest_peer_commitment(
4763                source,
4764                request.commitment.as_ref(),
4765                &ctx.p2p_node,
4766                &ctx.last_commitment_by_peer,
4767                &ctx.ever_capable_peers,
4768                &ctx.sig_verify_attempts,
4769            )
4770            .await
4771            {
4772                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4773            }
4774            dispatch_neighbor_sync_request(
4775                *source,
4776                request,
4777                ctx,
4778                bootstrapping,
4779                // Atomically snapshot + mark-gossiped: emitted in the sync
4780                // response, so we must stay answerable for it (ADR-0002).
4781                ctx.my_commitment_state
4782                    .current_for_gossip()
4783                    .map(|b| b.commitment().clone()),
4784                msg.request_id,
4785                received_at,
4786                rr_message_id,
4787            )
4788            .await
4789        }
4790        ReplicationMessageBody::VerificationRequest(request) => {
4791            dispatch_verification_request(
4792                *source,
4793                request,
4794                ctx,
4795                msg.request_id,
4796                received_at,
4797                rr_message_id,
4798            )
4799            .await
4800        }
4801        ReplicationMessageBody::FetchRequest(request) => {
4802            dispatch_fetch_request(
4803                *source,
4804                request,
4805                ctx,
4806                msg.request_id,
4807                received_at,
4808                rr_message_id,
4809            )
4810            .await
4811        }
4812        ReplicationMessageBody::AuditChallenge(challenge) => {
4813            // Responsible-chunk audit (audit #2) responder: answer with per-key
4814            // possession digests. This same handler also answers the
4815            // prune-confirmation audit, which sends the same `AuditChallenge`
4816            // wire message.
4817            //
4818            // Answering digests the stored bytes of every challenged key, so —
4819            // like the subtree/byte audits below — run it on a detached task off
4820            // this serial message loop. Handling it inline lets one challenge
4821            // block all other replication traffic until its digests complete
4822            // (head-of-line blocking). The same flood-fair admission applies: a
4823            // global ceiling AND a per-peer cap, dropping the challenge if either
4824            // is hit. A dropped challenge reads as a penalised timeout to the
4825            // auditor, so the caps must remain high enough for honest audit load;
4826            // the per-peer share still prevents one flooder from starving others.
4827            let class = AuditResponderClass::Digest;
4828            let guard = match admit_audit_responder(
4829                &ctx.audit_responder_semaphore,
4830                &ctx.audit_responder_inflight,
4831                source,
4832                class,
4833            )
4834            .await
4835            {
4836                Ok(guard) => guard,
4837                Err(failure) => {
4838                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4839                    audit_metrics::record_admission_drop(class);
4840                    ctx.audit_responder_metrics
4841                        .record_drop(*source, failure.reason.into());
4842                    warn!(
4843                        target: "ant_node::replication::audit_responder",
4844                        event = "admission_dropped",
4845                        kind = "responsible",
4846                        responder_class = class.as_str(),
4847                        source = %source,
4848                        challenge_id = challenge.challenge_id,
4849                        key_count = challenge.keys.len(),
4850                        request_response = rr_message_id.is_some(),
4851                        dispatch_ms = received_at.elapsed().as_millis(),
4852                        reason = failure.reason.as_str(),
4853                        global_inflight = failure.global_inflight,
4854                        global_limit = failure.global_limit,
4855                        peer_inflight = failure.peer_inflight,
4856                        peer_limit = failure.peer_limit,
4857                        "Audit responder admission dropped"
4858                    );
4859                    return Ok(());
4860                }
4861            };
4862            let admission_global_inflight = guard.global_inflight;
4863            let admission_peer_inflight = guard.peer_inflight;
4864            ctx.audit_responder_metrics.record_admitted(
4865                *source,
4866                admission_global_inflight,
4867                admission_peer_inflight,
4868            );
4869            info!(
4870                target: "ant_node::replication::audit_responder",
4871                event = "admitted",
4872                kind = "responsible",
4873                responder_class = class.as_str(),
4874                source = %source,
4875                challenge_id = challenge.challenge_id,
4876                key_count = challenge.keys.len(),
4877                request_response = rr_message_id.is_some(),
4878                dispatch_ms = received_at.elapsed().as_millis(),
4879                global_inflight = admission_global_inflight,
4880                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4881                peer_inflight = admission_peer_inflight,
4882                peer_limit = class.per_peer_limit(),
4883                "Audit responder request admitted"
4884            );
4885            let bootstrapping = *ctx.is_bootstrapping.read().await;
4886            let dispatch_latency = received_at.elapsed();
4887            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4888            debug!(
4889                audit_type = "digest_responder",
4890                dispatch_latency_ms = dispatch_latency.as_millis(),
4891                source = %source,
4892                "Audit challenge dispatch latency measured"
4893            );
4894            let storage = Arc::clone(&ctx.storage);
4895            let p2p_node = Arc::clone(&ctx.p2p_node);
4896            let source = *source;
4897            let request_id = msg.request_id;
4898            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
4899            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
4900            ctx.detached_task_tracker.spawn(async move {
4901                let _guard = guard; // global permit + per-peer slot, held until done
4902                let worker_started = Instant::now();
4903                match handle_audit_challenge_msg(
4904                    &source,
4905                    &challenge,
4906                    &storage,
4907                    &p2p_node,
4908                    bootstrapping,
4909                    ReplyRoute {
4910                        request_id,
4911                        rr_message_id: rr_message_id.as_deref(),
4912                        protocol: REPLICATION_PROTOCOL_ID,
4913                    },
4914                )
4915                .await
4916                {
4917                    Ok(completion) => log_audit_responder_completion(
4918                        &responder_metrics,
4919                        source,
4920                        class,
4921                        "responsible",
4922                        challenge.challenge_id,
4923                        challenge.keys.len(),
4924                        completion.response_kind,
4925                        completion.sent,
4926                        received_at,
4927                        worker_started,
4928                        completion.processing,
4929                        completion.response_send,
4930                    ),
4931                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
4932                }
4933            });
4934            Ok(())
4935        }
4936        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
4937            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
4938            // responder rebuilds the WHOLE nonce-selected subtree, reading every
4939            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
4940            // detached task so this serial message loop is never blocked on disk
4941            // I/O — otherwise one audit stalls all replication traffic (§5).
4942            //
4943            // A bounded, flood-fair admission restores backpressure (codex#1 +
4944            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
4945            // we drop this challenge. Subtree auditors grace timeout
4946            // non-responses, so capacity drops throttle flooders without turning
4947            // into trust penalties (and one source cannot starve other peers,
4948            // since its share is capped per-peer).
4949            let class = AuditResponderClass::Subtree;
4950            info!(
4951                "Audit challenge received: kind=subtree source={source} request_response={}",
4952                rr_message_id.is_some(),
4953            );
4954            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
4955            // so it uses its own tight admission pool + per-peer rate cooldown,
4956            // separate from the light responsible/slice audits, and a miss silently
4957            // drops (subtree auditors grace timeouts).
4958            let Some(guard) = ctx.subtree_round1.admit(source).await else {
4959                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
4960                warn!(
4961                    target: "ant_node::replication::audit_responder",
4962                    event = "admission_dropped",
4963                    kind = "subtree",
4964                    responder_class = class.as_str(),
4965                    source = %source,
4966                    challenge_id = challenge.challenge_id,
4967                    request_response = rr_message_id.is_some(),
4968                    dispatch_ms = received_at.elapsed().as_millis(),
4969                    reason = "heavy_pool_cooldown_or_work_budget",
4970                    "Audit responder admission dropped"
4971                );
4972                return Ok(());
4973            };
4974            let admission_global_inflight = guard.global_inflight;
4975            let admission_peer_inflight = guard.peer_inflight;
4976            ctx.audit_responder_metrics.record_admitted(
4977                *source,
4978                admission_global_inflight,
4979                admission_peer_inflight,
4980            );
4981            info!(
4982                target: "ant_node::replication::audit_responder",
4983                event = "admitted",
4984                kind = "subtree",
4985                responder_class = class.as_str(),
4986                source = %source,
4987                challenge_id = challenge.challenge_id,
4988                request_response = rr_message_id.is_some(),
4989                dispatch_ms = received_at.elapsed().as_millis(),
4990                global_inflight = admission_global_inflight,
4991                global_limit = ctx.subtree_round1.max_concurrent,
4992                peer_inflight = admission_peer_inflight,
4993                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
4994                "Audit responder request admitted"
4995            );
4996            let bootstrapping = *ctx.is_bootstrapping.read().await;
4997            let storage = Arc::clone(&ctx.storage);
4998            let p2p_node = Arc::clone(&ctx.p2p_node);
4999            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5000            let source = *source;
5001            let request_id = msg.request_id;
5002            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5003            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5004            let subtree_round1 = ctx.subtree_round1.clone();
5005            ctx.detached_task_tracker.spawn(async move {
5006                let _guard = guard; // global permit + per-peer slot, held until done
5007                let worker_started = Instant::now();
5008                let processing_started = Instant::now();
5009                let storage_commitment_audit::Round1Work {
5010                    response,
5011                    content_bytes,
5012                } = storage_commitment_audit::handle_subtree_challenge_measured(
5013                    &challenge,
5014                    &storage,
5015                    p2p_node.peer_id(),
5016                    bootstrapping,
5017                    Some(&my_commitment_state),
5018                )
5019                .await;
5020                let processing = processing_started.elapsed();
5021                // Charge the work actually done, on EVERY outcome.
5022                //
5023                // This used to charge only the `Proof` arm, reasoning that the
5024                // rejecting paths either read nothing or reflected this node's
5025                // own broken storage. The second half of that was wrong: a
5026                // retained commitment containing one unreadable key still costs
5027                // a full run of reads and keyed-BLAKE3 passes over every leaf
5028                // before it, and then rejects. An attacker who finds such a
5029                // commitment could replay subtrees over it indefinitely for
5030                // free. The per-peer cooldown does not catch that either, since
5031                // it is escapable by rotating identity — the responder-wide
5032                // budget is the only bound that applies, so it has to see the
5033                // work. A zero charge is a no-op, so the untouched paths are
5034                // unaffected.
5035                subtree_round1.charge_work(content_bytes).await;
5036                // A round-1 proof authorizes exactly one matching round 2: open a
5037                // single-use session so a slice challenge cannot be served without
5038                // a live round-1 exchange.
5039                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5040                {
5041                    subtree_round1
5042                        .open_session(
5043                            source,
5044                            challenge.challenge_id,
5045                            challenge.expected_commitment_hash,
5046                            challenge.nonce,
5047                        )
5048                        .await;
5049                }
5050                let response_kind = subtree_audit_response_kind(&response);
5051                let work_items = subtree_audit_response_work_items(&response);
5052                let response_send_started = Instant::now();
5053                let sent = send_replication_response_checked(
5054                    &source,
5055                    &p2p_node,
5056                    request_id,
5057                    ReplicationMessageBody::SubtreeAuditResponse(response),
5058                    rr_message_id.as_deref(),
5059                    None,
5060                )
5061                .await;
5062                let response_send = response_send_started.elapsed();
5063                log_audit_responder_completion(
5064                    &responder_metrics,
5065                    source,
5066                    class,
5067                    "subtree",
5068                    challenge.challenge_id,
5069                    work_items,
5070                    response_kind,
5071                    sent,
5072                    received_at,
5073                    worker_started,
5074                    processing,
5075                    response_send,
5076                );
5077            });
5078            Ok(())
5079        }
5080        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5081            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5082            // block of each auditor-selected spot-check key with a Bao verified
5083            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5084            // build the proofs, so it runs off the serial loop under the light
5085            // audit pool's global and per-peer ceilings.
5086            let class = AuditResponderClass::Byte;
5087            info!(
5088                "Audit challenge received: kind=slice source={source} request_response={}",
5089                rr_message_id.is_some(),
5090            );
5091            let guard = match admit_slice_challenge(
5092                &ctx.audit_responder_semaphore,
5093                &ctx.audit_responder_inflight,
5094                &ctx.subtree_round1,
5095                source,
5096                &challenge,
5097            )
5098            .await
5099            {
5100                SliceAdmission::Admitted(guard) => guard,
5101                SliceAdmission::Capacity(failure) => {
5102                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5103                    audit_metrics::record_admission_drop(class);
5104                    ctx.audit_responder_metrics
5105                        .record_drop(*source, failure.reason.into());
5106                    warn!(
5107                        target: "ant_node::replication::audit_responder",
5108                        event = "admission_dropped",
5109                        kind = "byte",
5110                        responder_class = class.as_str(),
5111                        source = %source,
5112                        challenge_id = challenge.challenge_id,
5113                        key_count = challenge.openings.len(),
5114                        request_response = rr_message_id.is_some(),
5115                        dispatch_ms = received_at.elapsed().as_millis(),
5116                        reason = failure.reason.as_str(),
5117                        global_inflight = failure.global_inflight,
5118                        global_limit = failure.global_limit,
5119                        peer_inflight = failure.peer_inflight,
5120                        peer_limit = failure.peer_limit,
5121                        "Audit responder admission dropped"
5122                    );
5123                    return Ok(());
5124                }
5125                // No live round-1 session: reply with a cheap `Transient` rejection
5126                // rather than dropping silently. Sessions are ephemeral (an honest
5127                // responder that restarts between rounds loses its session), and an
5128                // unanswered `send_request` would make saorsa-core record a
5129                // transport trust failure against that honest responder — an
5130                // ongoing effect, not just a rollout-window one. A `Transient`
5131                // reply routes the auditor to the graced timeout lane (no trust
5132                // penalty; the responder re-earns pinned credit on the next audit)
5133                // and does no chunk work, so it is not a DoS lever.
5134                SliceAdmission::NoSession => {
5135                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5136                    debug!(
5137                        "Slice challenge without a live round-1 session source={source} \
5138                         challenge_id={} → Transient reject",
5139                        challenge.challenge_id
5140                    );
5141                    send_replication_response_checked(
5142                        source,
5143                        &ctx.p2p_node,
5144                        msg.request_id,
5145                        ReplicationMessageBody::SubtreeSliceResponse(
5146                            protocol::SubtreeSliceResponse::Rejected {
5147                                challenge_id: challenge.challenge_id,
5148                                kind: protocol::RejectKind::Transient,
5149                                reason: "no live round-1 session".to_string(),
5150                            },
5151                        ),
5152                        rr_message_id,
5153                        None,
5154                    )
5155                    .await;
5156                    return Ok(());
5157                }
5158            };
5159            let admission_global_inflight = guard.global_inflight;
5160            let admission_peer_inflight = guard.peer_inflight;
5161            ctx.audit_responder_metrics.record_admitted(
5162                *source,
5163                admission_global_inflight,
5164                admission_peer_inflight,
5165            );
5166            info!(
5167                target: "ant_node::replication::audit_responder",
5168                event = "admitted",
5169                kind = "byte",
5170                responder_class = class.as_str(),
5171                source = %source,
5172                challenge_id = challenge.challenge_id,
5173                key_count = challenge.openings.len(),
5174                request_response = rr_message_id.is_some(),
5175                dispatch_ms = received_at.elapsed().as_millis(),
5176                global_inflight = admission_global_inflight,
5177                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5178                peer_inflight = admission_peer_inflight,
5179                peer_limit = class.per_peer_limit(),
5180                "Audit responder request admitted"
5181            );
5182            let bootstrapping = *ctx.is_bootstrapping.read().await;
5183            let storage = Arc::clone(&ctx.storage);
5184            let p2p_node = Arc::clone(&ctx.p2p_node);
5185            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5186            let source = *source;
5187            let request_id = msg.request_id;
5188            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5189            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5190            ctx.detached_task_tracker.spawn(async move {
5191                let _guard = guard; // global permit + per-peer slot, held until done
5192                let worker_started = Instant::now();
5193                let processing_started = Instant::now();
5194                let response = storage_commitment_audit::handle_subtree_slice_challenge(
5195                    &challenge,
5196                    &storage,
5197                    p2p_node.peer_id(),
5198                    bootstrapping,
5199                    Some(&my_commitment_state),
5200                )
5201                .await;
5202                let processing = processing_started.elapsed();
5203                let response_kind = subtree_slice_response_kind(&response);
5204                let response_send_started = Instant::now();
5205                let sent = send_replication_response_checked(
5206                    &source,
5207                    &p2p_node,
5208                    request_id,
5209                    ReplicationMessageBody::SubtreeSliceResponse(response),
5210                    rr_message_id.as_deref(),
5211                    None,
5212                )
5213                .await;
5214                let response_send = response_send_started.elapsed();
5215                log_audit_responder_completion(
5216                    &responder_metrics,
5217                    source,
5218                    class,
5219                    "byte",
5220                    challenge.challenge_id,
5221                    challenge.openings.len(),
5222                    response_kind,
5223                    sent,
5224                    received_at,
5225                    worker_started,
5226                    processing,
5227                    response_send,
5228                );
5229            });
5230            Ok(())
5231        }
5232        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5233            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5234            // only. `lookup_by_hash` is an allocation-light read over the
5235            // bounded slot set; it returns the live current commitment or any
5236            // still-answerable recently-gossiped/quoted one. A miss is reported
5237            // as `NotRetained` (graced, never confirmed) rather than an error,
5238            // so an aged-out pin can never brand an honest node.
5239            //
5240            // Reuse the audit-responder admission guard (global ceiling + per-peer
5241            // cap) so a flood of fetches cannot drive unbounded commitment
5242            // clone/encode/send work; over-limit is dropped, which the fetching
5243            // peer graces exactly like a missed audit response.
5244            let class = AuditResponderClass::CommitmentPin;
5245            let guard = match admit_audit_responder(
5246                &ctx.audit_responder_semaphore,
5247                &ctx.audit_responder_inflight,
5248                source,
5249                class,
5250            )
5251            .await
5252            {
5253                Ok(guard) => guard,
5254                Err(failure) => {
5255                    audit_metrics::record_admission_drop(class);
5256                    ctx.audit_responder_metrics
5257                        .record_drop(*source, failure.reason.into());
5258                    warn!(
5259                        target: "ant_node::replication::audit_responder",
5260                        event = "admission_dropped",
5261                        kind = "commitment_pin",
5262                        responder_class = class.as_str(),
5263                        source = %source,
5264                        challenge_id = msg.request_id,
5265                        request_response = rr_message_id.is_some(),
5266                        dispatch_ms = received_at.elapsed().as_millis(),
5267                        reason = failure.reason.as_str(),
5268                        global_inflight = failure.global_inflight,
5269                        global_limit = failure.global_limit,
5270                        peer_inflight = failure.peer_inflight,
5271                        peer_limit = failure.peer_limit,
5272                        "Audit responder admission dropped"
5273                    );
5274                    return Ok(());
5275                }
5276            };
5277            ctx.audit_responder_metrics.record_admitted(
5278                *source,
5279                guard.global_inflight,
5280                guard.peer_inflight,
5281            );
5282            info!(
5283                target: "ant_node::replication::audit_responder",
5284                event = "admitted",
5285                kind = "commitment_pin",
5286                responder_class = class.as_str(),
5287                source = %source,
5288                challenge_id = msg.request_id,
5289                request_response = rr_message_id.is_some(),
5290                dispatch_ms = received_at.elapsed().as_millis(),
5291                global_inflight = guard.global_inflight,
5292                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5293                peer_inflight = guard.peer_inflight,
5294                peer_limit = class.per_peer_limit(),
5295                "Audit responder request admitted"
5296            );
5297            let worker_started = Instant::now();
5298            let processing_started = Instant::now();
5299            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5300                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5301                |built| protocol::GetCommitmentByPinResponse::Found {
5302                    commitment: built.commitment().clone(),
5303                },
5304            );
5305            let processing = processing_started.elapsed();
5306            let response_kind = commitment_pin_response_kind(&response);
5307            let response_send_started = Instant::now();
5308            let sent = send_replication_response_checked(
5309                source,
5310                &ctx.p2p_node,
5311                msg.request_id,
5312                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5313                rr_message_id,
5314                None,
5315            )
5316            .await;
5317            let response_send = response_send_started.elapsed();
5318            log_audit_responder_completion(
5319                &ctx.audit_responder_metrics,
5320                *source,
5321                class,
5322                "commitment_pin",
5323                msg.request_id,
5324                1,
5325                response_kind,
5326                sent,
5327                received_at,
5328                worker_started,
5329                processing,
5330                response_send,
5331            );
5332            drop(guard);
5333            Ok(())
5334        }
5335        // Response messages are handled by their respective request initiators.
5336        ReplicationMessageBody::FreshReplicationResponse(_)
5337        | ReplicationMessageBody::NeighborSyncResponse(_)
5338        | ReplicationMessageBody::VerificationResponse(_)
5339        | ReplicationMessageBody::FetchResponse(_)
5340        | ReplicationMessageBody::AuditResponse(_)
5341        | ReplicationMessageBody::SubtreeAuditResponse(_)
5342        | ReplicationMessageBody::SubtreeSliceResponse(_)
5343        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5344    }
5345}
5346
5347// ---------------------------------------------------------------------------
5348// Per-message-type handlers
5349// ---------------------------------------------------------------------------
5350
5351/// Verify a payment proof, yielding early if the engine is shutting down.
5352///
5353/// Returns `None` when shutdown won the race, meaning no verdict was reached
5354/// and the caller must abandon the message without storing or penalising.
5355///
5356/// Payment verification is pure network I/O — an EVM round trip and, on the
5357/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5358/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5359/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5360/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5361/// is guaranteed to end.
5362///
5363/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5364/// dropping its awaiter would detach a live LMDB transaction and break the
5365/// very contract the unbounded wait exists to uphold.
5366async fn verify_payment_until_shutdown(
5367    payment_verifier: &Arc<PaymentVerifier>,
5368    key: &XorName,
5369    proof_of_payment: &[u8],
5370    context: VerificationContext,
5371    shutdown: &CancellationToken,
5372) -> Option<Result<crate::payment::PaymentStatus>> {
5373    tokio::select! {
5374        () = shutdown.cancelled() => None,
5375        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5376            Some(result)
5377        }
5378    }
5379}
5380
5381/// A fresh offer rejected on payload shape alone.
5382struct FreshOfferRejection {
5383    /// Wire-visible reason returned to the sender.
5384    reason: String,
5385    /// Whether the sender is charged for it. Reserved for offers no honest
5386    /// node would construct, so an ordinary capacity refusal stays free.
5387    penalise: bool,
5388}
5389
5390/// Reject a fresh offer on payload shape, or return `None` to admit it.
5391///
5392/// Pure and non-blocking by construction: these are the checks answerable from
5393/// the payload alone, run on the serial message loop *before* the in-flight
5394/// claim and the admission permit, so a malformed offer can neither lock an
5395/// honest offer out of its key nor occupy one of the scarce
5396/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5397/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5398/// verification — stays on the worker.
5399///
5400/// The content-address hash is deliberately included despite costing real CPU
5401/// on the loop: it is what makes the entry below *earned* rather than merely
5402/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5403/// arrive at link speed, so a flooder can never make this loop hash faster than
5404/// it can deliver the bytes, and delivering them already cost it more than the
5405/// hash costs us. The receive path has in any case already deserialised the
5406/// same buffer.
5407///
5408/// Every rejection here is penalised. These are the conditions no honest sender
5409/// can produce — an absent, undersized, oversized, or non-matching payload — as
5410/// distinct from a capacity refusal, which is this node's own state and stays
5411/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5412/// proof that fails to verify may simply have been read against a lagging chain
5413/// view, and penalising that would charge honest senders in correlated bursts.
5414fn fresh_offer_structural_rejection(
5415    key: &XorName,
5416    data: &[u8],
5417    proof_of_payment: &[u8],
5418) -> Option<FreshOfferRejection> {
5419    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5420    // and an absent proof is the cheapest possible slot-filler, so this is the
5421    // first thing checked.
5422    if proof_of_payment.is_empty() {
5423        return Some(FreshOfferRejection {
5424            reason: "Missing proof of payment".to_string(),
5425            penalise: true,
5426        });
5427    }
5428
5429    // Bound the proof before it can be queued. The verifier applies the same
5430    // limits, but only once the offer reaches a worker — too late here, because
5431    // an entry retains a proof per queued sender, and a proof is capped on the
5432    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5433    // a byte of data and a 10 MiB "proof" would be admitted, and
5434    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5435    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5436    // admission bound exists to enforce.
5437    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5438        return Some(FreshOfferRejection {
5439            reason: format!(
5440                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5441                proof_of_payment.len(),
5442            ),
5443            penalise: true,
5444        });
5445    }
5446    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5447        return Some(FreshOfferRejection {
5448            reason: format!(
5449                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5450                proof_of_payment.len(),
5451            ),
5452            penalise: true,
5453        });
5454    }
5455
5456    // Enforce chunk size invariant: the normal PUT path rejects data larger
5457    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5458    // prevent peers from pushing oversized records through replication.
5459    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5460        return Some(FreshOfferRejection {
5461            reason: format!(
5462                "Data size {} exceeds maximum chunk size {}",
5463                data.len(),
5464                crate::ant_protocol::MAX_CHUNK_SIZE,
5465            ),
5466            penalise: true,
5467        });
5468    }
5469
5470    // Mirror the normal PUT path: the advertised key must be the content
5471    // address of the supplied bytes. Ordered last so an oversized payload is
5472    // refused without being hashed.
5473    //
5474    // This is the check that makes the entry safe to open, and safe for later
5475    // offers to be folded into. Until it passes, the sender has only *asserted*
5476    // an association between the key and the bytes. Opening an entry on an
5477    // assertion would let any peer that knows a key — every recipient of its
5478    // `PaidNotify`, not just the close group — seize it with junk; folding a
5479    // later offer into an entry on an assertion would be worse still, since the
5480    // handler tries each queued proof against the *opener's* bytes and would be
5481    // storing bytes nobody offered for that proof.
5482    let computed_key = crate::client::compute_address(data);
5483    if computed_key != *key {
5484        return Some(FreshOfferRejection {
5485            reason: format!(
5486                "Content address mismatch: expected {}, computed {}",
5487                hex::encode(key),
5488                hex::encode(computed_key),
5489            ),
5490            penalise: true,
5491        });
5492    }
5493
5494    None
5495}
5496
5497/// Tell `source` its offer for `key` was not taken.
5498///
5499/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5500/// one-way `send_message`, so the refusal is observed only as a later absence by
5501/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5502async fn refuse_fresh_offer(
5503    source: &PeerId,
5504    key: XorName,
5505    reason: String,
5506    ctx: &ReplicationMessageHandlerContext,
5507    request_id: u64,
5508    rr_message_id: Option<&str>,
5509) {
5510    send_replication_response(
5511        source,
5512        &ctx.p2p_node,
5513        request_id,
5514        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5515            key,
5516            reason,
5517        }),
5518        rr_message_id,
5519    )
5520    .await;
5521}
5522
5523/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5524/// the sender when the defect is one no honest node could produce.
5525///
5526/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5527/// two say opposite things: this is the sender's fault, that one is ours.
5528async fn refuse_malformed_fresh_offer(
5529    source: &PeerId,
5530    key: XorName,
5531    rejection: FreshOfferRejection,
5532    ctx: &ReplicationMessageHandlerContext,
5533    request_id: u64,
5534    rr_message_id: Option<&str>,
5535) {
5536    if rejection.penalise {
5537        warn!(
5538            "Rejecting fresh offer for key {} from {source}: {}",
5539            hex::encode(key),
5540            rejection.reason
5541        );
5542        ctx.p2p_node
5543            .report_trust_event(
5544                source,
5545                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5546            )
5547            .await;
5548    } else {
5549        debug!(
5550            "Fresh offer for {} from {source} refused before admission: {}",
5551            hex::encode(key),
5552            rejection.reason
5553        );
5554    }
5555    refuse_fresh_offer(
5556        source,
5557        key,
5558        rejection.reason,
5559        ctx,
5560        request_id,
5561        rr_message_id,
5562    )
5563    .await;
5564}
5565
5566/// Tell senders whose proofs joined an entry that was torn down before a handler
5567/// ever ran for it.
5568///
5569/// Only reachable in the window between opening an entry and failing to take an
5570/// admission permit. Their proofs are answered rather than dropped with the
5571/// entry, so the refusal count reflects what actually happened.
5572async fn refuse_stranded_fresh_offers(
5573    key: XorName,
5574    stranded: Vec<FreshOfferAttempt>,
5575    ctx: &ReplicationMessageHandlerContext,
5576) {
5577    for attempt in stranded {
5578        refuse_fresh_offer(
5579            &attempt.source,
5580            key,
5581            "Receiver at fresh-offer capacity".to_string(),
5582            ctx,
5583            attempt.request_id,
5584            attempt.rr_message_id.as_deref(),
5585        )
5586        .await;
5587    }
5588}
5589
5590/// Admit a fresh offer for handling on a worker, or refuse it.
5591///
5592/// This runs on the serial non-audit message loop, so it must stay cheap: every
5593/// path here is a set insert, a permit try, or a small response send. The offer
5594/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5595/// runs on a tracked worker task, never inline, because stalling this loop backs
5596/// up the inbound queue and ultimately drops replication messages wholesale.
5597///
5598/// Admission is bounded **per source** as well as globally
5599/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5600/// hold every slot, and since a refusal is later read as absence by the
5601/// sender's delayed possession check, the resulting refusals land as
5602/// audit-severity penalties on this node rather than on the flooder.
5603///
5604/// The structurally-invalid checks run **before** the entry is opened and before
5605/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5606/// the duration of a payment verification.
5607///
5608/// Only the offer that *opens* an entry costs a permit and a worker. Later
5609/// offers for the same key contribute their proof and are answered by whatever
5610/// the opener's handler concludes, which is what keeps the routine
5611/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5612/// one verification per key.
5613async fn dispatch_fresh_offer(
5614    source: PeerId,
5615    offer: protocol::FreshReplicationOffer,
5616    ctx: &ReplicationMessageHandlerContext,
5617    request_id: u64,
5618    received_at: Instant,
5619    rr_message_id: Option<&str>,
5620) -> Result<()> {
5621    if let Some(rejection) =
5622        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5623    {
5624        refuse_malformed_fresh_offer(
5625            &source,
5626            offer.key,
5627            rejection,
5628            ctx,
5629            request_id,
5630            rr_message_id,
5631        )
5632        .await;
5633        return Ok(());
5634    }
5635
5636    // Join the work already in flight for this key before taking an admission
5637    // permit, so the duplicates a single client PUT produces cost one permit
5638    // between them rather than one each.
5639    //
5640    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5641    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5642    // already held for the key. That is what lets its payload be dropped here
5643    // and only its proof retained: the handler will try that proof against the
5644    // bytes it already has.
5645    let key = offer.key;
5646    let admission_outcome = FreshOfferEntryGuard::admit(
5647        &ctx.fresh_offer_in_flight,
5648        offer,
5649        source,
5650        request_id,
5651        rr_message_id.map(ToOwned::to_owned),
5652        received_at,
5653    );
5654    let mut entry = match admission_outcome {
5655        FreshOfferAdmission::Opened(entry) => entry,
5656        FreshOfferAdmission::Joined => {
5657            // No response yet: this proof has not been judged. The handler that
5658            // owns the key answers every queued sender once it settles.
5659            debug!(
5660                "Fresh offer for {} from {source} queued behind the handler already \
5661                 holding the key",
5662                hex::encode(key)
5663            );
5664            return Ok(());
5665        }
5666        // Surplus, not suspect: the proofs already queued are enough to place
5667        // the record, so neither case is charged as misbehaviour.
5668        surplus => {
5669            debug!(
5670                "Fresh offer for {} from {source} refused: {}",
5671                hex::encode(key),
5672                surplus.surplus_reason()
5673            );
5674            refuse_fresh_offer(
5675                &source,
5676                key,
5677                "Duplicate offer already in flight".to_string(),
5678                ctx,
5679                request_id,
5680                rr_message_id,
5681            )
5682            .await;
5683            return Ok(());
5684        }
5685    };
5686
5687    let admission = match admit_bounded_responder(
5688        &ctx.fresh_offer_admission_semaphore,
5689        &ctx.fresh_offer_responder_inflight,
5690        &source,
5691        FRESH_OFFER_MAX_OUTSTANDING,
5692        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5693    )
5694    .await
5695    {
5696        Ok(guard) => guard,
5697        Err(failure) => {
5698            audit_metrics::record_responder_admission_drop(
5699                ReplicationResponderClass::FreshOffer,
5700                failure.reason.into(),
5701            );
5702            // WARN, not DEBUG: a healthy node should never refuse a legitimate
5703            // fresh offer. The sender does not read this refusal, so it
5704            // resurfaces as a missing key at the delayed possession check and
5705            // is charged to US at audit severity. Log the binding ceiling
5706            // locally; the wire reason stays generic so a probing peer cannot
5707            // map out this node's live occupancy.
5708            warn!(
5709                responder_class = "fresh_offer",
5710                source = %source,
5711                key = %hex::encode(key),
5712                "Fresh offer refused at admission — this node will be penalised                  for the resulting absence: {failure}"
5713            );
5714            // Release the key explicitly rather than on drop, so the next offer
5715            // opens a fresh entry rather than queueing behind a handler that was
5716            // never spawned — and so any proof that joined in the window between
5717            // opening the entry and failing here is answered rather than
5718            // discarded with it.
5719            let stranded = entry.release();
5720            refuse_fresh_offer(
5721                &source,
5722                key,
5723                "Receiver at fresh-offer capacity".to_string(),
5724                ctx,
5725                request_id,
5726                rr_message_id,
5727            )
5728            .await;
5729            refuse_stranded_fresh_offers(key, stranded, ctx).await;
5730            return Ok(());
5731        }
5732    };
5733
5734    let ctx = ctx.clone();
5735    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5736    // an `Arc<LmdbStorage>` while writing, and the shutdown contract requires
5737    // those references be released before the caller reopens the environment.
5738    ctx.detached_task_tracker
5739        .clone()
5740        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5741    Ok(())
5742}
5743
5744/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5745///
5746/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5747/// A started handler is never cancelled: `storage.put()` awaits
5748/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5749/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5750/// and from `handle_fresh_offer` racing the token around payment verification.
5751///
5752/// Works down the key's queued proofs rather than judging the key on the first
5753/// one. A proof that fails to establish payment disqualifies its *sender*, not
5754/// the record: the bytes are content-addressed and identical across every offer,
5755/// so the next sender's proof is tried against the copy already in hand — no
5756/// second payload, no second permit, no refetch. Only when a failure is about
5757/// the key itself (not responsible, no capacity, shutting down) does rotating
5758/// become pointless, because every remaining proof would meet the same wall.
5759async fn run_fresh_offer_worker(
5760    key: XorName,
5761    mut entry: Box<FreshOfferEntryGuard>,
5762    ctx: ReplicationMessageHandlerContext,
5763    admission: ResponderGuard,
5764) {
5765    // The admission permit is released on completion, freeing the payload's
5766    // memory budget and the opening source's per-peer share. The entry releases
5767    // the key itself, either as the queue empties or on drop.
5768    let _admission = admission;
5769    let received_at = entry.received_at();
5770    // Wait for a worker slot here rather than in the caller. The worker bound
5771    // caps concurrent EVM and storage pressure; making the message loop wait on
5772    // it is what put that pressure back on the loop.
5773    //
5774    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5775    // path for offers still queued behind a worker when the engine stops — not
5776    // dead code.
5777    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5778        .acquire_owned()
5779        .await
5780    else {
5781        debug!(
5782            "Fresh offer for {} dropped: worker pool shut down",
5783            hex::encode(key)
5784        );
5785        return;
5786    };
5787    // Fresh offers are fire-and-forget (`send_message`), so there is no
5788    // requester deadline to honour and a late store is still genuinely useful.
5789    // The threshold is the point past which the offer has already cost us what
5790    // it was going to cost: the possession check (ADR-0003) has run by then and
5791    // charged the absence to this node, and it does not re-offer the key —
5792    // repair comes later from neighbor sync. Shedding here trades a copy that
5793    // would have arrived after the penalty for the multi-MiB payload it is
5794    // holding, and keeps a backlog from outliving its own admission bound.
5795    //
5796    // Note this is a memory-pressure decision, not a redundancy one: the copy
5797    // is late, not useless, so on a node with headroom finishing it would still
5798    // beat waiting for neighbor sync.
5799    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5800        debug!(
5801            responder_class = "fresh_offer",
5802            key = %hex::encode(key),
5803            request_age_ms = received_at.elapsed().as_millis(),
5804            "Superseded fresh offer shed at dequeue"
5805        );
5806        return;
5807    }
5808
5809    let mut verdict = FreshOfferOutcome::Abandoned;
5810    while let Some(attempt) = entry.next_attempt() {
5811        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5812            Ok(outcome) => {
5813                verdict = outcome;
5814                match outcome {
5815                    // Settled: the record is down and every remaining sender
5816                    // wanted exactly that. Abandoned: the key cannot be placed
5817                    // by anyone right now, so the proofs behind this one would
5818                    // fail identically. Either way there is nothing left to try.
5819                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5820                    // This sender's claim to have paid did not hold up. Say so
5821                    // to that sender alone and try the next proof.
5822                    FreshOfferOutcome::ProofRejected => {}
5823                }
5824            }
5825            Err(e) => {
5826                debug!(
5827                    "Fresh replication offer for {} from {} error: {e}",
5828                    hex::encode(key),
5829                    attempt.source
5830                );
5831                verdict = FreshOfferOutcome::Abandoned;
5832                break;
5833            }
5834        }
5835    }
5836
5837    // Answer the senders whose proofs were never reached. A stored record is
5838    // what they were asking for, so it is an acceptance even though their own
5839    // proof went untested.
5840    let unreached = entry.release();
5841    if unreached.is_empty() {
5842        return;
5843    }
5844    let response = match verdict {
5845        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5846        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5847            FreshReplicationResponse::Rejected {
5848                key,
5849                reason: "Record could not be stored from any offered proof".to_string(),
5850            }
5851        }
5852    };
5853    for attempt in unreached {
5854        send_replication_response(
5855            &attempt.source,
5856            &ctx.p2p_node,
5857            attempt.request_id,
5858            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5859            attempt.rr_message_id.as_deref(),
5860        )
5861        .await;
5862    }
5863}
5864
5865/// What one proof concluded, and whether another proof for the same key is worth
5866/// trying.
5867///
5868/// The distinction the worker acts on is *what the failure was about*. A
5869/// rejected proof is a statement about its sender; anything else is a statement
5870/// about the key or this node, which no other sender's proof can change.
5871#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5872enum FreshOfferOutcome {
5873    /// The record is stored. The key is done.
5874    Settled,
5875    /// This proof did not establish payment. A different sender's proof for the
5876    /// same bytes may still succeed.
5877    ProofRejected,
5878    /// Nothing about this key can succeed right now — not responsible, no disk,
5879    /// shutting down, or a write that failed. Rotating repeats the failure.
5880    Abandoned,
5881}
5882
5883// A linear sequence of protocol steps — structural recheck, responsibility,
5884// capacity, payment, write — each with its own refusal response. Splitting it
5885// would scatter one decision across several functions.
5886#[allow(clippy::too_many_lines)]
5887async fn handle_fresh_offer(
5888    key: &XorName,
5889    data: &[u8],
5890    attempt: &FreshOfferAttempt,
5891    ctx: &ReplicationMessageHandlerContext,
5892) -> Result<FreshOfferOutcome> {
5893    let source = &attempt.source;
5894    let request_id = attempt.request_id;
5895    let rr_message_id = attempt.rr_message_id.as_deref();
5896    let p2p_node = &ctx.p2p_node;
5897    let config = &ctx.config;
5898    let self_id = *p2p_node.peer_id();
5899
5900    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
5901    // proof, bad proof size, oversized payload, content-address mismatch —
5902    // before opening the entry or taking an admission permit, so nothing
5903    // reaching a worker should trip them. Kept so the handler is correct in
5904    // isolation. Note this re-checks the *pairing* actually being used: these
5905    // bytes against this attempt's proof.
5906    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
5907    {
5908        if rejection.penalise {
5909            warn!(
5910                "Rejecting fresh offer for key {}: {}",
5911                hex::encode(key),
5912                rejection.reason
5913            );
5914            p2p_node
5915                .report_trust_event(
5916                    source,
5917                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5918                )
5919                .await;
5920        }
5921        send_replication_response(
5922            source,
5923            p2p_node,
5924            request_id,
5925            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5926                key: *key,
5927                reason: rejection.reason,
5928            }),
5929            rr_message_id,
5930        )
5931        .await;
5932        // Structurally invalid is a fact about this attempt, not the key.
5933        return Ok(FreshOfferOutcome::ProofRejected);
5934    }
5935
5936    // Rule 7: check storage admission. Fresh chunk receivers accept across the
5937    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
5938    // the same width client PUTs use), not just the close group plus a small
5939    // margin (ADR-0003). During full-node shunning a healthy replica's routing
5940    // table may still list closer full nodes it hasn't evicted yet, ranking it
5941    // outside the narrow window in its own view; the wider accept window absorbs
5942    // that transient skew so the chunk still lands. Retention (pruning) stays at
5943    // `storage_admission_width`, so steady-state replication is unchanged.
5944    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
5945    {
5946        send_replication_response(
5947            source,
5948            p2p_node,
5949            request_id,
5950            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5951                key: *key,
5952                reason: "Not in storage-admission range for this key".to_string(),
5953            }),
5954            rr_message_id,
5955        )
5956        .await;
5957        // About the key and this node's place in the routing table, not about
5958        // the sender: every queued proof would be refused identically.
5959        return Ok(FreshOfferOutcome::Abandoned);
5960    }
5961
5962    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
5963    // never store this record, so reject it before the expensive payment
5964    // verification (EVM on-chain query / merkle pool work) rather than verifying
5965    // and only then failing at `storage.put` below. Reuses the cached capacity
5966    // check (passing results only, so freed space is detected promptly), and the
5967    // store path keeps its own check as defence-in-depth.
5968    if let Err(e) = ctx.storage.check_capacity() {
5969        info!(
5970            target: "ant_node::storage::disk_precheck",
5971            key = %hex::encode(key),
5972            "Rejecting fresh replication offer before payment verification: {e}"
5973        );
5974        send_replication_response(
5975            source,
5976            p2p_node,
5977            request_id,
5978            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5979                key: *key,
5980                reason: e.to_string(),
5981            }),
5982            rr_message_id,
5983        )
5984        .await;
5985        // A full disk is this node's condition, not the sender's.
5986        return Ok(FreshOfferOutcome::Abandoned);
5987    }
5988
5989    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
5990    // part of the immediate write fan-out: this receiver is about to store the
5991    // record as if the client had PUT it here directly. Storage admission
5992    // was checked above before proof work. FreshReplication verification is
5993    // identical to ClientPut — store-strength cache semantics, paid-quote
5994    // issuer K-closeness checks for single-node proofs, merkle candidate
5995    // closeness for merkle proofs, and the same price-floor policy — the
5996    // distinct context only labels price-floor telemetry.
5997    let Some(verification) = verify_payment_until_shutdown(
5998        &ctx.payment_verifier,
5999        key,
6000        &attempt.proof_of_payment,
6001        fresh_offer_payment_context(),
6002        &ctx.shutdown,
6003    )
6004    .await
6005    else {
6006        debug!(
6007            "Fresh offer for {} from {source} abandoned: engine shutting down \
6008             during payment verification",
6009            hex::encode(key)
6010        );
6011        return Ok(FreshOfferOutcome::Abandoned);
6012    };
6013    match verification {
6014        Ok(status) if status.can_store() => {
6015            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6016        }
6017        // The chain has no record of this payment. That is a statement about
6018        // *this sender's* proof, so the key rotates to the next one rather than
6019        // being written off — the whole point of queueing them.
6020        //
6021        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6022        // not "definitively unpaid", so a lagging or reorganising chain view
6023        // renders honest senders indistinguishable from forgers, and penalising
6024        // would land on the entire close group at once. The structural checks in
6025        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6026        // because those cannot be produced by an honest sender at all.
6027        Ok(_) => {
6028            debug!(
6029                "Fresh offer for {} from {source}: no payment found for this proof",
6030                hex::encode(key)
6031            );
6032            send_replication_response(
6033                source,
6034                p2p_node,
6035                request_id,
6036                ReplicationMessageBody::FreshReplicationResponse(
6037                    FreshReplicationResponse::Rejected {
6038                        key: *key,
6039                        reason: "Payment verification failed: payment required".to_string(),
6040                    },
6041                ),
6042                rr_message_id,
6043            )
6044            .await;
6045            return Ok(FreshOfferOutcome::ProofRejected);
6046        }
6047        // A verification *error* is usually ours — an unreachable or failing EVM
6048        // endpoint — so it is neither penalised nor treated as this sender's
6049        // fault. Another proof still gets its turn, since the next call may well
6050        // succeed against a recovered endpoint.
6051        Err(e) => {
6052            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6053            send_replication_response(
6054                source,
6055                p2p_node,
6056                request_id,
6057                ReplicationMessageBody::FreshReplicationResponse(
6058                    FreshReplicationResponse::Rejected {
6059                        key: *key,
6060                        reason: format!("Payment verification error: {e}"),
6061                    },
6062                ),
6063                rr_message_id,
6064            )
6065            .await;
6066            return Ok(FreshOfferOutcome::ProofRejected);
6067        }
6068    }
6069
6070    // Rule 6: add to PaidForList.
6071    if let Err(e) = ctx.paid_list.insert(key).await {
6072        warn!("Failed to add key to PaidForList: {e}");
6073    }
6074
6075    // Store the record.
6076    match ctx.storage.put(key, data).await {
6077        Ok(_) => {
6078            send_replication_response(
6079                source,
6080                p2p_node,
6081                request_id,
6082                ReplicationMessageBody::FreshReplicationResponse(
6083                    FreshReplicationResponse::Accepted { key: *key },
6084                ),
6085                rr_message_id,
6086            )
6087            .await;
6088            Ok(FreshOfferOutcome::Settled)
6089        }
6090        Err(e) => {
6091            send_replication_response(
6092                source,
6093                p2p_node,
6094                request_id,
6095                ReplicationMessageBody::FreshReplicationResponse(
6096                    FreshReplicationResponse::Rejected {
6097                        key: *key,
6098                        reason: e.to_string(),
6099                    },
6100                ),
6101                rr_message_id,
6102            )
6103            .await;
6104            // The payment was good and the write still failed, so this is local
6105            // storage trouble that another proof cannot get around.
6106            Ok(FreshOfferOutcome::Abandoned)
6107        }
6108    }
6109}
6110
6111/// Admit a paid-list notification for handling on a worker, or drop it.
6112///
6113/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6114/// meant one message could park every other non-audit message behind a full
6115/// payment verification. That verification is not a bounded local computation:
6116/// on the merkle path it performs an iterative Kademlia lookup capped only by
6117/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6118/// the loop for minutes while the bounded inbound queue behind it overflowed
6119/// and dropped unrelated replication traffic wholesale.
6120///
6121/// It now follows the same detached-responder pattern as neighbor sync and
6122/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6123/// when stale, and run on a tracked worker.
6124///
6125/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6126/// refused notify is simply dropped. The sender's own paid-list convergence
6127/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6128/// the recovery path, exactly as for a notify lost in transit.
6129async fn dispatch_paid_notify(
6130    source: PeerId,
6131    notify: protocol::PaidNotify,
6132    ctx: &ReplicationMessageHandlerContext,
6133    received_at: Instant,
6134) -> Result<()> {
6135    let admission = match admit_bounded_responder(
6136        &ctx.paid_notify_admission_semaphore,
6137        &ctx.paid_notify_responder_inflight,
6138        &source,
6139        PAID_NOTIFY_MAX_OUTSTANDING,
6140        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6141    )
6142    .await
6143    {
6144        Ok(guard) => guard,
6145        Err(failure) => {
6146            audit_metrics::record_responder_admission_drop(
6147                ReplicationResponderClass::PaidNotify,
6148                failure.reason.into(),
6149            );
6150            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6151            // so a refusal discards durable paid-list evidence outright rather
6152            // than pushing work back onto a requester.
6153            warn!(
6154                responder_class = "paid_notify",
6155                source = %source,
6156                key = %hex::encode(notify.key),
6157                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6158            );
6159            return Ok(());
6160        }
6161    };
6162
6163    let ctx = ctx.clone();
6164    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6165    // Deliberately NOT the verification request deadline used by the
6166    // request/response responders. Nobody is waiting on a notify, and shedding
6167    // one discards durable paid-list evidence rather than a reply a requester
6168    // has already given up on. The threshold is instead the point at which the
6169    // pull path would have learned the same fact anyway: one slow-cadence
6170    // neighbor-sync interval, after which the verification cycle's paid-list
6171    // quorum makes this notify genuinely redundant.
6172    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6173    ctx.detached_task_tracker.clone().spawn(async move {
6174        let _admission = admission;
6175        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6176        // still queued behind a worker when the engine stops.
6177        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6178            debug!("Paid notify from {source} dropped: worker pool shut down");
6179            return;
6180        };
6181        if request_is_stale(received_at, queue_max_age) {
6182            debug!(
6183                responder_class = "paid_notify",
6184                source = %source,
6185                request_age_ms = received_at.elapsed().as_millis(),
6186                "Redundant paid notify shed at dequeue"
6187            );
6188            return;
6189        }
6190        if let Err(e) = handle_paid_notify(
6191            &source,
6192            &notify,
6193            &ctx.paid_list,
6194            &ctx.payment_verifier,
6195            &ctx.p2p_node,
6196            &ctx.config,
6197            &ctx.shutdown,
6198        )
6199        .await
6200        {
6201            debug!("Paid notify from {source} error: {e}");
6202        }
6203    });
6204
6205    Ok(())
6206}
6207
6208async fn handle_paid_notify(
6209    _source: &PeerId,
6210    notify: &protocol::PaidNotify,
6211    paid_list: &Arc<PaidList>,
6212    payment_verifier: &Arc<PaymentVerifier>,
6213    p2p_node: &Arc<P2PNode>,
6214    config: &ReplicationConfig,
6215    shutdown: &CancellationToken,
6216) -> Result<()> {
6217    let self_id = *p2p_node.peer_id();
6218
6219    // Rule 3: validate PoP presence before adding.
6220    if notify.proof_of_payment.is_empty() {
6221        return Ok(());
6222    }
6223
6224    // Check if we're in PaidCloseGroup for this key.
6225    if !admission::is_in_paid_close_group(
6226        &self_id,
6227        &notify.key,
6228        p2p_node,
6229        config.paid_list_close_group_size,
6230    )
6231    .await
6232    {
6233        return Ok(());
6234    }
6235
6236    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6237    // paid-list metadata, so local paid-list close-group membership was checked
6238    // above before proof work. The verifier then runs the same payment proof
6239    // checks as ClientPut while writing a paid-list-strength cache entry.
6240    let Some(verification) = verify_payment_until_shutdown(
6241        payment_verifier,
6242        &notify.key,
6243        &notify.proof_of_payment,
6244        paid_notify_payment_context(),
6245        shutdown,
6246    )
6247    .await
6248    else {
6249        debug!(
6250            "Paid notify for {} abandoned: engine shutting down during payment \
6251             verification",
6252            hex::encode(notify.key)
6253        );
6254        return Ok(());
6255    };
6256    match verification {
6257        Ok(status) if status.can_store() => {
6258            debug!(
6259                "PoP validated for paid notify key {}",
6260                hex::encode(notify.key)
6261            );
6262        }
6263        Ok(_) => {
6264            warn!(
6265                "Paid notify rejected: payment required for key {}",
6266                hex::encode(notify.key)
6267            );
6268            return Ok(());
6269        }
6270        Err(e) => {
6271            warn!(
6272                "PoP verification error for paid notify key {}: {e}",
6273                hex::encode(notify.key)
6274            );
6275            return Ok(());
6276        }
6277    }
6278
6279    if let Err(e) = paid_list.insert(&notify.key).await {
6280        warn!("Failed to add paid notify key to PaidForList: {e}");
6281    }
6282
6283    Ok(())
6284}
6285
6286#[allow(clippy::too_many_arguments)]
6287async fn dispatch_neighbor_sync_request(
6288    source: PeerId,
6289    request: protocol::NeighborSyncRequest,
6290    ctx: &ReplicationMessageHandlerContext,
6291    is_bootstrapping: bool,
6292    my_commitment: Option<StorageCommitment>,
6293    request_id: u64,
6294    received_at: Instant,
6295    rr_message_id: Option<&str>,
6296) -> Result<()> {
6297    let guard = match admit_bounded_responder(
6298        &ctx.neighbor_sync_responder_admission_semaphore,
6299        &ctx.neighbor_sync_responder_inflight,
6300        &source,
6301        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6302        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6303    )
6304    .await
6305    {
6306        Ok(guard) => guard,
6307        Err(failure) => {
6308            audit_metrics::record_responder_admission_drop(
6309                ReplicationResponderClass::NeighborSync,
6310                failure.reason.into(),
6311            );
6312            warn!(
6313                responder_class = "neighbor_sync",
6314                source = %source,
6315                "Neighbor-sync response dropped at admission: {failure}"
6316            );
6317            return Ok(());
6318        }
6319    };
6320
6321    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6322    let p2p_node = Arc::clone(&ctx.p2p_node);
6323    let storage = Arc::clone(&ctx.storage);
6324    let paid_list = Arc::clone(&ctx.paid_list);
6325    let queues = Arc::clone(&ctx.queues);
6326    let config = Arc::clone(&ctx.config);
6327    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6328    let sync_history = Arc::clone(&ctx.sync_history);
6329    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6330    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6331    let request_timeout = ctx.config.verification_request_timeout;
6332    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6333    ctx.detached_task_tracker.spawn(async move {
6334        let _guard = guard;
6335        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6336            debug!(
6337                responder_class = "neighbor_sync",
6338                source = %source,
6339                "Neighbor-sync responder worker pool closed before dequeue"
6340            );
6341            return;
6342        };
6343        if request_is_stale(received_at, request_timeout) {
6344            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6345            debug!(
6346                responder_class = "neighbor_sync",
6347                source = %source,
6348                request_age_ms = received_at.elapsed().as_millis(),
6349                "Stale neighbor-sync request shed at dequeue"
6350            );
6351            return;
6352        }
6353        if let Err(e) = handle_neighbor_sync_request(
6354            &source,
6355            &request,
6356            &p2p_node,
6357            &storage,
6358            &paid_list,
6359            &queues,
6360            &config,
6361            is_bootstrapping,
6362            &bootstrap_state,
6363            &sync_history,
6364            &sync_cycle_epoch,
6365            &repair_proofs,
6366            my_commitment,
6367            request_id,
6368            rr_message_id.as_deref(),
6369        )
6370        .await
6371        {
6372            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6373        }
6374    });
6375
6376    Ok(())
6377}
6378
6379#[allow(clippy::too_many_arguments)]
6380async fn handle_neighbor_sync_request(
6381    source: &PeerId,
6382    request: &protocol::NeighborSyncRequest,
6383    p2p_node: &Arc<P2PNode>,
6384    storage: &Arc<LmdbStorage>,
6385    paid_list: &Arc<PaidList>,
6386    queues: &Arc<RwLock<ReplicationQueues>>,
6387    config: &ReplicationConfig,
6388    is_bootstrapping: bool,
6389    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6390    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6391    sync_cycle_epoch: &Arc<RwLock<u64>>,
6392    repair_proofs: &Arc<RwLock<RepairProofs>>,
6393    my_commitment: Option<StorageCommitment>,
6394    request_id: u64,
6395    rr_message_id: Option<&str>,
6396) -> Result<()> {
6397    let self_id = *p2p_node.peer_id();
6398
6399    // No per-request hint count limit: the wire message size limit
6400    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6401    // challenges, sync hints don't drive expensive computation — they just
6402    // enter the verification queue. A per-request limit here would break
6403    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6404
6405    // Build response (outbound hints).
6406    let (response, sent_replica_hints, sender_in_rt) =
6407        neighbor_sync::handle_sync_request_with_proofs(
6408            source,
6409            request,
6410            p2p_node,
6411            storage,
6412            paid_list,
6413            config,
6414            is_bootstrapping,
6415            my_commitment.clone(),
6416        )
6417        .await;
6418
6419    // Send response.
6420    let response_sent = send_replication_response_checked(
6421        source,
6422        p2p_node,
6423        request_id,
6424        ReplicationMessageBody::NeighborSyncResponse(response),
6425        rr_message_id,
6426        None,
6427    )
6428    .await;
6429
6430    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6431    if !sender_in_rt {
6432        return Ok(());
6433    }
6434
6435    // Update sync history for this peer before recording repair proofs so a
6436    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6437    {
6438        let mut history = sync_history.write().await;
6439        let record = history.entry(*source).or_insert(PeerSyncRecord {
6440            last_sync: None,
6441            cycles_since_sync: 0,
6442        });
6443        record.last_sync = Some(Instant::now());
6444        record.cycles_since_sync = 0;
6445    }
6446
6447    if response_sent && !request.bootstrapping {
6448        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6449            .await;
6450    }
6451
6452    // Admit inbound hints and queue for verification.
6453    let outcome = admit_and_queue_hints(
6454        &self_id,
6455        source,
6456        &request.replica_hints,
6457        &request.paid_hints,
6458        p2p_node,
6459        config,
6460        storage,
6461        paid_list,
6462        queues,
6463    )
6464    .await;
6465
6466    // Track discovered keys for bootstrap drain detection so that hints
6467    // admitted via inbound sync requests are not missed. Capacity-rejected
6468    // hints keep this source on the "not yet drained" list until its next
6469    // sync re-admits them; a clean cycle clears the source.
6470    if is_bootstrapping {
6471        let live_discovered = outcome.discovered.clone();
6472        let outcomes = [(*source, outcome)];
6473        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6474    }
6475
6476    Ok(())
6477}
6478
6479async fn handle_verification_request(
6480    source: &PeerId,
6481    request: &protocol::VerificationRequest,
6482    storage: &Arc<LmdbStorage>,
6483    paid_list: &Arc<PaidList>,
6484    p2p_node: &Arc<P2PNode>,
6485    request_id: u64,
6486    rr_message_id: Option<&str>,
6487) -> Result<()> {
6488    #[derive(Clone, Copy)]
6489    enum CachedPaidLookup {
6490        NotChecked,
6491        Checked(Option<bool>),
6492    }
6493
6494    #[derive(Clone, Copy)]
6495    struct CachedVerificationLookup {
6496        present: Option<bool>,
6497        paid: CachedPaidLookup,
6498    }
6499
6500    if verification_request_exceeds_limit(request.keys.len()) {
6501        warn!(
6502            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6503            request.keys.len(),
6504        );
6505        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6506        return Ok(());
6507    }
6508
6509    let requested_keys = request.keys.as_slice();
6510
6511    if request.paid_list_check_indices.len() > request.keys.len() {
6512        warn!(
6513            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6514            request.paid_list_check_indices.len(),
6515            request.keys.len(),
6516        );
6517        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6518        return Ok(());
6519    }
6520
6521    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6522    let paid_check_set: HashSet<u32> = request
6523        .paid_list_check_indices
6524        .iter()
6525        .copied()
6526        .filter(|&idx| {
6527            if idx >= keys_len {
6528                warn!(
6529                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6530                    requested_keys.len(),
6531                );
6532                false
6533            } else {
6534                true
6535            }
6536        })
6537        .collect();
6538
6539    let mut results = Vec::with_capacity(requested_keys.len());
6540    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6541    for (i, key) in requested_keys.iter().enumerate() {
6542        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6543        let cached = lookup_cache.entry(*key).or_insert_with(|| {
6544            let present = match storage.exists(key) {
6545                Ok(present) => Some(present),
6546                Err(e) => {
6547                    warn!(
6548                        "Verification request from {source}: failed to check storage for {}: {e}",
6549                        hex::encode(key)
6550                    );
6551                    None
6552                }
6553            };
6554            CachedVerificationLookup {
6555                present,
6556                paid: CachedPaidLookup::NotChecked,
6557            }
6558        });
6559
6560        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6561            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6562                Ok(paid) => Some(paid),
6563                Err(e) => {
6564                    warn!(
6565                        "Verification request from {source}: failed to check paid-list for {}: {e}",
6566                        hex::encode(key)
6567                    );
6568                    None
6569                }
6570            });
6571        }
6572
6573        let paid = if needs_paid {
6574            match cached.paid {
6575                CachedPaidLookup::Checked(paid) => paid,
6576                CachedPaidLookup::NotChecked => None,
6577            }
6578        } else {
6579            None
6580        };
6581
6582        if cached.present.is_none() && paid.is_none() {
6583            continue;
6584        }
6585
6586        results.push(protocol::KeyVerificationResult {
6587            key: *key,
6588            present: cached.present.unwrap_or(false),
6589            paid,
6590        });
6591    }
6592
6593    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6594
6595    Ok(())
6596}
6597
6598async fn dispatch_verification_request(
6599    source: PeerId,
6600    request: protocol::VerificationRequest,
6601    ctx: &ReplicationMessageHandlerContext,
6602    request_id: u64,
6603    received_at: Instant,
6604    rr_message_id: Option<&str>,
6605) -> Result<()> {
6606    let guard = match admit_bounded_responder(
6607        &ctx.verification_responder_admission_semaphore,
6608        &ctx.verification_responder_inflight,
6609        &source,
6610        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6611        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6612    )
6613    .await
6614    {
6615        Ok(guard) => guard,
6616        Err(failure) => {
6617            audit_metrics::record_responder_admission_drop(
6618                ReplicationResponderClass::Verification,
6619                failure.reason.into(),
6620            );
6621            warn!(
6622                responder_class = "verification",
6623                source = %source,
6624                "Verification response dropped at admission: {failure}"
6625            );
6626            return Ok(());
6627        }
6628    };
6629
6630    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6631    let storage = Arc::clone(&ctx.storage);
6632    let paid_list = Arc::clone(&ctx.paid_list);
6633    let p2p_node = Arc::clone(&ctx.p2p_node);
6634    let request_timeout = ctx.config.verification_request_timeout;
6635    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6636    ctx.detached_task_tracker.spawn(async move {
6637        let _guard = guard;
6638        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6639            debug!(
6640                responder_class = "verification",
6641                source = %source,
6642                "Verification responder worker pool closed before dequeue"
6643            );
6644            return;
6645        };
6646        if request_is_stale(received_at, request_timeout) {
6647            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6648            debug!(
6649                responder_class = "verification",
6650                source = %source,
6651                request_age_ms = received_at.elapsed().as_millis(),
6652                "Stale verification request shed at dequeue"
6653            );
6654            return;
6655        }
6656        if let Err(e) = handle_verification_request(
6657            &source,
6658            &request,
6659            &storage,
6660            &paid_list,
6661            &p2p_node,
6662            request_id,
6663            rr_message_id.as_deref(),
6664        )
6665        .await
6666        {
6667            debug!(source = %source, "Verification request handling failed: {e}");
6668        }
6669    });
6670
6671    Ok(())
6672}
6673
6674const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6675    key_count > MAX_INCOMING_VERIFICATION_KEYS
6676}
6677
6678async fn send_verification_results(
6679    source: &PeerId,
6680    p2p_node: &Arc<P2PNode>,
6681    request_id: u64,
6682    results: Vec<protocol::KeyVerificationResult>,
6683    rr_message_id: Option<&str>,
6684) {
6685    send_replication_response(
6686        source,
6687        p2p_node,
6688        request_id,
6689        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6690        rr_message_id,
6691    )
6692    .await;
6693}
6694
6695async fn dispatch_fetch_request(
6696    source: PeerId,
6697    request: protocol::FetchRequest,
6698    ctx: &ReplicationMessageHandlerContext,
6699    request_id: u64,
6700    received_at: Instant,
6701    rr_message_id: Option<&str>,
6702) -> Result<()> {
6703    let guard = match admit_bounded_responder(
6704        &ctx.fetch_responder_admission_semaphore,
6705        &ctx.fetch_responder_inflight,
6706        &source,
6707        FETCH_RESPONDER_MAX_OUTSTANDING,
6708        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6709    )
6710    .await
6711    {
6712        Ok(guard) => guard,
6713        Err(failure) => {
6714            audit_metrics::record_responder_admission_drop(
6715                ReplicationResponderClass::Fetch,
6716                failure.reason.into(),
6717            );
6718            warn!(
6719                responder_class = "fetch",
6720                source = %source,
6721                "Fetch response dropped at admission: {failure}"
6722            );
6723            return Ok(());
6724        }
6725    };
6726
6727    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6728    let storage = Arc::clone(&ctx.storage);
6729    let p2p_node = Arc::clone(&ctx.p2p_node);
6730    let request_timeout = ctx.config.fetch_request_timeout;
6731    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6732    ctx.detached_task_tracker.spawn(async move {
6733        let _guard = guard;
6734        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6735            debug!(
6736                responder_class = "fetch",
6737                source = %source,
6738                "Fetch responder worker pool closed before dequeue"
6739            );
6740            return;
6741        };
6742        if request_is_stale(received_at, request_timeout) {
6743            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6744            debug!(
6745                responder_class = "fetch",
6746                source = %source,
6747                request_age_ms = received_at.elapsed().as_millis(),
6748                "Stale fetch request shed at dequeue"
6749            );
6750            return;
6751        }
6752        if let Err(e) = handle_fetch_request(
6753            &source,
6754            &request,
6755            &storage,
6756            &p2p_node,
6757            request_id,
6758            rr_message_id.as_deref(),
6759        )
6760        .await
6761        {
6762            debug!(source = %source, "Fetch request handling failed: {e}");
6763        }
6764    });
6765
6766    Ok(())
6767}
6768
6769fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6770    received_at.elapsed() >= timeout
6771}
6772
6773async fn handle_fetch_request(
6774    source: &PeerId,
6775    request: &protocol::FetchRequest,
6776    storage: &Arc<LmdbStorage>,
6777    p2p_node: &Arc<P2PNode>,
6778    request_id: u64,
6779    rr_message_id: Option<&str>,
6780) -> Result<()> {
6781    let response = match storage.get(&request.key).await {
6782        Ok(Some(data)) => protocol::FetchResponse::Success {
6783            key: request.key,
6784            data,
6785        },
6786        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
6787        Err(e) => protocol::FetchResponse::Error {
6788            key: request.key,
6789            reason: format!("{e}"),
6790        },
6791    };
6792
6793    send_replication_response(
6794        source,
6795        p2p_node,
6796        request_id,
6797        ReplicationMessageBody::FetchResponse(response),
6798        rr_message_id,
6799    )
6800    .await;
6801
6802    Ok(())
6803}
6804
6805/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
6806/// the prune-confirmation audit, which reuses the same wire message): reply with
6807/// per-key possession digests.
6808struct AuditResponderCompletion {
6809    response_kind: &'static str,
6810    sent: bool,
6811    processing: Duration,
6812    response_send: Duration,
6813}
6814
6815async fn handle_audit_challenge_msg(
6816    source: &PeerId,
6817    challenge: &protocol::AuditChallenge,
6818    storage: &Arc<LmdbStorage>,
6819    p2p_node: &Arc<P2PNode>,
6820    is_bootstrapping: bool,
6821    reply: ReplyRoute<'_>,
6822) -> Result<AuditResponderCompletion> {
6823    #[allow(clippy::cast_possible_truncation)]
6824    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
6825    info!(
6826        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
6827        challenge.keys.len(),
6828        is_bootstrapping,
6829        reply.rr_message_id.is_some(),
6830    );
6831
6832    let processing_started = Instant::now();
6833    let response = audit::handle_audit_challenge(
6834        challenge,
6835        storage,
6836        p2p_node.peer_id(),
6837        is_bootstrapping,
6838        stored_chunks,
6839    )
6840    .await;
6841    let processing = processing_started.elapsed();
6842    let response_kind = audit_response_kind(&response);
6843
6844    let response_send_started = Instant::now();
6845    let sent = send_replication_response_checked(
6846        source,
6847        p2p_node,
6848        reply.request_id,
6849        ReplicationMessageBody::AuditResponse(response),
6850        reply.rr_message_id,
6851        Some(reply.protocol),
6852    )
6853    .await;
6854    let response_send = response_send_started.elapsed();
6855
6856    Ok(AuditResponderCompletion {
6857        response_kind,
6858        sent,
6859        processing,
6860        response_send,
6861    })
6862}
6863
6864#[allow(clippy::too_many_arguments)]
6865fn log_audit_responder_completion(
6866    metrics: &AuditResponderMetrics,
6867    source: PeerId,
6868    class: AuditResponderClass,
6869    kind: &'static str,
6870    challenge_id: u64,
6871    work_items: usize,
6872    response_kind: &'static str,
6873    sent: bool,
6874    received_at: Instant,
6875    worker_started: Instant,
6876    processing: Duration,
6877    response_send: Duration,
6878) {
6879    let dispatch = worker_started.saturating_duration_since(received_at);
6880    let total = received_at.elapsed();
6881    metrics.record_completed(source, processing, total, sent);
6882    if sent {
6883        info!(
6884            target: "ant_node::replication::audit_responder",
6885            event = "completed",
6886            kind,
6887            responder_class = class.as_str(),
6888            source = %source,
6889            challenge_id,
6890            work_items,
6891            response = response_kind,
6892            sent,
6893            dispatch_ms = dispatch.as_millis(),
6894            processing_ms = processing.as_millis(),
6895            response_send_ms = response_send.as_millis(),
6896            total_ms = total.as_millis(),
6897            "Audit responder request completed"
6898        );
6899    } else {
6900        warn!(
6901            target: "ant_node::replication::audit_responder",
6902            event = "completed",
6903            kind,
6904            responder_class = class.as_str(),
6905            source = %source,
6906            challenge_id,
6907            work_items,
6908            response = response_kind,
6909            sent,
6910            dispatch_ms = dispatch.as_millis(),
6911            processing_ms = processing.as_millis(),
6912            response_send_ms = response_send.as_millis(),
6913            total_ms = total.as_millis(),
6914            "Audit responder request completed without sending a reply"
6915        );
6916    }
6917}
6918
6919/// Where a reply goes and how it is addressed.
6920///
6921/// Grouped because the audit responder needs all three together and one of them
6922/// is not derivable from the body: during the rollout window a possession reply
6923/// may have to go out on the core id rather than its family's own (see
6924/// [`is_legacy_possession_challenge`]).
6925struct ReplyRoute<'a> {
6926    /// Correlates the reply with the challenge, at the replication layer.
6927    request_id: u64,
6928    /// Present when the challenge arrived over request-response, in which case
6929    /// the reply rides the same exchange back.
6930    rr_message_id: Option<&'a str>,
6931    /// The protocol id to answer on.
6932    protocol: &'static str,
6933}
6934
6935fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
6936    match response {
6937        protocol::AuditResponse::Digests { .. } => "digests",
6938        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
6939        protocol::AuditResponse::Rejected { .. } => "rejected",
6940    }
6941}
6942
6943fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
6944    match response {
6945        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
6946        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
6947        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
6948    }
6949}
6950
6951fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
6952    match response {
6953        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
6954        protocol::SubtreeAuditResponse::Bootstrapping { .. }
6955        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
6956    }
6957}
6958
6959fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
6960    match response {
6961        protocol::SubtreeSliceResponse::Items { .. } => "items",
6962        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
6963        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
6964    }
6965}
6966
6967fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
6968    match response {
6969        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
6970        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
6971    }
6972}
6973
6974// ---------------------------------------------------------------------------
6975// Message sending helper
6976// ---------------------------------------------------------------------------
6977
6978/// Send a replication response message as a best-effort reply.
6979///
6980/// Encode and send failures are logged by the checked helper. Most response
6981/// paths do not need to branch on send success, so this wrapper keeps those
6982/// call sites explicit about their best-effort behavior.
6983async fn send_replication_response(
6984    peer: &PeerId,
6985    p2p_node: &Arc<P2PNode>,
6986    request_id: u64,
6987    body: ReplicationMessageBody,
6988    rr_message_id: Option<&str>,
6989) {
6990    let _ =
6991        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
6992            .await;
6993}
6994
6995/// Send a replication response message and report whether it was accepted.
6996///
6997/// Returns `true` after the message is encoded and accepted by the P2P send
6998/// path. Returns `false` after logging an encode or send failure. Repair-proof
6999/// recording uses this to avoid trusting hints that were not actually sent.
7000///
7001/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7002/// request-response path so saorsa-core can route it back to the caller's
7003/// `send_request` future. Otherwise it is sent as a plain message.
7004///
7005/// `protocol` overrides the id the body would route on by family. Exactly one
7006/// caller needs it: a possession challenge from a peer that predates the family
7007/// split has to be answered where it was asked (see
7008/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7009/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7010async fn send_replication_response_checked(
7011    peer: &PeerId,
7012    p2p_node: &Arc<P2PNode>,
7013    request_id: u64,
7014    body: ReplicationMessageBody,
7015    rr_message_id: Option<&str>,
7016    protocol: Option<&'static str>,
7017) -> bool {
7018    let msg = ReplicationMessage { request_id, body };
7019    let encoded = match msg.encode() {
7020        Ok(data) => data,
7021        Err(e) => {
7022            warn!("Failed to encode replication response: {e}");
7023            return false;
7024        }
7025    };
7026    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7027    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7028    // included for completeness. Other response variants (verification/audit/
7029    // commitment) are intentionally excluded — the round-2 audit reply is now a
7030    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7031    if matches!(
7032        msg.body,
7033        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7034    ) {
7035        protocol::record_served(peer, encoded.len());
7036    }
7037    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7038    let result = if let Some(msg_id) = rr_message_id {
7039        p2p_node
7040            .send_response(peer, protocol, msg_id, encoded)
7041            .await
7042    } else {
7043        p2p_node.send_message(peer, protocol, encoded, &[]).await
7044    };
7045    if let Err(e) = result {
7046        debug!("Failed to send replication response to {peer}: {e}");
7047        return false;
7048    }
7049    true
7050}
7051
7052async fn record_sent_replica_hints(
7053    peer: &PeerId,
7054    hints: &[neighbor_sync::SentReplicaHint],
7055    repair_proofs: &Arc<RwLock<RepairProofs>>,
7056    sync_cycle_epoch: &Arc<RwLock<u64>>,
7057) {
7058    if hints.is_empty() {
7059        return;
7060    }
7061
7062    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7063    let mut proofs = repair_proofs.write().await;
7064    for hint in hints {
7065        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7066            debug!(
7067                "Recorded repair hint proof for peer {peer} and key {}",
7068                hex::encode(hint.key)
7069            );
7070        }
7071    }
7072}
7073
7074// ---------------------------------------------------------------------------
7075// Neighbor sync round
7076// ---------------------------------------------------------------------------
7077
7078/// Run one neighbor sync round.
7079#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7080async fn run_neighbor_sync_round(
7081    p2p_node: &Arc<P2PNode>,
7082    storage: &Arc<LmdbStorage>,
7083    paid_list: &Arc<PaidList>,
7084    queues: &Arc<RwLock<ReplicationQueues>>,
7085    config: &ReplicationConfig,
7086    sync_state: &Arc<RwLock<NeighborSyncState>>,
7087    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7088    sync_cycle_epoch: &Arc<RwLock<u64>>,
7089    repair_proofs: &Arc<RwLock<RepairProofs>>,
7090    is_bootstrapping: &Arc<RwLock<bool>>,
7091    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7092    commitment_state: &Arc<ResponderCommitmentState>,
7093    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7094    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7095    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7096    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7097    gossip_audit: &GossipAuditTrigger,
7098) {
7099    let self_id = *p2p_node.peer_id();
7100    let bootstrapping = *is_bootstrapping.read().await;
7101
7102    // Check if cycle is complete; start new one if needed.
7103    // We check under a read lock, then release it before the expensive
7104    // prune pass and DHT snapshot so other tasks are not starved.
7105    let cycle_complete = sync_state.read().await.is_cycle_complete();
7106    if cycle_complete {
7107        // A completed local neighbor-sync cycle advances the epoch component
7108        // of repair-proof maturity. The per-key wall-clock minimum age is
7109        // checked when audits are selected.
7110        {
7111            let mut history = sync_history.write().await;
7112            for record in history.values_mut() {
7113                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7114            }
7115        }
7116        {
7117            let mut epoch = sync_cycle_epoch.write().await;
7118            *epoch = epoch.saturating_add(1);
7119        }
7120
7121        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7122        // Prune candidacy is unconditional once the hysteresis elapses;
7123        // bootstrap state only defers the remote prune-confirmation audits
7124        // until bootstrap has drained.
7125        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7126        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7127            self_id: &self_id,
7128            storage,
7129            paid_list,
7130            p2p_node,
7131            config,
7132            sync_state,
7133            repair_proofs,
7134            allow_remote_prune_audits,
7135            commitment_state: Some(commitment_state),
7136            audit_challenge_coordinator,
7137        })
7138        .await;
7139
7140        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7141        let neighbors =
7142            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7143                .await;
7144
7145        // Now re-acquire write lock and re-check before swapping cycle.
7146        let mut state = sync_state.write().await;
7147        if state.is_cycle_complete() {
7148            // Preserve cooldown and bootstrap-claim tracking across cycles.
7149            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7150            // would reset the abuse detection timer every cycle.
7151            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7152            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7153            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7154            let old_prune_cursor = state.prune_cursor;
7155            *state = NeighborSyncState::new_cycle(neighbors);
7156            state.last_sync_times = old_sync_times;
7157            state.bootstrap_claims = old_bootstrap_claims;
7158            state.bootstrap_claim_history = old_bootstrap_claim_history;
7159            state.prune_cursor = old_prune_cursor;
7160        }
7161    }
7162
7163    // Select batch of peers.
7164    let batch = {
7165        let mut state = sync_state.write().await;
7166        neighbor_sync::select_sync_batch(
7167            &mut state,
7168            config.neighbor_sync_peer_count,
7169            config.neighbor_sync_cooldown,
7170        )
7171    };
7172
7173    if batch.is_empty() {
7174        return;
7175    }
7176
7177    debug!("Neighbor sync: syncing with {} peers", batch.len());
7178
7179    // Snapshot our current commitment once per round so all peers in
7180    // this batch see the same thing (gossip is the responder's attestation;
7181    // same value across the batch is fine and reduces RwLock churn). Atomically
7182    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7183    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7184    let my_commitment = commitment_state
7185        .current_for_gossip()
7186        .map(|b| b.commitment().clone());
7187
7188    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7189        &batch,
7190        storage,
7191        paid_list,
7192        p2p_node,
7193        config.close_group_size,
7194        config.paid_list_close_group_size,
7195    )
7196    .await;
7197
7198    // Sync with each peer in the batch.
7199    for peer in &batch {
7200        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7201        let outcome = neighbor_sync::sync_with_peer_with_hints(
7202            peer,
7203            p2p_node,
7204            config,
7205            bootstrapping,
7206            hints,
7207            my_commitment.clone(),
7208        )
7209        .await;
7210
7211        if let Some(outcome) = outcome {
7212            handle_sync_response(
7213                &self_id,
7214                peer,
7215                &outcome.response,
7216                &outcome.sent_replica_hints,
7217                p2p_node,
7218                config,
7219                bootstrapping,
7220                bootstrap_state,
7221                storage,
7222                paid_list,
7223                queues,
7224                sync_state,
7225                sync_history,
7226                sync_cycle_epoch,
7227                repair_proofs,
7228                last_commitment_by_peer,
7229                ever_capable_peers,
7230                sig_verify_attempts,
7231                gossip_audit,
7232            )
7233            .await;
7234        } else {
7235            // Sync failed -- remove peer and try to fill slot.
7236            let replacement = {
7237                let mut state = sync_state.write().await;
7238                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7239            };
7240
7241            // Attempt sync with the replacement peer (if one was found).
7242            if let Some(replacement_peer) = replacement {
7243                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7244                    std::slice::from_ref(&replacement_peer),
7245                    storage,
7246                    paid_list,
7247                    p2p_node,
7248                    config.close_group_size,
7249                    config.paid_list_close_group_size,
7250                )
7251                .await;
7252                let hints = replacement_hints
7253                    .remove(&replacement_peer)
7254                    .unwrap_or_default();
7255                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7256                    &replacement_peer,
7257                    p2p_node,
7258                    config,
7259                    bootstrapping,
7260                    hints,
7261                    my_commitment.clone(),
7262                )
7263                .await;
7264
7265                if let Some(outcome) = replacement_outcome {
7266                    handle_sync_response(
7267                        &self_id,
7268                        &replacement_peer,
7269                        &outcome.response,
7270                        &outcome.sent_replica_hints,
7271                        p2p_node,
7272                        config,
7273                        bootstrapping,
7274                        bootstrap_state,
7275                        storage,
7276                        paid_list,
7277                        queues,
7278                        sync_state,
7279                        sync_history,
7280                        sync_cycle_epoch,
7281                        repair_proofs,
7282                        last_commitment_by_peer,
7283                        ever_capable_peers,
7284                        sig_verify_attempts,
7285                        gossip_audit,
7286                    )
7287                    .await;
7288                }
7289            }
7290        }
7291    }
7292}
7293
7294/// Process a successful neighbor sync response: record the sync, check for
7295/// bootstrap claim abuse, and admit inbound hints.
7296#[allow(clippy::too_many_arguments)]
7297async fn handle_sync_response(
7298    self_id: &PeerId,
7299    peer: &PeerId,
7300    resp: &NeighborSyncResponse,
7301    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7302    p2p_node: &Arc<P2PNode>,
7303    config: &ReplicationConfig,
7304    bootstrapping: bool,
7305    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7306    storage: &Arc<LmdbStorage>,
7307    paid_list: &Arc<PaidList>,
7308    queues: &Arc<RwLock<ReplicationQueues>>,
7309    sync_state: &Arc<RwLock<NeighborSyncState>>,
7310    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7311    sync_cycle_epoch: &Arc<RwLock<u64>>,
7312    repair_proofs: &Arc<RwLock<RepairProofs>>,
7313    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7314    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7315    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7316    gossip_audit: &GossipAuditTrigger,
7317) {
7318    // Ingest the peer's commitment if they piggybacked one on the response.
7319    // Same verification as the request path (peer-id binding + signature);
7320    // forged commitments are dropped at the edge. A *changed* commitment here
7321    // is a gossip-audit trigger just like on the request path — so a peer that
7322    // only ever answers sync (never initiates) is still audited (ADR-0002).
7323    if let Some(target) = ingest_peer_commitment(
7324        peer,
7325        resp.commitment.as_ref(),
7326        p2p_node,
7327        last_commitment_by_peer,
7328        ever_capable_peers,
7329        sig_verify_attempts,
7330    )
7331    .await
7332    {
7333        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7334    }
7335
7336    // Record successful sync.
7337    {
7338        let mut state = sync_state.write().await;
7339        neighbor_sync::record_successful_sync(&mut state, peer);
7340    }
7341    {
7342        let mut history = sync_history.write().await;
7343        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7344            last_sync: None,
7345            cycles_since_sync: 0,
7346        });
7347        record.last_sync = Some(Instant::now());
7348        record.cycles_since_sync = 0;
7349    }
7350
7351    // Process inbound hints from response (skip if peer is bootstrapping).
7352    if resp.bootstrapping {
7353        // Gap 6: BootstrapClaimAbuse grace period enforcement.
7354        // Separate state mutation from network I/O to avoid holding the
7355        // write lock across report_trust_event.
7356        let should_report = {
7357            let now = Instant::now();
7358            let mut state = sync_state.write().await;
7359            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7360                BootstrapClaimObservation::WithinGrace { .. } => false,
7361                BootstrapClaimObservation::PastGrace { first_seen } => {
7362                    warn!(
7363                        "Peer {peer} has been claiming bootstrap for {:?}, \
7364                         exceeding grace period of {:?} — reporting abuse",
7365                        now.duration_since(first_seen),
7366                        config.bootstrap_claim_grace_period,
7367                    );
7368                    true
7369                }
7370                BootstrapClaimObservation::Repeated { first_seen } => {
7371                    warn!(
7372                        "Peer {peer} repeated bootstrap claim after previously stopping; \
7373                         first claim was {:?} ago — reporting abuse",
7374                        now.duration_since(first_seen),
7375                    );
7376                    true
7377                }
7378            }
7379        };
7380        if should_report {
7381            p2p_node
7382                .report_trust_event(
7383                    peer,
7384                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7385                )
7386                .await;
7387        }
7388    } else {
7389        // Peer is not claiming bootstrap; clear active claim while retaining
7390        // history so the peer cannot start a second grace window later.
7391        {
7392            let mut state = sync_state.write().await;
7393            state.clear_active_bootstrap_claim(peer);
7394        }
7395        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7396        let outcome = admit_and_queue_hints(
7397            self_id,
7398            peer,
7399            &resp.replica_hints,
7400            &resp.paid_hints,
7401            p2p_node,
7402            config,
7403            storage,
7404            paid_list,
7405            queues,
7406        )
7407        .await;
7408
7409        // Track discovered keys for bootstrap drain detection so that hints
7410        // admitted via regular neighbor sync are not missed. Capacity-
7411        // rejected hints keep this source on the "not yet drained" list
7412        // until its next sync replays them; a clean cycle clears it.
7413        if bootstrapping {
7414            let live_discovered = outcome.discovered.clone();
7415            let outcomes = [(*peer, outcome)];
7416            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7417                .await;
7418        }
7419    }
7420}
7421
7422/// Admit hints and queue them for verification, returning newly-discovered keys.
7423///
7424/// Shared by neighbor-sync request handling, response handling, and bootstrap
7425/// sync so that admission + queueing logic lives in one place.
7426#[allow(clippy::too_many_arguments)]
7427/// Outcome of [`admit_and_queue_hints`].
7428///
7429/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7430/// available; that source is kept outstanding until it re-hints. `displaced`
7431/// tracks older borrowed hints reclaimed for another sender; only the key is
7432/// dropped from bootstrap tracking — the former owner's standing is untouched
7433/// (see [`publish_bootstrap_admission_outcomes`]).
7434struct AdmissionOutcome {
7435    discovered: HashSet<XorName>,
7436    capacity_rejected_count: usize,
7437    displaced: Vec<CapacityDisplacement>,
7438}
7439
7440/// Publish one atomic admission unit into bootstrap drain accounting.
7441///
7442/// Only sources that were themselves capacity-rejected are kept outstanding.
7443/// A fairness displacement forfeits the displaced *key* but never stamps its
7444/// former owner: reclaiming a borrowed slot is this node's own fairness
7445/// decision, so charging it to the victim would let a sustained flooder wedge
7446/// our bootstrap drain open through an unrelated honest peer. Clean sources
7447/// are cleared only after every outcome in the unit is known, so peer
7448/// iteration order cannot falsely clear a rejection recorded later in the same
7449/// bootstrap batch.
7450async fn publish_bootstrap_admission_outcomes(
7451    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7452    outcomes: &[(PeerId, AdmissionOutcome)],
7453    live_discovered: &HashSet<XorName>,
7454) {
7455    let mut rejected_sources = HashSet::new();
7456    let mut clean_sources = HashSet::new();
7457    let mut displaced_keys = HashSet::new();
7458
7459    for (source, outcome) in outcomes {
7460        if outcome.capacity_rejected_count > 0 {
7461            rejected_sources.insert(*source);
7462        } else {
7463            clean_sources.insert(*source);
7464        }
7465        // Only the *key* of a fairness displacement is forfeited here, never
7466        // its owner's standing. Reclaiming a borrowed slot is our own fairness
7467        // decision, not a failure by the peer that held it: stamping the victim
7468        // would let a sustained flooder block our bootstrap drain through an
7469        // unrelated honest peer that never overflowed us. The displaced key
7470        // falls to the same post-bootstrap neighbor-sync and audit/repair
7471        // recovery path that TTL expiry already relies on.
7472        for displacement in &outcome.displaced {
7473            displaced_keys.insert(displacement.key);
7474        }
7475    }
7476    clean_sources.retain(|source| !rejected_sources.contains(source));
7477
7478    let now = Instant::now();
7479    let mut state = bootstrap_state.write().await;
7480    for key in displaced_keys {
7481        state.remove_key(&key);
7482    }
7483    state.pending_keys.extend(live_discovered);
7484    for source in clean_sources {
7485        state.capacity_rejected_sources.remove(&source);
7486    }
7487    for source in rejected_sources {
7488        // First-seen: a source that keeps overflowing us must not keep its own
7489        // record fresh, or bootstrap never drains and auditing stays off.
7490        state.note_capacity_rejected(source, now);
7491    }
7492}
7493
7494#[allow(clippy::too_many_arguments)]
7495async fn admit_and_queue_hints(
7496    self_id: &PeerId,
7497    source_peer: &PeerId,
7498    replica_hints: &[XorName],
7499    paid_hints: &[XorName],
7500    p2p_node: &Arc<P2PNode>,
7501    config: &ReplicationConfig,
7502    storage: &Arc<LmdbStorage>,
7503    paid_list: &Arc<PaidList>,
7504    queues: &Arc<RwLock<ReplicationQueues>>,
7505) -> AdmissionOutcome {
7506    let pending_keys: HashSet<XorName> = {
7507        let q = queues.read().await;
7508        q.pending_keys().into_iter().collect()
7509    };
7510
7511    let admitted = admission::admit_hints(
7512        self_id,
7513        replica_hints,
7514        paid_hints,
7515        p2p_node,
7516        config,
7517        storage,
7518        paid_list,
7519        &pending_keys,
7520    )
7521    .await;
7522
7523    let mut q = queues.write().await;
7524    queue_admitted_hints(source_peer, admitted, storage, &mut q)
7525}
7526
7527fn queue_admitted_hints(
7528    source_peer: &PeerId,
7529    admitted: admission::AdmissionResult,
7530    storage: &LmdbStorage,
7531    q: &mut ReplicationQueues,
7532) -> AdmissionOutcome {
7533    let mut discovered = HashSet::new();
7534    let mut capacity_rejected_count: usize = 0;
7535    let mut displaced = Vec::new();
7536    let now = Instant::now();
7537
7538    for key in admitted.replica_keys {
7539        if !storage.exists(&key).unwrap_or(false) {
7540            let result = q.add_pending_verify(
7541                key,
7542                VerificationEntry {
7543                    state: VerificationState::PendingVerify,
7544                    verified_sources: Vec::new(),
7545                    tried_sources: HashSet::new(),
7546                    created_at: now,
7547                    next_verify_at: now,
7548                    hint_sources: HashSet::from([*source_peer]),
7549                    // Non-empty: this peer claimed possession, so it is a
7550                    // fetch-source candidate. Derives HintPipeline::Replica.
7551                    replica_hint_sources: HashSet::from([*source_peer]),
7552                },
7553            );
7554            match result {
7555                crate::replication::scheduling::AdmissionResult::Admitted => {
7556                    discovered.insert(key);
7557                }
7558                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7559                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7560                    capacity_rejected_count += 1;
7561                }
7562            }
7563        }
7564    }
7565
7566    for key in admitted.paid_only_keys {
7567        let result = q.add_pending_verify(
7568            key,
7569            VerificationEntry {
7570                state: VerificationState::PendingVerify,
7571                verified_sources: Vec::new(),
7572                tried_sources: HashSet::new(),
7573                created_at: now,
7574                next_verify_at: now,
7575                hint_sources: HashSet::from([*source_peer]),
7576                // Empty: a paid hint makes no possession claim, so this peer is
7577                // not a fetch source. Derives HintPipeline::PaidOnly.
7578                replica_hint_sources: HashSet::new(),
7579            },
7580        );
7581        match result {
7582            crate::replication::scheduling::AdmissionResult::Admitted => {
7583                discovered.insert(key);
7584            }
7585            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7586            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7587                capacity_rejected_count += 1;
7588            }
7589        }
7590    }
7591
7592    if capacity_rejected_count > 0 {
7593        debug!(
7594            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7595             rejected at queue capacity; source will need to re-hint after pending_verify drains"
7596        );
7597    }
7598
7599    displaced.extend(q.take_capacity_displacements());
7600
7601    AdmissionOutcome {
7602        discovered,
7603        capacity_rejected_count,
7604        displaced,
7605    }
7606}
7607
7608// ---------------------------------------------------------------------------
7609// Verification cycle
7610// ---------------------------------------------------------------------------
7611
7612/// Run one verification cycle: process pending keys through quorum checks.
7613#[allow(clippy::too_many_lines)]
7614async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7615    let cycle_started = Instant::now();
7616    let VerificationCycleContext {
7617        p2p_node,
7618        paid_list,
7619        storage,
7620        queues,
7621        config,
7622        bootstrap_state,
7623        is_bootstrapping,
7624        bootstrap_complete_notify,
7625        last_commitment_by_peer,
7626        ever_capable_peers,
7627        recent_provers,
7628    } = ctx;
7629
7630    // Self-heal the bootstrap drain before any early-return below: abandoned
7631    // capacity-rejection records must expire, and a drain condition that
7632    // became true without a triggering event must still be observed. Pending
7633    // peer requests legitimately block the drain check itself, but not this.
7634    expire_and_recheck_bootstrap_drain(
7635        bootstrap_state,
7636        queues,
7637        is_bootstrapping,
7638        bootstrap_complete_notify,
7639        config.capacity_rejected_max_age(),
7640    )
7641    .await;
7642
7643    // Bootstrap admits one concurrent neighbor batch as an atomic source
7644    // aggregation unit. Do not select newly queued keys until that batch's
7645    // hints and drain accounting have both been published.
7646    if bootstrap_state.read().await.pending_peer_requests > 0 {
7647        return;
7648    }
7649
7650    // Evict stale entries that have been pending too long (e.g. unreachable
7651    // verification targets during a network partition).
7652    let stale_pending_keys = {
7653        let mut q = queues.write().await;
7654        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7655    };
7656    if !stale_pending_keys.is_empty() {
7657        update_bootstrap_after_verification(
7658            &stale_pending_keys,
7659            bootstrap_state,
7660            queues,
7661            is_bootstrapping,
7662            bootstrap_complete_notify,
7663        )
7664        .await;
7665    }
7666
7667    let pending_keys = {
7668        let mut q = queues.write().await;
7669        // Re-check while holding the queue write lock used by fair selection.
7670        // This closes the race
7671        // where a bootstrap batch starts after the early check: the batch
7672        // cannot publish its hints under the queue write lock until this
7673        // selection either returns or declines to run.
7674        if bootstrap_state.read().await.pending_peer_requests > 0 {
7675            return;
7676        }
7677        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7678    };
7679
7680    if pending_keys.is_empty() {
7681        return;
7682    }
7683    let initial_pending_count = pending_keys.len();
7684
7685    let self_id = *p2p_node.peer_id();
7686
7687    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
7688    // step 4). Paid-list membership settles *validity* — the key is known-paid,
7689    // so no quorum round is needed. It says nothing about whether we must hold
7690    // the bytes; that is decided below.
7691    let mut local_paid_keys = Vec::new();
7692    let mut keys_needing_network = Vec::new();
7693    let mut terminal_keys: Vec<XorName> = Vec::new();
7694    {
7695        let mut q = queues.write().await;
7696        for key in &pending_keys {
7697            if paid_list.contains(key).unwrap_or(false) {
7698                if q.set_pending_state(key, VerificationState::PaidListVerified) {
7699                    local_paid_keys.push(*key);
7700                }
7701            } else {
7702                keys_needing_network.push(*key);
7703            }
7704        }
7705    }
7706
7707    // Storage responsibility is a live routing question, decided identically
7708    // for every known-paid key regardless of how the advertising peer labelled
7709    // its hint — a replica hint is a possession *claim* by the sender, never
7710    // permission for us to store. Held outside the queue lock: `is_responsible`
7711    // awaits into the DHT manager.
7712    let mut local_paid_presence_probe_keys = Vec::new();
7713    if !local_paid_keys.is_empty() {
7714        let mut terminal_paid = Vec::new();
7715        for key in local_paid_keys {
7716            if storage.exists(&key).unwrap_or(false) {
7717                terminal_paid.push(key);
7718            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
7719                // We carry storage responsibility and lack the bytes. The
7720                // presence probe below discovers holders to fetch from; it is
7721                // source discovery, not re-verification.
7722                local_paid_presence_probe_keys.push(key);
7723            } else {
7724                terminal_paid.push(key);
7725            }
7726        }
7727
7728        if !terminal_paid.is_empty() {
7729            let mut q = queues.write().await;
7730            for key in terminal_paid {
7731                q.remove_pending(&key);
7732                terminal_keys.push(key);
7733            }
7734        }
7735    }
7736
7737    let local_paid_probe_count = local_paid_presence_probe_keys.len();
7738    let keys_needing_network_count = keys_needing_network.len();
7739
7740    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
7741    // step 4, authorization succeeds immediately; run a presence-only probe
7742    // to find any holder we can fetch from.
7743    if !local_paid_presence_probe_keys.is_empty() {
7744        let targets = quorum::compute_presence_targets(
7745            &local_paid_presence_probe_keys,
7746            p2p_node,
7747            config,
7748            &self_id,
7749        )
7750        .await;
7751        let evidence = quorum::run_verification_round(
7752            &local_paid_presence_probe_keys,
7753            &targets,
7754            p2p_node,
7755            config,
7756        )
7757        .await;
7758
7759        let mut q = queues.write().await;
7760        for key in local_paid_presence_probe_keys {
7761            if storage.exists(&key).unwrap_or(false) {
7762                q.remove_pending(&key);
7763                terminal_keys.push(key);
7764                continue;
7765            }
7766            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
7767                quorum::present_sources_for_key(&key, ev, &targets)
7768            });
7769            if let Some(entry) = q.get_pending(&key) {
7770                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
7771            }
7772            if sources.is_empty() {
7773                warn!(
7774                    "Locally paid key {} has no responding holders yet; deferring retry",
7775                    hex::encode(key)
7776                );
7777                q.defer_pending(&key, config.verification_request_timeout);
7778            } else {
7779                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7780                // Atomic remove+enqueue: if fetch_queue is at capacity, the
7781                // pending entry is preserved and retried next cycle (no
7782                // silent drop of verified replica-repair work).
7783                let _ = q.promote_pending_to_fetch(key, distance, sources);
7784            }
7785        }
7786    }
7787
7788    // Steps 2-5: Network verification (skipped if all keys resolved locally).
7789    if !keys_needing_network.is_empty() {
7790        // Step 2: Compute targets and run network verification round.
7791        let targets =
7792            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
7793                .await;
7794
7795        let evidence =
7796            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
7797
7798        // Step 3: Evaluate results — collect outcomes without holding the write
7799        // lock across paid-list I/O.
7800        //
7801        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
7802        // table and recent_provers cache up front so the synchronous
7803        // evaluate_key_evidence_with_holder_check predicate can consult
7804        // them without awaiting. The predicate downgrades a Present
7805        // claim to Unresolved unless the peer is credited for that key.
7806        // Snapshot per-peer commitment data. We need two views:
7807        //   - `commitment_by_peer_snapshot`: peers that currently have
7808        //     a verified commitment record on file (used to look up
7809        //     their current hash).
7810        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
7811        //     set. Sourced from a separate set rather than the
7812        //     commitment map so eviction (PeerRemoved cleanup, sybil
7813        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
7814        //     a previously-v12 peer to "legacy" credit-unconditionally.
7815        //     Legacy / pre-v12 peers that have never sent a commitment
7816        //     remain absent from the set and are credited via the
7817        //     legacy path so mixed-version networks stay live.
7818        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
7819            let map = last_commitment_by_peer.read().await;
7820            map.iter()
7821                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
7822                // of every peer's ~5 KiB commitment.
7823                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
7824                .collect()
7825        };
7826        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
7827        // Take a full snapshot of recent_provers under the read lock,
7828        // then release. The cache is bounded (16/key × keys), so the
7829        // clone is cheap.
7830        let provers_snapshot = recent_provers.read().await.clone();
7831        // For the replica-fetch path, we need to know whether THIS
7832        // node already holds the key being verified. The v12 §6
7833        // holder-credit gate is meant to prevent uncredited Present
7834        // claims from contributing to paid-list / reward quorum for
7835        // keys we DO hold (and could audit ourselves). For keys we
7836        // are trying to FETCH (i.e. not in local storage), there is
7837        // no possible local audit credit, and gating the presence
7838        // quorum on credit would deadlock replica-repair in a
7839        // fully v12-capable close group.
7840        let mut locally_held: HashSet<XorName> = HashSet::new();
7841        for key in &keys_needing_network {
7842            if storage.exists(key).unwrap_or(false) {
7843                locally_held.insert(*key);
7844            }
7845        }
7846        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
7847            if !locally_held.contains(key) {
7848                // Replica-fetch path: we don't hold this key, so we
7849                // cannot have collected audit credit for it. Trust
7850                // Present claims to drive fetch-source promotion;
7851                // chunk-PUT payment_verifier is the security backstop
7852                // when the bytes actually arrive.
7853                return true;
7854            }
7855            if !capable_peer_snapshot.contains(peer) {
7856                // Pre-v12 / legacy peer that has never gossiped a
7857                // commitment. The v12 §6 holder-eligibility check
7858                // doesn't apply: their Present evidence comes through
7859                // the legacy path and we credit it unconditionally
7860                // so a mixed-version network stays live during
7861                // transition.
7862                return true;
7863            }
7864            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
7865                // Peer is commitment_capable (sticky) but currently
7866                // has no live commitment record on file (e.g. their
7867                // last gossip was evicted from the LRU cache, or it
7868                // failed verification). Withhold credit until they
7869                // re-prove storage under a fresh commitment.
7870                return false;
7871            };
7872            provers_snapshot.is_credited_holder(key, peer, hash)
7873        };
7874
7875        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
7876        {
7877            let q = queues.read().await;
7878            for key in &keys_needing_network {
7879                let Some(ev) = evidence.get(key) else {
7880                    continue;
7881                };
7882                if q.get_pending(key).is_none() {
7883                    continue;
7884                }
7885                let outcome = quorum::evaluate_key_evidence_with_holder_check(
7886                    key,
7887                    ev,
7888                    &targets,
7889                    config,
7890                    holder_credit,
7891                );
7892                evaluated.push((*key, outcome));
7893            }
7894        } // read lock released
7895
7896        // Step 4: Insert verified keys into PaidForList (no lock held).
7897        let mut paid_insert_keys: Vec<XorName> = Vec::new();
7898        for (key, outcome) in &evaluated {
7899            if matches!(
7900                outcome,
7901                KeyVerificationOutcome::QuorumVerified { .. }
7902                    | KeyVerificationOutcome::PaidListVerified { .. }
7903            ) {
7904                paid_insert_keys.push(*key);
7905            }
7906        }
7907        for key in &paid_insert_keys {
7908            if let Err(e) = paid_list.insert(key).await {
7909                warn!("Failed to add verified key to PaidForList: {e}");
7910            }
7911        }
7912
7913        // Verification established validity; the paid-list insert above records
7914        // it. Downloading the bytes is a separate duty, owed only by the
7915        // storage-admission group, asked on the same terms for every verified
7916        // key — the advertising peer's replica/paid labelling is a claim about
7917        // itself and carries no authority over what we store. This check is a
7918        // cheap pre-filter that keeps never-responsible keys out of the fetch
7919        // queue entirely; the authoritative gate is the per-attempt recheck in
7920        // `execute_single_fetch`, because a key can wait in the nearest-first
7921        // fetch queue long enough for this promotion-time answer to go stale.
7922        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
7923        for (key, outcome) in &evaluated {
7924            if matches!(
7925                outcome,
7926                KeyVerificationOutcome::QuorumVerified { .. }
7927                    | KeyVerificationOutcome::PaidListVerified { .. }
7928            ) && !storage.exists(key).unwrap_or(false)
7929                && is_storage_admitted(&self_id, key, p2p_node, config).await
7930            {
7931                fetch_allowed_keys.insert(*key);
7932            }
7933        }
7934
7935        // Step 5: Update queues with the evaluated outcomes.
7936        let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
7937        let mut q = queues.write().await;
7938        for (key, outcome) in evaluated {
7939            let replica_hint_sources = q
7940                .get_pending(&key)
7941                .map(|entry| entry.replica_hint_sources.clone())
7942                .unwrap_or_default();
7943            if let Some(ev) = evidence.get(&key) {
7944                if let Some(source) =
7945                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
7946                {
7947                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
7948                }
7949            }
7950            match outcome {
7951                KeyVerificationOutcome::QuorumVerified { sources }
7952                | KeyVerificationOutcome::PaidListVerified { sources } => {
7953                    let mut fetch_sources = sources;
7954                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
7955                    let fetch_eligible = fetch_allowed_keys.contains(&key);
7956                    if fetch_eligible && !fetch_sources.is_empty() {
7957                        let distance =
7958                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
7959                        // Atomic remove+enqueue: on fetch_queue capacity miss
7960                        // the pending entry is preserved so this verified key
7961                        // is retried on the next cycle (no silent drop).
7962                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
7963                        // Not terminal — either moved to fetch queue, or
7964                        // retained as pending until queue drains.
7965                    } else if fetch_eligible && fetch_sources.is_empty() {
7966                        warn!(
7967                            "Verified storage-admitted key {} has no holders yet; deferring retry",
7968                            hex::encode(key)
7969                        );
7970                        q.defer_pending(&key, config.verification_request_timeout);
7971                    } else {
7972                        q.remove_pending(&key);
7973                        terminal_keys.push(key);
7974                    }
7975                }
7976                KeyVerificationOutcome::QuorumFailed => {
7977                    q.remove_pending(&key);
7978                    terminal_keys.push(key);
7979                }
7980                KeyVerificationOutcome::QuorumInconclusive => {
7981                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
7982                    q.defer_pending(&key, config.verification_request_timeout);
7983                }
7984            }
7985        }
7986        drop(q);
7987
7988        for (peer, bad_hint_count) in bad_singleton_hints {
7989            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
7990            warn!(
7991                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
7992                 sole-source replica hints; \
7993                 reporting {reports} bounded trust failure(s)"
7994            );
7995            for _ in 0..reports {
7996                p2p_node
7997                    .report_trust_event(
7998                        &peer,
7999                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8000                    )
8001                    .await;
8002            }
8003        }
8004    }
8005
8006    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8007    // the drain condition.
8008    update_bootstrap_after_verification(
8009        &terminal_keys,
8010        bootstrap_state,
8011        queues,
8012        is_bootstrapping,
8013        bootstrap_complete_notify,
8014    )
8015    .await;
8016
8017    let (pending_after, fetch_after, in_flight_after) = {
8018        let q = queues.read().await;
8019        (
8020            q.pending_count(),
8021            q.fetch_queue_count(),
8022            q.in_flight_count(),
8023        )
8024    };
8025    let terminal_key_count = terminal_keys.len();
8026    let elapsed_ms = cycle_started.elapsed().as_millis();
8027
8028    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8029        info!(
8030            target: "ant_node::replication::verification",
8031            "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}",
8032        );
8033    } else {
8034        debug!(
8035            target: "ant_node::replication::verification",
8036            "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}",
8037        );
8038    }
8039}
8040
8041/// Add peers that claimed possession as fallback fetch sources.
8042///
8043/// Paid-only advertisers make no possession claim and are absent from
8044/// `replica_hint_sources` by construction, so they are never added.
8045fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8046    for source in replica_hint_sources {
8047        if !sources.contains(source) {
8048            sources.push(*source);
8049        }
8050    }
8051}
8052
8053/// Return the sole replica advertiser when either the close group definitively
8054/// rejects the key or the advertiser explicitly denies possessing it.
8055/// Paid-only advertisements, corroborated replica hints, and inconclusive
8056/// rounds without that direct contradiction are deliberately non-penalizing.
8057fn punishable_singleton_replica_hint_source(
8058    replica_hint_sources: &HashSet<PeerId>,
8059    outcome: &KeyVerificationOutcome,
8060    evidence: &crate::replication::types::KeyVerificationEvidence,
8061) -> Option<PeerId> {
8062    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8063    // reserved for peers that actually claimed possession.
8064    if replica_hint_sources.len() != 1 {
8065        return None;
8066    }
8067    let source = *replica_hint_sources.iter().next()?;
8068    let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8069    let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8070
8071    (rejected_by_close_group || denied_possession).then_some(source)
8072}
8073
8074/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8075/// bootstrap pending set and transition out of bootstrapping when drained.
8076async fn update_bootstrap_after_verification(
8077    terminal_keys: &[XorName],
8078    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8079    queues: &Arc<RwLock<ReplicationQueues>>,
8080    is_bootstrapping: &Arc<RwLock<bool>>,
8081    bootstrap_complete_notify: &Arc<Notify>,
8082) {
8083    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8084        return;
8085    }
8086    {
8087        let mut bs = bootstrap_state.write().await;
8088        for key in terminal_keys {
8089            bs.remove_key(key);
8090        }
8091    }
8092    let q = queues.read().await;
8093    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8094        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8095    }
8096}
8097
8098/// Retire bootstrap work owed by a peer that permanently left the routing
8099/// table, then immediately re-check drain so this removal can complete
8100/// bootstrap without waiting for an unrelated pipeline event.
8101async fn update_bootstrap_after_peer_removed(
8102    peer: &PeerId,
8103    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8104    queues: &Arc<RwLock<ReplicationQueues>>,
8105    is_bootstrapping: &Arc<RwLock<bool>>,
8106    bootstrap_complete_notify: &Arc<Notify>,
8107) {
8108    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8109    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8110
8111    if !orphaned_keys.is_empty() {
8112        let mut state = bootstrap_state.write().await;
8113        for key in &orphaned_keys {
8114            state.remove_key(key);
8115        }
8116    }
8117
8118    if orphaned_keys.is_empty() && !cleared_rejection {
8119        return;
8120    }
8121    let q = queues.read().await;
8122    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8123        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8124    }
8125}
8126
8127/// Periodic bootstrap-drain self-healing, run on every verification worker
8128/// tick until bootstrap drains.
8129///
8130/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8131/// recording of a capacity rejection leaves an entry no future event can
8132/// clear — `max_age` expiry is its only exit. And a clean-cycle
8133/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8134/// quiet node the drain condition can become true with nothing left to
8135/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8136/// drain itself, so this is invoked before `run_verification_cycle`'s
8137/// early-returns.
8138async fn expire_and_recheck_bootstrap_drain(
8139    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8140    queues: &Arc<RwLock<ReplicationQueues>>,
8141    is_bootstrapping: &Arc<RwLock<bool>>,
8142    bootstrap_complete_notify: &Arc<Notify>,
8143    max_age: Duration,
8144) {
8145    if bootstrap_state.read().await.is_drained() {
8146        return;
8147    }
8148    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8149    let q = queues.read().await;
8150    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8151        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8152    }
8153}
8154
8155/// Set `is_bootstrapping` to `false` and wake all waiters.
8156async fn complete_bootstrap(
8157    is_bootstrapping: &Arc<RwLock<bool>>,
8158    bootstrap_complete_notify: &Arc<Notify>,
8159) {
8160    *is_bootstrapping.write().await = false;
8161    bootstrap_complete_notify.notify_waiters();
8162    info!("Replication bootstrap complete");
8163}
8164
8165// ---------------------------------------------------------------------------
8166// Fetch types and single-fetch executor
8167// ---------------------------------------------------------------------------
8168
8169/// Result classification for a single fetch attempt.
8170enum FetchResult {
8171    /// Data fetched, integrity-checked, and stored successfully.
8172    Stored,
8173    /// Content-address integrity check failed — do not retry.
8174    IntegrityFailed,
8175    /// Source failed (network error or non-success response) — retryable.
8176    SourceFailed,
8177    /// Live routing state no longer places this node in the storage-admission
8178    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8179    /// the fetch was serving has lapsed, so no alternate source is tried and
8180    /// no trust event is reported: the source did nothing wrong.
8181    NoLongerResponsible,
8182}
8183
8184/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8185/// worker loop to update queue state.
8186struct FetchOutcome {
8187    key: XorName,
8188    result: FetchResult,
8189}
8190
8191/// What the fetch worker must do next for a key whose fetch attempt resolved.
8192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8193enum FetchFollowUp {
8194    /// The key terminally left the fetch pipeline (its in-flight entry is
8195    /// removed and any verification retry-slot reservation released); the
8196    /// caller must run bootstrap accounting for it.
8197    Terminal,
8198    /// The key returned to `pending_verify` for a later verification round.
8199    RequeuedForVerification,
8200    /// Retry immediately from this next untried verified source.
8201    RetryFrom(PeerId),
8202}
8203
8204/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8205///
8206/// Split out of the fetch-worker loop so the per-variant queue transitions
8207/// are unit-testable without a live network. The caller holds the queues
8208/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8209/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8210/// retry-slot reservation, and the caller's terminal handling shrinks the
8211/// bootstrap pending set — dropping the key without that accounting would
8212/// stall bootstrap drain forever.
8213///
8214/// The nursery `option_if_let_else` rewrite is impossible here: both
8215/// `map_or_else` closures would need `&mut *q` simultaneously.
8216#[allow(clippy::option_if_let_else)]
8217fn apply_fetch_result(
8218    q: &mut ReplicationQueues,
8219    key: &XorName,
8220    result: &FetchResult,
8221    verification_retry_after: Duration,
8222) -> FetchFollowUp {
8223    match result {
8224        FetchResult::Stored | FetchResult::NoLongerResponsible => {
8225            q.complete_fetch(key);
8226            FetchFollowUp::Terminal
8227        }
8228        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8229            if let Some(next_peer) = q.retry_fetch(key) {
8230                FetchFollowUp::RetryFrom(next_peer)
8231            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8232                FetchFollowUp::RequeuedForVerification
8233            } else {
8234                FetchFollowUp::Terminal
8235            }
8236        }
8237    }
8238}
8239
8240/// Whether this node currently sits inside the storage-admission group for
8241/// `key`, per live local routing state.
8242///
8243/// This is the one question every storage decision in this module asks; see
8244/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8245/// network I/O — but it awaits into the DHT manager, so callers must not
8246/// hold the queues lock across it.
8247async fn is_storage_admitted(
8248    self_id: &PeerId,
8249    key: &XorName,
8250    p2p_node: &Arc<P2PNode>,
8251    config: &ReplicationConfig,
8252) -> bool {
8253    admission::is_responsible(
8254        self_id,
8255        key,
8256        p2p_node,
8257        storage_admission_width(config.close_group_size),
8258    )
8259    .await
8260}
8261
8262#[allow(clippy::too_many_lines)]
8263/// Execute a single fetch request against `source` for `key`.
8264///
8265/// Handles encoding, network I/O, integrity checking, storage, and trust
8266/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8267/// queue state without holding any locks during the network round-trip.
8268///
8269/// This is the authoritative storage-responsibility gate: each attempt —
8270/// including every per-source retry, which re-enters here — rechecks live
8271/// routing state before spending bandwidth, and once more before writing
8272/// bytes that arrived after a round-trip. The verification-time check that
8273/// promoted the key into the fetch queue is only a pre-filter; the queue is
8274/// nearest-first and deep, so a promotion decision can go stale under
8275/// topology churn before the key is ever dequeued.
8276async fn execute_single_fetch(
8277    p2p_node: Arc<P2PNode>,
8278    storage: Arc<LmdbStorage>,
8279    config: Arc<ReplicationConfig>,
8280    key: XorName,
8281    source: PeerId,
8282) -> FetchOutcome {
8283    let self_id = *p2p_node.peer_id();
8284    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8285        debug!(
8286            "Skipping fetch for {}: no longer in the storage-admission group",
8287            hex::encode(key)
8288        );
8289        return FetchOutcome {
8290            key,
8291            result: FetchResult::NoLongerResponsible,
8292        };
8293    }
8294
8295    let request = protocol::FetchRequest { key };
8296    let msg = ReplicationMessage {
8297        request_id: rand::thread_rng().gen::<u64>(),
8298        body: ReplicationMessageBody::FetchRequest(request),
8299    };
8300
8301    let encoded = match msg.encode() {
8302        Ok(data) => data,
8303        Err(e) => {
8304            warn!("Failed to encode fetch request: {e}");
8305            return FetchOutcome {
8306                key,
8307                result: FetchResult::SourceFailed,
8308            };
8309        }
8310    };
8311
8312    let result = p2p_node
8313        .send_request(
8314            &source,
8315            REPLICATION_PROTOCOL_ID,
8316            encoded,
8317            config.fetch_request_timeout,
8318        )
8319        .await;
8320
8321    match result {
8322        Ok(response) => {
8323            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8324                p2p_node
8325                    .report_trust_event(
8326                        &source,
8327                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8328                    )
8329                    .await;
8330                return FetchOutcome {
8331                    key,
8332                    result: FetchResult::SourceFailed,
8333                };
8334            };
8335
8336            match resp_msg.body {
8337                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8338                    key: resp_key,
8339                    data,
8340                }) => {
8341                    // Validate the response key matches the requested key.
8342                    // A malicious peer could serve valid data for a different
8343                    // key, passing integrity checks while the requested key
8344                    // is falsely marked as fetched.
8345                    if resp_key != key {
8346                        warn!(
8347                            "Fetch response key mismatch: requested {}, got {}",
8348                            hex::encode(key),
8349                            hex::encode(resp_key)
8350                        );
8351                        p2p_node
8352                            .report_trust_event(
8353                                &source,
8354                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8355                            )
8356                            .await;
8357                        return FetchOutcome {
8358                            key,
8359                            result: FetchResult::IntegrityFailed,
8360                        };
8361                    }
8362
8363                    // Enforce chunk size invariant on fetched data.
8364                    // Checked before the content-address hash to avoid
8365                    // hashing up to 10 MiB of oversized junk data.
8366                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8367                        warn!(
8368                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8369                            hex::encode(resp_key),
8370                            data.len(),
8371                            crate::ant_protocol::MAX_CHUNK_SIZE,
8372                        );
8373                        p2p_node
8374                            .report_trust_event(
8375                                &source,
8376                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8377                            )
8378                            .await;
8379                        return FetchOutcome {
8380                            key,
8381                            result: FetchResult::IntegrityFailed,
8382                        };
8383                    }
8384
8385                    // Content-address integrity check.
8386                    let computed = crate::client::compute_address(&data);
8387                    if computed != resp_key {
8388                        warn!(
8389                            "Fetched record integrity check failed: expected {}, got {}",
8390                            hex::encode(resp_key),
8391                            hex::encode(computed)
8392                        );
8393                        p2p_node
8394                            .report_trust_event(
8395                                &source,
8396                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8397                            )
8398                            .await;
8399                        return FetchOutcome {
8400                            key,
8401                            result: FetchResult::IntegrityFailed,
8402                        };
8403                    }
8404
8405                    // Responsibility can lapse during the network round-trip.
8406                    // The bandwidth is already spent; declining the write is
8407                    // what still avoids the disk write and the later
8408                    // fetch→store→prune churn. Edge flapping is dampened by
8409                    // the margin `storage_admission_width` adds over
8410                    // `close_group_size`.
8411                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8412                        debug!(
8413                            "Fetched {} but responsibility lapsed in transit; not storing",
8414                            hex::encode(key)
8415                        );
8416                        return FetchOutcome {
8417                            key,
8418                            result: FetchResult::NoLongerResponsible,
8419                        };
8420                    }
8421
8422                    if let Err(e) = storage.put(&resp_key, &data).await {
8423                        warn!(
8424                            "Failed to store fetched record {}: {e}",
8425                            hex::encode(resp_key)
8426                        );
8427                        return FetchOutcome {
8428                            key,
8429                            result: FetchResult::SourceFailed,
8430                        };
8431                    }
8432
8433                    FetchOutcome {
8434                        key,
8435                        result: FetchResult::Stored,
8436                    }
8437                }
8438                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8439                    ..
8440                }) => {
8441                    // This peer was selected as a fetch source because it
8442                    // recently answered `Present` during verification. A
8443                    // subsequent NotFound is evidence of a stale/false claim
8444                    // or chunk wiping, so penalize lightly and try another
8445                    // verified source.
8446                    warn!(
8447                        "Fetch: verified source {source} returned NotFound for {}",
8448                        hex::encode(key)
8449                    );
8450                    p2p_node
8451                        .report_trust_event(
8452                            &source,
8453                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8454                        )
8455                        .await;
8456                    FetchOutcome {
8457                        key,
8458                        result: FetchResult::SourceFailed,
8459                    }
8460                }
8461                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8462                    reason,
8463                    ..
8464                }) => {
8465                    warn!(
8466                        "Fetch: peer {source} returned error for {}: {reason}",
8467                        hex::encode(key)
8468                    );
8469                    p2p_node
8470                        .report_trust_event(
8471                            &source,
8472                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8473                        )
8474                        .await;
8475                    FetchOutcome {
8476                        key,
8477                        result: FetchResult::SourceFailed,
8478                    }
8479                }
8480                _ => {
8481                    // Unexpected message type — treat as malformed.
8482                    p2p_node
8483                        .report_trust_event(
8484                            &source,
8485                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8486                        )
8487                        .await;
8488                    FetchOutcome {
8489                        key,
8490                        result: FetchResult::SourceFailed,
8491                    }
8492                }
8493            }
8494        }
8495        Err(e) => {
8496            debug!("Fetch request to {source} failed: {e}");
8497            // No ApplicationFailure here — P2PNode::send_request() already
8498            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
8499            FetchOutcome {
8500                key,
8501                result: FetchResult::SourceFailed,
8502            }
8503        }
8504    }
8505}
8506
8507// ---------------------------------------------------------------------------
8508// Audit result handler
8509// ---------------------------------------------------------------------------
8510
8511/// Format the first confirmed-failed key as a 16-hex-char label.
8512///
8513/// Pairs with `challenged_peer` to form a stable cross-host correlation
8514/// handle in the audit-failure log line, e.g.
8515///
8516/// ```text
8517/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
8518/// ```
8519///
8520/// Falls back to `"0x"` when the list is empty so the log line never
8521/// contains a misleading default.
8522fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8523    confirmed_failed_keys.first().map_or_else(
8524        || "0x".to_string(),
8525        |k| format!("0x{}", hex::encode(&k[..8])),
8526    )
8527}
8528
8529/// Execute the side effects for a subtree storage-commitment audit failure.
8530///
8531/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
8532/// legitimately time out on slow or loaded honest peers, so it never touches the
8533/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
8534/// failures still penalise immediately and revoke holder credit.
8535async fn handle_subtree_failed_audit(
8536    challenged_peer: &PeerId,
8537    confirmed_failed_key_count: usize,
8538    reason: &AuditFailureReason,
8539    p2p_node: &Arc<P2PNode>,
8540    sync_state: &Arc<RwLock<NeighborSyncState>>,
8541    recent_provers: &Arc<RwLock<RecentProvers>>,
8542) {
8543    if matches!(reason, AuditFailureReason::Timeout) {
8544        debug!(
8545            "Audit timeout for {challenged_peer} fully graced \
8546             (subtree audit does not evict on timeout)"
8547        );
8548        return;
8549    }
8550
8551    // The caller already logged the rich failure line with reason + per-category
8552    // summary; avoid a redundant second error log here.
8553    let _ = confirmed_failed_key_count;
8554    {
8555        let mut state = sync_state.write().await;
8556        state.clear_active_bootstrap_claim(challenged_peer);
8557    }
8558    {
8559        let mut provers_guard = recent_provers.write().await;
8560        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8561    }
8562    p2p_node
8563        .report_trust_event(
8564            challenged_peer,
8565            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8566        )
8567        .await;
8568}
8569
8570/// Handle audit result: log findings and emit trust events.
8571async fn handle_subtree_audit_result(
8572    result: &AuditTickResult,
8573    p2p_node: &Arc<P2PNode>,
8574    sync_state: &Arc<RwLock<NeighborSyncState>>,
8575    recent_provers: &Arc<RwLock<RecentProvers>>,
8576    config: &ReplicationConfig,
8577) {
8578    match result {
8579        AuditTickResult::Passed {
8580            challenged_peer,
8581            keys_checked,
8582        } => {
8583            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8584            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8585            // Peer responded normally — clear the active bootstrap claim while
8586            // retaining history so a later claim is treated as repeated abuse.
8587            {
8588                let mut state = sync_state.write().await;
8589                state.clear_active_bootstrap_claim(challenged_peer);
8590            }
8591            p2p_node
8592                .report_trust_event(
8593                    challenged_peer,
8594                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8595                )
8596                .await;
8597        }
8598        AuditTickResult::Failed {
8599            evidence,
8600            no_response_class,
8601        } => {
8602            if let FailureEvidence::AuditFailure {
8603                challenged_peer,
8604                confirmed_failed_keys,
8605                summary,
8606                reason,
8607                ..
8608            } = evidence
8609            {
8610                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
8611                // Rich diagnostics (from main's audit-failure logging) + the
8612                // first-failed-key correlation handle.
8613                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8614                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8615                error!(
8616                    "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
8617                    audit_failure_class,
8618                    confirmed_failed_keys.len(),
8619                    summary.challenged_keys,
8620                    summary.absent_keys,
8621                    summary.digest_mismatch_keys,
8622                );
8623                // Route the side effects through the subtree-only failure path.
8624                // Responsible-chunk `AuditChallenge` handling intentionally uses
8625                // its own old immediate-penalty handler below.
8626                handle_subtree_failed_audit(
8627                    challenged_peer,
8628                    confirmed_failed_keys.len(),
8629                    reason,
8630                    p2p_node,
8631                    sync_state,
8632                    recent_provers,
8633                )
8634                .await;
8635            }
8636        }
8637        AuditTickResult::BootstrapClaim { peer } => {
8638            // Gap 6: BootstrapClaimAbuse grace period in audit path.
8639            // Separate state mutation from network I/O to avoid holding the
8640            // write lock across report_trust_event.
8641            let should_report = {
8642                let now = Instant::now();
8643                let mut state = sync_state.write().await;
8644                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8645                {
8646                    BootstrapClaimObservation::WithinGrace { .. } => {
8647                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8648                        false
8649                    }
8650                    BootstrapClaimObservation::PastGrace { first_seen } => {
8651                        warn!(
8652                            "Audit: peer {peer} claiming bootstrap past grace period \
8653                             ({:?} > {:?}), reporting abuse",
8654                            now.duration_since(first_seen),
8655                            config.bootstrap_claim_grace_period,
8656                        );
8657                        true
8658                    }
8659                    BootstrapClaimObservation::Repeated { first_seen } => {
8660                        warn!(
8661                            "Audit: peer {peer} repeated bootstrap claim after previously \
8662                             stopping; first claim was {:?} ago, reporting abuse",
8663                            now.duration_since(first_seen),
8664                        );
8665                        true
8666                    }
8667                }
8668            };
8669            if should_report {
8670                p2p_node
8671                    .report_trust_event(
8672                        peer,
8673                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8674                    )
8675                    .await;
8676            }
8677        }
8678        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8679    }
8680}
8681
8682/// Whether a confirmed audit failure with this reason clears the peer's active
8683/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
8684/// bootstrapping); every confirmed storage-integrity reason does.
8685///
8686/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
8687/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
8688/// still reports the normal audit trust penalty.
8689fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
8690    !matches!(reason, AuditFailureReason::Timeout)
8691}
8692
8693/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
8694/// events and manage bootstrap-claim state.
8695///
8696/// This is intentionally separate from the subtree audit result handler. A
8697/// responsible-chunk `AuditChallenge` `Failed` result reports
8698/// `ApplicationFailure` immediately for every reason, including `Timeout`,
8699/// restoring the pre-ADR-0002 behaviour.
8700#[allow(clippy::too_many_lines)]
8701async fn handle_audit_result(
8702    result: &AuditTickResult,
8703    p2p_node: &Arc<P2PNode>,
8704    sync_state: &Arc<RwLock<NeighborSyncState>>,
8705    config: &ReplicationConfig,
8706) {
8707    match result {
8708        AuditTickResult::Passed {
8709            challenged_peer,
8710            keys_checked,
8711        } => {
8712            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
8713            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8714            {
8715                let mut state = sync_state.write().await;
8716                state.clear_active_bootstrap_claim(challenged_peer);
8717            }
8718            p2p_node
8719                .report_trust_event(
8720                    challenged_peer,
8721                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
8722                )
8723                .await;
8724        }
8725        AuditTickResult::Failed {
8726            evidence,
8727            no_response_class,
8728        } => {
8729            if let FailureEvidence::AuditFailure {
8730                challenged_peer,
8731                confirmed_failed_keys,
8732                summary,
8733                reason,
8734                ..
8735            } = evidence
8736            {
8737                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
8738                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
8739                let audit_failure_class = no_response_class.unwrap_or("confirmed");
8740                error!(
8741                    "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
8742                    audit_failure_class,
8743                    confirmed_failed_keys.len(),
8744                    summary.challenged_keys,
8745                    summary.absent_keys,
8746                    summary.digest_mismatch_keys,
8747                );
8748                if audit_failure_clears_bootstrap_claim(reason) {
8749                    let mut state = sync_state.write().await;
8750                    state.clear_active_bootstrap_claim(challenged_peer);
8751                } else {
8752                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
8753                }
8754                p2p_node
8755                    .report_trust_event(
8756                        challenged_peer,
8757                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8758                    )
8759                    .await;
8760            }
8761        }
8762        AuditTickResult::BootstrapClaim { peer } => {
8763            let should_report = {
8764                let now = Instant::now();
8765                let mut state = sync_state.write().await;
8766                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
8767                {
8768                    BootstrapClaimObservation::WithinGrace { .. } => {
8769                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
8770                        false
8771                    }
8772                    BootstrapClaimObservation::PastGrace { first_seen } => {
8773                        warn!(
8774                            "Audit: peer {peer} claiming bootstrap past grace period \
8775                             ({:?} > {:?}), reporting abuse",
8776                            now.duration_since(first_seen),
8777                            config.bootstrap_claim_grace_period,
8778                        );
8779                        true
8780                    }
8781                    BootstrapClaimObservation::Repeated { first_seen } => {
8782                        warn!(
8783                            "Audit: peer {peer} repeated bootstrap claim after previously \
8784                             stopping; first claim was {:?} ago, reporting abuse",
8785                            now.duration_since(first_seen),
8786                        );
8787                        true
8788                    }
8789                }
8790            };
8791            if should_report {
8792                p2p_node
8793                    .report_trust_event(
8794                        peer,
8795                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8796                    )
8797                    .await;
8798            }
8799        }
8800        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
8801    }
8802}
8803
8804/// Whether a confirmed audit failure with this reason should revoke the
8805/// peer's `recent_provers` holder credit immediately (v12 §6).
8806///
8807/// `true` for any reason where the peer actually answered (or admitted
8808/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
8809/// bytes for committed key"), `MalformedResponse` — these prove the
8810/// peer no longer holds what it committed to, so it must not keep
8811/// holder credit for the proof TTL. `false` for `Timeout`: a single
8812/// dropped packet must not strip an honest peer; the 40-min TTL is the
8813/// deliberate liveness cushion there.
8814fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
8815    !matches!(reason, AuditFailureReason::Timeout)
8816}
8817
8818/// Apply the holder-credit revocation decision for a confirmed audit
8819/// failure. Pure over `RecentProvers` so the handler wiring is unit-
8820/// testable without a live `P2PNode`: the production `Failed` arm of
8821/// `handle_subtree_audit_result` calls exactly this.
8822fn apply_audit_failure_credit_revocation(
8823    provers: &mut RecentProvers,
8824    challenged_peer: &PeerId,
8825    reason: &AuditFailureReason,
8826) {
8827    if audit_failure_revokes_holder_credit(reason) {
8828        provers.forget_peer(challenged_peer);
8829    }
8830}
8831
8832// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
8833
8834// ---------------------------------------------------------------------------
8835// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
8836// ---------------------------------------------------------------------------
8837
8838/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
8839/// message handler passes one value instead of a long argument list; all
8840/// fields are cheap `Arc` clones.
8841#[derive(Clone)]
8842struct GossipAuditTrigger {
8843    p2p_node: Arc<P2PNode>,
8844    config: Arc<ReplicationConfig>,
8845    recent_provers: Arc<RwLock<RecentProvers>>,
8846    sync_state: Arc<RwLock<NeighborSyncState>>,
8847    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
8848    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
8849    /// only when a real audit is about to be sent — never by a losing lottery
8850    /// ticket — so gossip traffic alone can never suppress a paid first audit.
8851    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
8852    detached_task_tracker: TaskTracker,
8853    /// Gossip-private lottery attempt window: stamped on every roll (win or
8854    /// lose) so a gossip flood cannot re-roll the lottery within the window.
8855    /// The first-audit scheduler never reads this map.
8856    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
8857}
8858
8859/// What a gossip ingest yields for the audit trigger: the commitment hash to
8860/// pin and the `key_count` needed to size the response deadline from the actual
8861/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
8862/// or not) so a stable-keyset node stays auditable — not just on its first
8863/// commitment.
8864#[derive(Debug, Clone, Copy)]
8865struct AuditTarget {
8866    pin_hash: [u8; 32],
8867    key_count: u32,
8868}
8869
8870/// ADR-0004: a commitment that backed a payment, surfaced by the payment
8871/// verifier's cross-check so it can receive a **deterministic first audit**.
8872///
8873/// Sent from the verifier to the replication engine's first-audit drainer. The
8874/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
8875/// audits of the same peer revert to the gossip lottery), orders most-recently-
8876/// monetized first, and runs the same `run_subtree_audit` under the same
8877/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
8878#[derive(Debug, Clone, Copy)]
8879pub struct MonetizedPinEvent {
8880    /// The peer whose commitment backed the payment.
8881    pub peer: PeerId,
8882    /// The pinned commitment hash.
8883    pub pin: [u8; 32],
8884    /// The committed key count (sizes the audit deadline).
8885    pub key_count: u32,
8886    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
8887    /// pin whose quote is older than the answerability window (ADR-0004 A1
8888    /// guardrail A): with grace removed, challenging an aged-out pin would
8889    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
8890    pub quote_ts: SystemTime,
8891}
8892
8893/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
8894/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
8895/// stamps `now`), `false` if it was audited within
8896/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
8897/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
8898/// without a live node: a burst of gossips from one peer yields at most one
8899/// `true` per cooldown window.
8900fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8901    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8902    let known = match map.get(peer) {
8903        Some(&last) => {
8904            if now.saturating_duration_since(last) < cooldown {
8905                return false;
8906            }
8907            true
8908        }
8909        None => false,
8910    };
8911    // Bound the map under churn like its siblings (drop the oldest stamp) before
8912    // admitting a brand-new peer.
8913    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
8914        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
8915            map.remove(&victim);
8916        }
8917    }
8918    map.insert(*peer, now);
8919    true
8920}
8921
8922/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
8923/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
8924/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
8925/// already covered; the authoritative check-and-stamp still runs at promotion,
8926/// so this is only an optimization and never the security boundary.
8927fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
8928    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
8929    map.get(peer).map_or(true, |&last| {
8930        now.saturating_duration_since(last) >= cooldown
8931    })
8932}
8933
8934/// The gossip-audit launch decision in ONE place so the ordering is shared
8935/// between production and its test (ADR-0002 "occasional surprise exams").
8936///
8937/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
8938/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
8939/// sampled first, a gossip flood would re-roll it on every message until one
8940/// won, multiplying audits, so each peer gets at most one lottery roll per
8941/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
8942/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
8943/// also consults — only after a WIN, i.e. only when a real audit is about to be
8944/// sent. A losing ticket must never stamp `launched`: no challenge went on the
8945/// wire, so it must not defer a paid first audit (repeatable losses could
8946/// otherwise hold a monetized pin past its answerability window). Production
8947/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
8948/// test calls it with a deterministic `lottery_wins`, so a reorder regression
8949/// here fails the test.
8950fn audit_launch_decision(
8951    attempts: &mut HashMap<PeerId, Instant>,
8952    launched: &mut HashMap<PeerId, Instant>,
8953    peer: &PeerId,
8954    now: Instant,
8955    lottery_wins: bool,
8956) -> bool {
8957    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
8958    // window even on a loss; private to the gossip path).
8959    if !cooldown_allows_audit(attempts, peer, now) {
8960        return false;
8961    }
8962    // Gate 2: the probability lottery. A loss stops here and stamps nothing
8963    // shared.
8964    if !lottery_wins {
8965        return false;
8966    }
8967    // Gate 3: the shared actual-audit cooldown (a recent real audit from
8968    // either path still suppresses this launch), stamped only on launch.
8969    cooldown_allows_audit(launched, peer, now)
8970}
8971
8972/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
8973/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
8974/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
8975/// handling is never blocked on a network round-trip.
8976async fn maybe_trigger_gossip_audit(
8977    trigger: &GossipAuditTrigger,
8978    peer: &PeerId,
8979    target: AuditTarget,
8980) {
8981    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
8982    // lives in the pure `audit_launch_decision` so the ordering is shared with
8983    // its test. Sample the lottery here, then let the helper apply the gates.
8984    let now = Instant::now();
8985    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
8986    {
8987        // Lock order: attempts before the shared cooldown; this is the only
8988        // place both are held together.
8989        let mut attempts = trigger.lottery_attempts.write().await;
8990        let mut launched = trigger.cooldown.write().await;
8991        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
8992            return;
8993        }
8994    }
8995
8996    let detached_task_tracker = trigger.detached_task_tracker.clone();
8997    let trigger = trigger.clone();
8998    let peer = *peer;
8999    detached_task_tracker.spawn(async move {
9000        let credit = storage_commitment_audit::AuditCredit {
9001            recent_provers: &trigger.recent_provers,
9002        };
9003        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9004            &trigger.p2p_node,
9005            &trigger.config,
9006            &peer,
9007            target.pin_hash,
9008            target.key_count,
9009            Some(&credit),
9010            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9011        )
9012        .await;
9013        handle_subtree_audit_result(
9014            &result,
9015            &trigger.p2p_node,
9016            &trigger.sync_state,
9017            &trigger.recent_provers,
9018            &trigger.config,
9019        )
9020        .await;
9021    });
9022}
9023
9024/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9025///
9026/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9027/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9028/// of its last attempt. Holds one write lock across the decision so two
9029/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9030/// caller's expensive verify so a slow/failed verify still rate-limits the next
9031/// message. Bounds the map under a flood of distinct peer ids.
9032async fn sig_verify_rate_limit_ok(
9033    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9034    source: &PeerId,
9035    now: Instant,
9036) -> bool {
9037    let mut attempts = sig_verify_attempts.write().await;
9038    if let Some(&last) = attempts.get(source) {
9039        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9040            return false;
9041        }
9042    }
9043    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9044        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9045            attempts.remove(&victim);
9046        }
9047    }
9048    attempts.insert(*source, now);
9049    true
9050}
9051
9052/// Verify + store an inbound commitment from a gossip peer.
9053///
9054/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9055/// the bootstrap-sync loop. Drops the commitment unless all five gates
9056/// pass:
9057///   1. `source` is in our DHT routing table (sybil/churn cap).
9058///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9059///      binding to the authenticated transport peer).
9060///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9061///      (the embedded pubkey actually belongs to the claimed identity —
9062///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9063///   4. `verify_commitment_signature(commitment)` succeeds against the
9064///      embedded public key. The signed payload binds the pubkey, so an
9065///      adversary cannot swap the key while keeping the body.
9066///   5. The cache has room or this is an update for an existing entry
9067///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9068///
9069/// On all-pass, the commitment is stored as the auditor's per-peer
9070/// "last known commitment" for use as `expected_commitment_hash` in
9071/// future audits.
9072///
9073/// Failures (no commitment / mismatched peer id / bad signature) are
9074/// silent drops — gossip is best-effort and a malformed commitment from
9075/// one peer should not affect anything else.
9076///
9077/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9078/// or not its root changed), so the caller can run a probabilistic,
9079/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9080/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9081/// being auditable, so it cannot pass one audit and then delete data while
9082/// re-gossiping the same root forever. The cooldown + probability bound the
9083/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9084/// gate) or there is nothing to pin.
9085///
9086/// Handle a capable peer gossiping `None` (a commitment downgrade).
9087///
9088/// A capable peer that previously gossiped a commitment but now gossips `None`
9089/// is trying to drop off the audit path. Within the answerability window we keep
9090/// the cached commitment pinned AND return it as an audit target so this gossip
9091/// still schedules a subtree audit against the peer's last known commitment — if
9092/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9093/// the trigger MUST fire here or the downgrade is never re-challenged).
9094///
9095/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9096/// honours for its own retired commitment: once that elapses since we last
9097/// received the peer's commitment, an honest peer has legitimately retired that
9098/// root (its responder side `retire_current`s and lets it age out) and can no
9099/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9100/// failure, so we then forget the cached commitment (keeping the sticky
9101/// `commitment_capable` bit) and stop pinning it.
9102async fn handle_commitment_downgrade(
9103    source: &PeerId,
9104    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9105) -> Option<AuditTarget> {
9106    let now = Instant::now();
9107    let cached = {
9108        let map = last_commitment_by_peer.read().await;
9109        map.get(source).and_then(|rec| {
9110            if !rec.commitment_capable {
9111                return None;
9112            }
9113            let last = rec.last_commitment()?;
9114            let pin = rec.commitment_hash()?;
9115            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9116            Some((pin, last.key_count, fresh))
9117        })
9118    };
9119    match cached {
9120        Some((pin, key_count, true)) => {
9121            warn!(
9122                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9123                 (downgrade attempt); auditing against its last cached commitment"
9124            );
9125            Some(AuditTarget {
9126                pin_hash: pin,
9127                key_count,
9128            })
9129        }
9130        Some((_, _, false)) => {
9131            // Cached commitment has aged past the answerability window — forget
9132            // it so we stop pinning a root the peer is no longer obliged to
9133            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9134            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9135            // from this peer may have refreshed `received_at` in the gap between
9136            // our read and write locks; if so, leave its fresh commitment intact.
9137            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9138                let still_stale =
9139                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9140                if still_stale {
9141                    rec.clear_commitment();
9142                    debug!(
9143                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9144                         commitment aged past the answerability TTL; forgetting it"
9145                    );
9146                }
9147            }
9148            None
9149        }
9150        None => None,
9151    }
9152}
9153
9154async fn ingest_peer_commitment(
9155    source: &PeerId,
9156    commitment: Option<&StorageCommitment>,
9157    p2p_node: &Arc<P2PNode>,
9158    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9159    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9160    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9161) -> Option<AuditTarget> {
9162    let Some(c) = commitment else {
9163        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9164    };
9165    // RT-membership gate: only accept commitments from peers in our
9166    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9167    // populate the cache, which closes the hole where a flood of
9168    // off-RT identities could fill the cap and evict honest
9169    // peers. The neighbor-sync request handler applies the same gate
9170    // before admitting inbound replication hints (see neighbor_sync.rs
9171    // `sender_in_rt`); we mirror that policy here for the commitment
9172    // piggyback.
9173    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9174        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9175        return None;
9176    }
9177    // Peer-id binding: the commitment's claimed sender must match the
9178    // authenticated transport peer (`source`). Defeats relay/replay
9179    // and also pins which embedded public key we are about to verify
9180    // against — the verify itself trusts the embedded key, so the
9181    // peer-id binding is the link to a real identity.
9182    if &c.sender_peer_id != source.as_bytes() {
9183        warn!(
9184            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9185             (dropped, possible relay attempt)"
9186        );
9187        return None;
9188    }
9189    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9190    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9191    // with a throwaway key they own and lie about which identity it
9192    // belongs to (the embedded-key signature would verify trivially).
9193    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9194    if derived_peer_id != c.sender_peer_id {
9195        warn!(
9196            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9197             {source} (dropped, throwaway-key attack)"
9198        );
9199        return None;
9200    }
9201    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9202    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9203    // sybil/RT-membership-bypassing peer that flooded valid-looking
9204    // gossip would otherwise burn CPU on every message. The rate
9205    // limit is checked AFTER cheap structural gates (RT, peer-id
9206    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9207    //
9208    // Tracked in `sig_verify_attempts` (separate from
9209    // last_commitment_by_peer) so EVERY attempt — successful or not —
9210    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9211    // would skip the cap for peers we've never successfully verified,
9212    // letting a flood of invalid-but-structurally-plausible gossips
9213    // burn CPU.
9214    let now = Instant::now();
9215    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9216        debug!(
9217            "ingest_peer_commitment: rate-limited sig verify from {source} \
9218             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9219        );
9220        return None;
9221    }
9222    // Signature verify, using the public key embedded in the commitment
9223    // itself. The pubkey is bound by the signature payload (see
9224    // commitment_signed_payload) so an adversary cannot keep the body
9225    // and swap the key to one they hold the secret for.
9226    if !crate::replication::commitment::verify_commitment_signature(c) {
9227        warn!(
9228            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9229             (dropped, forged commitment)"
9230        );
9231        return None;
9232    }
9233    // The new commitment's hash, used to store and to pin for the audit target.
9234    let new_hash = commitment_hash(c);
9235    let mut map = last_commitment_by_peer.write().await;
9236    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9237    // evict an arbitrary existing entry to make room. Updates for peers
9238    // already in the map are always accepted (they replace, not grow).
9239    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9240        // Drop one arbitrary entry. HashMap iter order is random which
9241        // is fine — over time PeerRemoved cleanup keeps the working set
9242        // anchored on the real RT membership; this cap only fires under
9243        // active flooding attempts.
9244        if let Some(victim) = map.keys().next().copied() {
9245            map.remove(&victim);
9246            warn!(
9247                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9248                 evicted {victim} to admit {source}"
9249            );
9250        }
9251    }
9252    // Preserve sticky commitment_capable across updates — once true,
9253    // always true. New entries start with capable = true (we just
9254    // verified a valid commitment from this peer).
9255    map.entry(*source)
9256        .and_modify(|r| {
9257            // set_commitment refreshes the cached hash (§13) alongside the
9258            // commitment + received_at so they never drift.
9259            r.set_commitment(c.clone(), now);
9260            r.last_sig_verify_at = now;
9261            r.commitment_capable = true; // sticky-redundant but explicit
9262        })
9263        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9264    drop(map);
9265    // Record the sticky "ever v12-capable" bit in a set independent of
9266    // `last_commitment_by_peer` (whose entries can be evicted by
9267    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9268    // shield and the §6 holder-eligibility closure consult to decide
9269    // whether the peer is expected to speak v12.
9270    //
9271    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9272    // identity-rotation attacks: once full, new entries are refused.
9273    // Refusal degrades over-cap peers to the behaviour before this set
9274    // existed (treated as legacy on rejoin), which is not a security
9275    // regression and preserves the historic set stable.
9276    {
9277        let mut set = ever_capable_peers.write().await;
9278        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9279            set.insert(*source);
9280        } else {
9281            warn!(
9282                "ingest_peer_commitment: ever_capable_peers at cap \
9283                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9284            );
9285        }
9286    }
9287    // Return an audit target for EVERY valid stored commitment (changed or
9288    // not), so the caller's cooldown+probability-gated trigger keeps a
9289    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9290    // failure (new_hash == None, unreachable for a real commitment) yields None.
9291    new_hash.map(|pin_hash| AuditTarget {
9292        pin_hash,
9293        key_count: c.key_count,
9294    })
9295}
9296
9297// ---------------------------------------------------------------------------
9298// Storage-bound audit (v12) — responder commitment rotation
9299// ---------------------------------------------------------------------------
9300
9301/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9302/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9303/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9304async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9305    let bytes = match tokio::fs::read(path).await {
9306        Ok(b) => b,
9307        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9308            debug!(
9309                "Commitment retention: no snapshot at {} (fresh start)",
9310                path.display()
9311            );
9312            return;
9313        }
9314        Err(e) => {
9315            warn!(
9316                "Commitment retention: failed to read {}: {e}",
9317                path.display()
9318            );
9319            return;
9320        }
9321    };
9322    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9323        state.restore(&persisted);
9324        info!(
9325            "Commitment retention: reloaded {} slot(s) from {}",
9326            state.retained_slot_count(),
9327            path.display()
9328        );
9329    } else {
9330        warn!(
9331            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9332            path.display()
9333        );
9334    }
9335}
9336
9337/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9338/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9339/// needless disk writes on idle nodes. On success updates `last` to the bytes
9340/// written; on a serialization/write error the existing on-disk snapshot is left
9341/// intact (never truncated).
9342async fn persist_retention_if_changed(
9343    state: &ResponderCommitmentState,
9344    path: &Path,
9345    last: &mut Option<Vec<u8>>,
9346) {
9347    let Some(bytes) = state.snapshot().to_bytes() else {
9348        warn!("Commitment retention: serialization failed; keeping previous snapshot");
9349        return;
9350    };
9351    if last.as_deref() == Some(bytes.as_slice()) {
9352        return;
9353    }
9354    if write_retention_atomic(path, bytes.clone()).await {
9355        *last = Some(bytes);
9356    }
9357}
9358
9359/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9360/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9361/// success. Only the retention-persist loop writes this path, so a fixed temp
9362/// name is safe.
9363async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9364    let path = path.to_path_buf();
9365    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9366        let tmp = path.with_extension("tmp");
9367        std::fs::write(&tmp, &bytes)?;
9368        std::fs::File::open(&tmp)?.sync_all()?;
9369        std::fs::rename(&tmp, &path)?;
9370        // Fsync the directory so the rename (the durable-commit point) is not
9371        // lost on a crash right after it. An empty parent (relative filename)
9372        // means the current directory.
9373        let dir = path
9374            .parent()
9375            .filter(|p| !p.as_os_str().is_empty())
9376            .unwrap_or_else(|| Path::new("."));
9377        std::fs::File::open(dir)?.sync_all()?;
9378        Ok(())
9379    })
9380    .await;
9381    match res {
9382        Ok(Ok(())) => true,
9383        Ok(Err(e)) => {
9384            warn!("Commitment retention: persist failed: {e}");
9385            false
9386        }
9387        Err(e) => {
9388            warn!("Commitment retention: persist task join failed: {e}");
9389            false
9390        }
9391    }
9392}
9393
9394/// Read the current LMDB key set, build + sign a fresh
9395/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9396/// The prior `current` is demoted to `previous`; the prior `previous` is
9397/// dropped (per `ResponderCommitmentState::rotate`).
9398///
9399/// For content-addressed chunks (Autonomi's chunk store), `address ==
9400/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9401/// re-read each chunk's bytes to compute the leaf hash.
9402///
9403/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9404/// rotate. The auditor side handles "no commitment for this peer" by
9405/// falling back to the legacy plain-digest audit path.
9406async fn rebuild_and_rotate_commitment(
9407    storage: &Arc<LmdbStorage>,
9408    identity: &Arc<NodeIdentity>,
9409    state: &Arc<ResponderCommitmentState>,
9410    p2p: &Arc<P2PNode>,
9411    config: &Arc<ReplicationConfig>,
9412) -> Result<()> {
9413    let stored_keys = storage
9414        .all_keys()
9415        .await
9416        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9417
9418    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9419    // everything currently on disk ("hold"). This is the half of the retention
9420    // contract that lets out-of-range chunks age out: a key that has left our
9421    // close group is excluded from the NEXT commitment, so once its last gossip
9422    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9423    // set, `ResponderCommitmentState::is_held` goes false,
9424    // and the pruner (which until then vetoes its deletion) reclaims it. Without
9425    // this filter the pruner's reprieve would keep re-committing stale keys
9426    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9427    // re-committed and re-gossiped every rotation — a permanent pin).
9428    let storage_empty = stored_keys.is_empty();
9429    let self_id = *p2p.peer_id();
9430    let mut keys = Vec::with_capacity(stored_keys.len());
9431    for k in stored_keys {
9432        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9433            keys.push(k);
9434        }
9435    }
9436
9437    if keys.is_empty() {
9438        if storage_empty {
9439            // Storage is genuinely empty — there is nothing to answer for, so
9440            // drop the previously advertised commitment immediately. Keeping it
9441            // would leave remote auditors pinning a hash we can never satisfy
9442            // again (the bytes are gone).
9443            if state.retained_slot_count() > 0 {
9444                debug!("Commitment rotation: storage empty, clearing retained slots");
9445                state.clear_all();
9446            }
9447            return Ok(());
9448        }
9449        // Bytes are still on disk but no key is currently in range. We must NOT
9450        // clear retention here: a peer may still be pinning a root we gossiped
9451        // moments ago and could demand its bytes in a round-2 challenge, which
9452        // we can still answer (the bytes are present). But we must STOP
9453        // advertising the stale commitment: retire it so `current()` returns
9454        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
9455        // The retired slot then ages out by its gossip-answerability TTL while
9456        // remaining answerable for in-flight pins until then. Once it ages out,
9457        // `is_held` flips false and the pruner reclaims the now-uncommitted,
9458        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
9459        // pointing at the stale root, which the gossip loop would keep
9460        // re-stamping — pinning its keys forever.)
9461        debug!(
9462            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9463             (stays answerable until its gossip TTL lapses, bytes still on disk)"
9464        );
9465        state.retire_current();
9466        return Ok(());
9467    }
9468
9469    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
9470    // to more than the protocol limit; auditor would reject the
9471    // commitment otherwise).
9472    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9473    if keys.len() > cap {
9474        warn!(
9475            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9476             truncating — investigate as this likely means a misconfiguration",
9477            keys.len(),
9478            cap
9479        );
9480    }
9481
9482    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
9483    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
9484    // full chunk re-read per rotation.
9485    //
9486    // Consequence to be precise about: because the leaf is `(key, key)`,
9487    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
9488    // commitment therefore binds "which keys I claim to hold"; it does NOT
9489    // by itself prove byte possession. Byte possession is enforced by the
9490    // round-2 slice audit: a Bao verified slice decoded against the chunk
9491    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
9492    // nonce, so a responder that holds the key list but dropped the bytes
9493    // cannot answer. This is sound ONLY while keys are content addresses;
9494    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
9495    // (`evaluate_subtree_structure`), so a non-content-addressed
9496    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
9497    // earn credit for `key`. If this module is ever reused for
9498    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
9499    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
9500    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9501
9502    // No-op-rotation guard: compute just the Merkle root from `entries`
9503    // and compare against the currently-advertised commitment's root.
9504    // If they match, the key set is unchanged and a new rotation would
9505    // only swap a randomized ML-DSA signature for a fresh one — same
9506    // content, different commitment_hash. That invalidates every
9507    // outstanding `recent_provers` credit on this node across the
9508    // close group with no security benefit, breaking steady-state
9509    // quorum liveness on large nodes that can't re-audit every key
9510    // every rotation interval. Skip the rotation entirely when the
9511    // tree is unchanged.
9512    // Build the tree ONCE here (moving `entries`): it serves both the no-op
9513    // root check below and, if we proceed, the signed commitment via
9514    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
9515    // inside `BuiltCommitment::build`).
9516    let candidate_tree = commitment::MerkleTree::build(entries)
9517        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9518    let candidate_root = candidate_tree.root();
9519    if let Some(current) = state.current() {
9520        if current.commitment().root == candidate_root {
9521            debug!(
9522                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9523                hex::encode(candidate_root)
9524            );
9525            // Even though we skip re-signing (to avoid invalidating holder
9526            // credit), retention must still advance on the wall clock: a
9527            // previously-gossiped commitment that holds a now-out-of-range key
9528            // must be able to age out of the answerability window even when the
9529            // committed key set is frozen here for many rotations. Without this,
9530            // the no-op guard would pin a stale slot — and its key — forever.
9531            state.age_out();
9532            return Ok(());
9533        }
9534    }
9535
9536    let sk_bytes = identity.secret_key_bytes().to_vec();
9537    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9538        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9539    let pk_bytes = identity.public_key().as_bytes().to_vec();
9540    let peer_id_bytes = *p2p.peer_id().as_bytes();
9541
9542    let built = commitment_state::BuiltCommitment::build_from_tree(
9543        candidate_tree,
9544        &peer_id_bytes,
9545        &sk,
9546        &pk_bytes,
9547    )
9548    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9549
9550    let hash = hex::encode(built.hash());
9551    let key_count = built.commitment().key_count;
9552    state.rotate(built);
9553    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9554    Ok(())
9555}
9556
9557#[cfg(test)]
9558#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9559mod tests {
9560    use super::*;
9561    use super::{
9562        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9563        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9564        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9565        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9566        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9567        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9568        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9569        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9570    };
9571    use crate::payment::VerificationContext;
9572    use crate::replication::audit::AuditTickResult;
9573    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9574    use crate::replication::recent_provers::RecentProvers;
9575    use crate::replication::types::{AuditFailureReason, FailureEvidence};
9576    use lru::LruCache;
9577    use saorsa_core::identity::PeerId;
9578    use std::collections::HashMap;
9579    use std::num::NonZeroUsize;
9580    use std::sync::atomic::Ordering;
9581    use std::sync::Arc;
9582    use std::time::Duration;
9583    use std::time::Instant;
9584    use std::time::SystemTime;
9585
9586    #[test]
9587    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9588        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9589            assert_eq!(match_replication_protocol(id), Some((id, false)));
9590            assert_eq!(
9591                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
9592                Some((id, true))
9593            );
9594        }
9595        assert_eq!(
9596            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
9597            None
9598        );
9599        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
9600        assert_eq!(match_replication_protocol(RR_PREFIX), None);
9601    }
9602
9603    #[test]
9604    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
9605        use crate::replication::protocol::{
9606            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
9607            SubtreeSliceChallenge,
9608        };
9609
9610        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
9611            challenge_id: 1,
9612            nonce: [0u8; 32],
9613            challenged_peer_id: [0u8; 32],
9614            expected_commitment_hash: [0u8; 32],
9615            openings: vec![],
9616        });
9617        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
9618            challenge_id: 1,
9619            nonce: [0u8; 32],
9620            challenged_peer_id: [0u8; 32],
9621            keys: vec![[0u8; 32]],
9622        });
9623        let digest_response =
9624            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
9625        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
9626            key: [0u8; 32],
9627            data: vec![],
9628            proof_of_payment: vec![],
9629        });
9630
9631        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
9632        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
9633
9634        for body in [&digest_challenge, &digest_response, &core] {
9635            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
9636            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
9637        }
9638
9639        for body in [&subtree, &digest_challenge, &digest_response, &core] {
9640            assert!(body_matches_protocol(body, response_protocol_for(body)));
9641        }
9642    }
9643
9644    fn test_peer(b: u8) -> PeerId {
9645        let mut bytes = [0u8; 32];
9646        bytes[0] = b;
9647        PeerId::from_bytes(bytes)
9648    }
9649
9650    /// A structurally valid offer for `data`: real content address, a proof of
9651    /// the minimum accepted size, distinguished by `proof_marker` so a test can
9652    /// tell whose proof came back out of the queue.
9653    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
9654        protocol::FreshReplicationOffer {
9655            key: crate::client::compute_address(&data),
9656            data,
9657            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
9658        }
9659    }
9660
9661    fn admit_test_offer(
9662        in_flight: &FreshOfferInFlight,
9663        offer: protocol::FreshReplicationOffer,
9664        source: PeerId,
9665    ) -> FreshOfferAdmission {
9666        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
9667    }
9668
9669    #[test]
9670    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
9671        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9672        let data = vec![0x11u8; 64];
9673
9674        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
9675        let FreshOfferAdmission::Opened(entry) = opened else {
9676            panic!("first offer for a key should open the entry")
9677        };
9678
9679        // A second sender contributes its proof instead of being turned away:
9680        // its bytes are provably the same, so only the proof is worth keeping.
9681        assert!(
9682            matches!(
9683                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
9684                FreshOfferAdmission::Joined
9685            ),
9686            "a duplicate from a new source should queue its proof"
9687        );
9688        // The same peer twice is not extra evidence, just extra work.
9689        assert!(
9690            matches!(
9691                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
9692                FreshOfferAdmission::DuplicateSource
9693            ),
9694            "one source should hold at most one queued proof per key"
9695        );
9696
9697        // An entry that outlived its handler would bar the key forever.
9698        drop(entry);
9699        assert!(
9700            matches!(
9701                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
9702                FreshOfferAdmission::Opened(_)
9703            ),
9704            "a released key should be openable again"
9705        );
9706    }
9707
9708    #[test]
9709    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
9710        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9711
9712        // A node only receives offers for keys close to its own ID, so accepted
9713        // keys share a long prefix. Any prefix-derived shard index would have
9714        // funnelled these two onto one lock and serialized them.
9715        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
9716        assert!(
9717            matches!(
9718                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
9719                FreshOfferAdmission::Opened(_)
9720            ),
9721            "distinct keys should never block each other"
9722        );
9723    }
9724
9725    /// The regression that motivated queueing proofs at all.
9726    ///
9727    /// A sender whose proof does not verify must cost the network its own
9728    /// attempt and nothing more. Refusing every later offer outright made the
9729    /// first arrival the only arrival, so one bad proof lost the record — and
9730    /// the delayed possession check then charged that absence to this node.
9731    #[test]
9732    fn a_failing_proof_hands_the_key_to_the_next_sender() {
9733        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9734        let data = vec![0x5Au8; 128];
9735        let forger = test_peer(0xF0);
9736        let genuine = test_peer(0x0F);
9737
9738        let FreshOfferAdmission::Opened(mut entry) =
9739            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
9740        else {
9741            panic!("the first offer should open the entry");
9742        };
9743        assert!(
9744            matches!(
9745                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
9746                FreshOfferAdmission::Joined
9747            ),
9748            "the genuine sender must not be turned away by the forger"
9749        );
9750
9751        let first = entry
9752            .next_attempt()
9753            .expect("the opener's proof comes first");
9754        assert_eq!(first.source, forger);
9755
9756        // Treat the forger's proof as failed: the next one is still reachable,
9757        // and it is tried against the bytes already held rather than a refetch.
9758        let second = entry
9759            .next_attempt()
9760            .expect("a failed proof must not consume the key");
9761        assert_eq!(second.source, genuine);
9762        assert_eq!(
9763            second.proof_of_payment,
9764            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
9765        );
9766        assert_eq!(
9767            entry.data(),
9768            data.as_slice(),
9769            "every proof is tried against the one copy of the bytes"
9770        );
9771
9772        // Draining the queue releases the key rather than stranding it.
9773        assert!(entry.next_attempt().is_none());
9774        assert!(
9775            matches!(
9776                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
9777                FreshOfferAdmission::Opened(_)
9778            ),
9779            "an exhausted entry should release its key"
9780        );
9781    }
9782
9783    /// The cap has to be a lifetime budget, not a queue depth.
9784    ///
9785    /// The handler pops a proof before verifying it, so gating admission on the
9786    /// *instantaneous* queue length lets a fresh source refill the slot that pop
9787    /// just freed. Each refill is another on-chain payment verification, run
9788    /// sequentially while the entry holds its admission permit and a worker
9789    /// slot, so a stream of distinct sources could keep one key's handler — and
9790    /// one of only four workers — busy indefinitely.
9791    #[test]
9792    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
9793        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9794        let data = vec![0x3Du8; 32];
9795
9796        let FreshOfferAdmission::Opened(mut entry) =
9797            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
9798        else {
9799            panic!("the first offer should open the entry")
9800        };
9801
9802        // Drive pop-then-admit with a fresh source every time, exactly as a
9803        // sybil stream would. The budget must be spent by admissions, not
9804        // returned by pops.
9805        let mut admitted = 1;
9806        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
9807            let _ = entry.next_attempt();
9808            if matches!(
9809                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
9810                FreshOfferAdmission::Joined
9811            ) {
9812                admitted += 1;
9813            }
9814        }
9815
9816        assert!(
9817            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
9818            "a key accepted {admitted} proofs over its lifetime, but the budget is \
9819             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
9820        );
9821    }
9822
9823    #[test]
9824    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
9825        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
9826        let data = vec![0x2Cu8; 32];
9827
9828        // The opener occupies the first slot, so the cap is reached after
9829        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
9830        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
9831        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
9832            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
9833            assert!(
9834                matches!(
9835                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
9836                    FreshOfferAdmission::Joined
9837                ),
9838                "sender {i} is within the legitimate close-group fan-out"
9839            );
9840        }
9841
9842        let surplus = test_peer(0xEE);
9843        assert!(
9844            matches!(
9845                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
9846                FreshOfferAdmission::Full
9847            ),
9848            "past the cap a proof is surplus: enough are already queued to place the record"
9849        );
9850    }
9851
9852    #[test]
9853    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
9854        assert!(!verification_request_exceeds_limit(
9855            config::MAX_VERIFICATION_KEYS_PER_CYCLE
9856        ));
9857        assert!(verification_request_exceeds_limit(
9858            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
9859        ));
9860    }
9861
9862    // The heavy round-1 limiter enforces the per-peer rate cooldown
9863    // and single-use round-1 → round-2 sessions.
9864    #[tokio::test]
9865    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
9866        let limiter = SubtreeRound1Limiter::new(
9867            Duration::from_secs(3600),
9868            config::MAX_CONCURRENT_SUBTREE_ROUND1,
9869        );
9870        let peer = test_peer(1);
9871
9872        // First round-1 is admitted; drop the guard so concurrency is free again.
9873        let guard = limiter.admit(&peer).await;
9874        assert!(guard.is_some(), "first round-1 admitted");
9875        drop(guard);
9876        // A second round-1 within the cooldown is dropped even though the heavy
9877        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
9878        assert!(
9879            limiter.admit(&peer).await.is_none(),
9880            "second round-1 within cooldown is rate-dropped"
9881        );
9882        // A different peer has its own cooldown.
9883        assert!(limiter.admit(&test_peer(2)).await.is_some());
9884
9885        // Session: opened by round 1, consumed exactly once by the matching round 2.
9886        let hash = [7u8; 32];
9887        let nonce = [9u8; 32];
9888        limiter.open_session(peer, 42, hash, nonce).await;
9889        // Wrong nonce / commitment does not match.
9890        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
9891        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
9892        // A round 2 with no prior round 1 (wrong challenge_id) misses.
9893        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
9894        // The matching round 2 consumes it — and only once (single-use).
9895        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
9896        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
9897    }
9898
9899    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
9900    // so a party holding several identities refills its allowance by rotating
9901    // between them and can keep the heavy pool busy indefinitely. The work
9902    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
9903    // so a fresh identity is refused exactly like a repeat caller once it is
9904    // spent. That is the difference between bounding concurrency and bounding
9905    // sustained work.
9906    #[tokio::test]
9907    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
9908        // Cooldown disabled so only the work budget can refuse anything.
9909        let limiter =
9910            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
9911        assert!(
9912            limiter.admit(&test_peer(1)).await.is_some(),
9913            "a node starts with budget in hand so it can serve audits at once"
9914        );
9915
9916        // Serve enough proof work to run the balance into debt. Charging exactly
9917        // the burst would leave it at zero, which the next nanosecond of refill
9918        // lifts back above the line — the debt is the point.
9919        limiter
9920            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
9921            .await;
9922
9923        for id in 2..8u8 {
9924            assert!(
9925                limiter.admit(&test_peer(id)).await.is_none(),
9926                "a never-seen peer must still be refused while the budget is spent"
9927            );
9928        }
9929    }
9930
9931    // The budget is a rate, not a quota: it comes back on its own, so an honest
9932    // auditor blocked by a flood is only delayed. Carrying the debt is what
9933    // prices an expensive proof above a cheap one — without it, a proof reading
9934    // a maximal subtree would cost no more of the next caller's wait than a
9935    // one-leaf proof.
9936    #[test]
9937    fn round1_work_budget_carries_debt_and_refills_over_time() {
9938        let now = Instant::now();
9939        let at = |secs: u64| {
9940            now.checked_add(Duration::from_secs(secs))
9941                .unwrap_or_else(Instant::now)
9942        };
9943        let mut budget = Round1WorkBudget {
9944            balance: 0,
9945            last_refill: now,
9946        };
9947        assert!(!budget.has_budget(now), "empty means empty");
9948
9949        // A proof costing four seconds' worth of refill leaves four seconds of
9950        // debt, so the wait scales with what was actually served.
9951        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
9952        assert!(
9953            !budget.has_budget(at(3)),
9954            "still in debt three seconds after an over-large proof"
9955        );
9956        assert!(
9957            budget.has_budget(at(5)),
9958            "the debt is worked off at the refill rate"
9959        );
9960
9961        // Idle time does not bank unbounded credit for a later flood.
9962        budget.refill(at(24 * 60 * 60));
9963        assert_eq!(
9964            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
9965            "refill is capped at the burst size"
9966        );
9967    }
9968
9969    // The heavy round-1 pool size is the tightest bound the responder applies and
9970    // the one least backed by fleet measurement, so it is read from config rather
9971    // than baked into the binary: a fleet that lands on the wrong number retunes
9972    // instead of waiting for a release. These pin that the configured value is
9973    // what actually gates admission, and that a 0 degrades to slow, not to off —
9974    // a wedged-shut responder would read on every auditor as a graced timeout,
9975    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
9976    #[tokio::test]
9977    async fn round1_pool_size_comes_from_config() {
9978        // Cooldown disabled so only concurrency can refuse anything.
9979        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
9980        let held = limiter.admit(&test_peer(1)).await;
9981        assert!(held.is_some(), "the single configured slot is admitted");
9982        assert!(
9983            limiter.admit(&test_peer(2)).await.is_none(),
9984            "a second concurrent round 1 is refused at a configured pool of 1, \
9985             proving admission follows config rather than the compiled-in default"
9986        );
9987        drop(held);
9988        assert!(
9989            limiter.admit(&test_peer(2)).await.is_some(),
9990            "the slot is reusable once the first proof completes"
9991        );
9992    }
9993
9994    #[tokio::test]
9995    async fn round1_pool_size_of_zero_is_clamped_to_one() {
9996        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
9997        assert!(
9998            limiter.admit(&test_peer(1)).await.is_some(),
9999            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10000        );
10001    }
10002
10003    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10004        let mut k = [0u8; 32];
10005        k[0] = b;
10006        k
10007    }
10008
10009    #[test]
10010    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10011        let source = test_peer(0x91);
10012        let corroborator = test_peer(0x92);
10013        let mut evidence = types::KeyVerificationEvidence {
10014            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10015            paid_list: HashMap::new(),
10016        };
10017        let failed = KeyVerificationOutcome::QuorumFailed;
10018
10019        assert_eq!(
10020            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10021            Some(source)
10022        );
10023        assert_eq!(
10024            punishable_singleton_replica_hint_source(
10025                &HashSet::from([source, corroborator]),
10026                &failed,
10027                &evidence,
10028            ),
10029            None,
10030            "corroborated hints must not use the sole-source penalty lane"
10031        );
10032        assert_eq!(
10033            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10034            None,
10035            "paid-list advertisements do not claim possession, so they leave the \
10036             replica-hint source set empty and cannot be penalized"
10037        );
10038
10039        evidence
10040            .presence
10041            .insert(source, PresenceEvidence::Unresolved);
10042        assert_eq!(
10043            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10044            Some(source),
10045            "definitive close-group rejection is punishable without direct contradiction"
10046        );
10047        assert_eq!(
10048            punishable_singleton_replica_hint_source(
10049                &HashSet::from([source]),
10050                &KeyVerificationOutcome::QuorumInconclusive,
10051                &evidence,
10052            ),
10053            None,
10054            "timeouts and inconclusive evidence are neutral"
10055        );
10056
10057        evidence.presence.insert(source, PresenceEvidence::Absent);
10058        assert_eq!(
10059            punishable_singleton_replica_hint_source(
10060                &HashSet::from([source]),
10061                &KeyVerificationOutcome::QuorumVerified {
10062                    sources: vec![corroborator],
10063                },
10064                &evidence,
10065            ),
10066            Some(source),
10067            "an explicit denial is punishable regardless of the overall outcome"
10068        );
10069    }
10070
10071    /// Build a round-2 slice challenge matching an open session. `openings` is
10072    /// empty: these tests exercise admission and session handling only, which
10073    /// run before any block is opened.
10074    fn slice_challenge(
10075        challenge_id: u64,
10076        commitment_hash: [u8; 32],
10077        nonce: [u8; 32],
10078    ) -> protocol::SubtreeSliceChallenge {
10079        protocol::SubtreeSliceChallenge {
10080            challenge_id,
10081            nonce,
10082            challenged_peer_id: [0u8; 32],
10083            expected_commitment_hash: commitment_hash,
10084            openings: Vec::new(),
10085        }
10086    }
10087
10088    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10089    // responder caps MUST NOT burn the single-use round-1 session.
10090    //
10091    // The handler used to consume the session first and admit second, so a
10092    // transient local capacity drop permanently destroyed that audit exchange —
10093    // every retry hit the `no live round-1 session` path and got `Transient`,
10094    // even after load cleared. Turning momentary local load into a deterministic
10095    // round-2 miss costs the responder its whole-slice credit for that round.
10096    #[tokio::test]
10097    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10098        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10099        let inflight = Arc::new(RwLock::new(HashMap::new()));
10100        let round1 =
10101            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10102        let peer = test_peer(0xB1);
10103        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10104        let challenge = slice_challenge(id, hash, nonce);
10105
10106        round1.open_session(peer, id, hash, nonce).await;
10107
10108        // Saturate this peer's share so the next admission must be refused.
10109        let mut hold = Vec::new();
10110        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10111            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10112                .await
10113            {
10114                Ok(guard) => hold.push(guard),
10115                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10116            }
10117        }
10118
10119        let refused =
10120            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10121        assert!(
10122            matches!(refused, SliceAdmission::Capacity(_)),
10123            "a saturated peer share must refuse on capacity, not on session"
10124        );
10125
10126        // Load clears. The session must have survived the refusal.
10127        drop(hold);
10128        let retried =
10129            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10130        assert!(
10131            matches!(retried, SliceAdmission::Admitted(_)),
10132            "the round-1 session must survive a capacity refusal so the retry succeeds"
10133        );
10134
10135        // Still single-use: the successful admission consumed it exactly once.
10136        drop(retried);
10137        let replayed =
10138            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10139        assert!(
10140            matches!(replayed, SliceAdmission::NoSession),
10141            "a consumed session must not be replayable"
10142        );
10143    }
10144
10145    // The permit taken for the session probe is released when the probe misses,
10146    // so an unsessioned flood cannot pin the responder pool shut.
10147    #[tokio::test]
10148    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10149        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10150        let inflight = Arc::new(RwLock::new(HashMap::new()));
10151        let round1 =
10152            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10153        let peer = test_peer(0xB2);
10154        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10155
10156        // Far more unsessioned challenges than the per-peer cap would allow if
10157        // the slot leaked on the miss path.
10158        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10159            let outcome =
10160                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10161            assert!(
10162                matches!(outcome, SliceAdmission::NoSession),
10163                "no session was ever opened, so every attempt must miss"
10164            );
10165        }
10166
10167        assert_eq!(
10168            semaphore.available_permits(),
10169            MAX_CONCURRENT_AUDIT_RESPONSES,
10170            "every global permit must be returned"
10171        );
10172        assert!(
10173            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10174            "no per-peer slot may be left occupied"
10175        );
10176    }
10177
10178    #[test]
10179    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10180        assert!(!audit_failure_revokes_holder_credit(
10181            &AuditFailureReason::Timeout
10182        ));
10183        assert!(audit_failure_revokes_holder_credit(
10184            &AuditFailureReason::DigestMismatch
10185        ));
10186    }
10187
10188    #[tokio::test]
10189    async fn audit_responder_admission_reports_per_peer_cap_full() {
10190        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10191        let inflight = Arc::new(RwLock::new(HashMap::new()));
10192        let peer = test_peer(0xA1);
10193
10194        let mut guards = Vec::new();
10195        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10196            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10197                .await
10198            {
10199                Ok(guard) => guards.push(guard),
10200                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10201            }
10202        }
10203
10204        let Err(err) =
10205            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10206        else {
10207            panic!("admission should fail once per-peer cap is full");
10208        };
10209        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10210        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10211        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10212        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10213
10214        drop(guards);
10215    }
10216
10217    #[tokio::test]
10218    async fn audit_responder_admission_reports_global_pool_full() {
10219        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10220        let inflight = Arc::new(RwLock::new(HashMap::new()));
10221        let peer = test_peer(0xA2);
10222
10223        let mut held_global_permits = Vec::new();
10224        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10225            held_global_permits.push(
10226                Arc::clone(&semaphore)
10227                    .try_acquire_owned()
10228                    .expect("test should be able to exhaust the global pool"),
10229            );
10230        }
10231
10232        let Err(err) =
10233            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10234        else {
10235            panic!("admission should fail once global pool is full");
10236        };
10237        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10238        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10239        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10240        assert_eq!(err.peer_inflight, 0);
10241        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10242
10243        drop(held_global_permits);
10244    }
10245
10246    #[tokio::test]
10247    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10248        let semaphore = Arc::new(Semaphore::new(1));
10249        let inflight = Arc::new(RwLock::new(HashMap::new()));
10250        let peer = test_peer(0xA3);
10251
10252        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10253            .await
10254            .expect("first responder should be admitted");
10255        assert_eq!(semaphore.available_permits(), 0);
10256        assert_eq!(inflight.read().await.get(&peer), Some(&1));
10257
10258        drop(guard);
10259        assert_eq!(semaphore.available_permits(), 1);
10260        assert!(!inflight.read().await.contains_key(&peer));
10261    }
10262
10263    #[tokio::test]
10264    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10265        let semaphore = Arc::new(Semaphore::new(1));
10266        let inflight = Arc::new(RwLock::new(HashMap::new()));
10267        let peer = test_peer(0xA4);
10268        let held_map = inflight.write().await;
10269
10270        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10271        assert!(
10272            tokio::time::timeout(Duration::from_millis(10), waiting)
10273                .await
10274                .is_err(),
10275            "admission should still be waiting for the peer map"
10276        );
10277
10278        drop(held_map);
10279        assert_eq!(semaphore.available_permits(), 1);
10280        assert!(!inflight.read().await.contains_key(&peer));
10281    }
10282
10283    #[test]
10284    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10285        let timeout = Duration::from_secs(1);
10286        let old_received_at = Instant::now()
10287            .checked_sub(timeout)
10288            .unwrap_or_else(Instant::now);
10289
10290        assert!(request_is_stale(old_received_at, timeout));
10291        assert!(!request_is_stale(Instant::now(), timeout));
10292    }
10293
10294    #[tokio::test]
10295    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10296        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10297        let inflight = Arc::new(RwLock::new(HashMap::new()));
10298        let first_peer = test_peer(0xB3);
10299        let second_peer = test_peer(0xB4);
10300
10301        let first_guard = admit_bounded_responder(
10302            &semaphore,
10303            &inflight,
10304            &first_peer,
10305            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10306            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10307        )
10308        .await
10309        .expect("first sync from a peer should be admitted");
10310        let duplicate = admit_bounded_responder(
10311            &semaphore,
10312            &inflight,
10313            &first_peer,
10314            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10315            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10316        )
10317        .await;
10318        let other_peer = admit_bounded_responder(
10319            &semaphore,
10320            &inflight,
10321            &second_peer,
10322            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10323            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10324        )
10325        .await;
10326
10327        assert!(matches!(
10328            duplicate,
10329            Err(ResponderAdmissionFailure {
10330                reason: ResponderRejectReason::PerPeerCapFull,
10331                ..
10332            })
10333        ));
10334        assert!(other_peer.is_ok());
10335        drop(first_guard);
10336        drop(other_peer);
10337    }
10338
10339    /// One flooding peer must not be able to hold every fresh-offer slot.
10340    ///
10341    /// This is the eviction primitive the per-peer share closes: with only a
10342    /// global bound, a single source occupies the pool, every honest offer in
10343    /// that window is refused, and because a refusal reads as absence to the
10344    /// sender's delayed possession check those refusals land as
10345    /// audit-severity penalties on *this* node.
10346    #[tokio::test]
10347    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10348        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10349        let inflight = Arc::new(RwLock::new(HashMap::new()));
10350        let flooder = test_peer(0xC1);
10351        let honest = test_peer(0xC2);
10352
10353        let mut held = Vec::new();
10354        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10355            held.push(
10356                admit_bounded_responder(
10357                    &semaphore,
10358                    &inflight,
10359                    &flooder,
10360                    FRESH_OFFER_MAX_OUTSTANDING,
10361                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10362                )
10363                .await
10364                .expect("offers within the per-peer share are admitted"),
10365            );
10366        }
10367
10368        let flooder_excess = admit_bounded_responder(
10369            &semaphore,
10370            &inflight,
10371            &flooder,
10372            FRESH_OFFER_MAX_OUTSTANDING,
10373            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10374        )
10375        .await;
10376        assert!(
10377            matches!(
10378                flooder_excess,
10379                Err(ResponderAdmissionFailure {
10380                    reason: ResponderRejectReason::PerPeerCapFull,
10381                    ..
10382                })
10383            ),
10384            "one source must not exceed its fresh-offer share"
10385        );
10386
10387        let honest_offer = admit_bounded_responder(
10388            &semaphore,
10389            &inflight,
10390            &honest,
10391            FRESH_OFFER_MAX_OUTSTANDING,
10392            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10393        )
10394        .await;
10395        assert!(
10396            honest_offer.is_ok(),
10397            "an honest sender must still be admitted while another peer floods"
10398        );
10399
10400        assert!(
10401            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10402                < FRESH_OFFER_MAX_OUTSTANDING,
10403            "the per-peer share must leave room for other sources"
10404        );
10405
10406        drop(held);
10407        drop(honest_offer);
10408    }
10409
10410    /// Paid notifies get the same per-source treatment as every other class.
10411    #[tokio::test]
10412    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10413        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10414        let inflight = Arc::new(RwLock::new(HashMap::new()));
10415        let flooder = test_peer(0xC3);
10416        let honest = test_peer(0xC4);
10417
10418        let mut held = Vec::new();
10419        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10420            held.push(
10421                admit_bounded_responder(
10422                    &semaphore,
10423                    &inflight,
10424                    &flooder,
10425                    PAID_NOTIFY_MAX_OUTSTANDING,
10426                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10427                )
10428                .await
10429                .expect("notifies within the per-peer share are admitted"),
10430            );
10431        }
10432
10433        assert!(
10434            matches!(
10435                admit_bounded_responder(
10436                    &semaphore,
10437                    &inflight,
10438                    &flooder,
10439                    PAID_NOTIFY_MAX_OUTSTANDING,
10440                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10441                )
10442                .await,
10443                Err(ResponderAdmissionFailure {
10444                    reason: ResponderRejectReason::PerPeerCapFull,
10445                    ..
10446                })
10447            ),
10448            "one source must not exceed its paid-notify share"
10449        );
10450        assert!(
10451            admit_bounded_responder(
10452                &semaphore,
10453                &inflight,
10454                &honest,
10455                PAID_NOTIFY_MAX_OUTSTANDING,
10456                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10457            )
10458            .await
10459            .is_ok(),
10460            "an honest sender must still be admitted while another peer floods"
10461        );
10462
10463        drop(held);
10464    }
10465
10466    /// The fresh-offer per-source bound must guarantee headroom for a peer
10467    /// holding nothing, without throttling a single legitimate fan-out.
10468    ///
10469    /// Sized as a quota rather than a reserve, this bound refused offers during
10470    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
10471    /// refusal is charged to THIS node at audit severity because the sender
10472    /// never reads it.
10473    #[test]
10474    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10475        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10476
10477        assert_eq!(
10478            FRESH_OFFER_MAX_OUTSTANDING - share,
10479            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10480            "a source holding none must always find a free slot"
10481        );
10482        assert!(
10483            share < FRESH_OFFER_MAX_OUTSTANDING,
10484            "one peer must not be able to take the whole pool"
10485        );
10486        // The failure this pins: a share sized like the request/response
10487        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
10488        // one-way bulk traffic.
10489        assert!(
10490            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10491            "fresh offers are one-way bulk, not request/response — their share \
10492             must not be sized like the request classes'"
10493        );
10494    }
10495
10496    /// A malformed offer must be refused before it can occupy an admission
10497    /// slot, so junk cannot hold capacity for the length of a verification.
10498    #[test]
10499    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10500        let key = test_key(0xC5);
10501
10502        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10503
10504        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10505            .expect("an offer with no proof must be refused");
10506        assert!(
10507            rejection.penalise,
10508            "an honest sender always attaches a proof"
10509        );
10510
10511        // A proof is retained per queued sender, so its size has to be bounded
10512        // here rather than at the verifier, which only sees it on a worker.
10513        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10514        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10515            .expect("an undersized proof must be refused");
10516        assert!(
10517            rejection.penalise,
10518            "no honest sender constructs an undersized proof"
10519        );
10520        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10521        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10522            .expect("an oversized proof must be refused");
10523        assert!(
10524            rejection.penalise,
10525            "no honest sender constructs an oversized proof"
10526        );
10527
10528        let rejection = fresh_offer_structural_rejection(
10529            &key,
10530            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10531            &valid_proof,
10532        )
10533        .expect("an oversized offer must be refused");
10534        assert!(
10535            rejection.penalise,
10536            "no honest sender constructs an oversized offer"
10537        );
10538
10539        let data = vec![0u8; 1];
10540        assert!(
10541            fresh_offer_structural_rejection(
10542                &crate::client::compute_address(&data),
10543                &data,
10544                &valid_proof
10545            )
10546            .is_none(),
10547            "a well-formed offer must reach admission"
10548        );
10549    }
10550
10551    /// Knowing a key must not be enough to enter its entry.
10552    ///
10553    /// Opening an entry on an unverified key/bytes association would let a peer
10554    /// that has only *learned* the key — every recipient of its `PaidNotify`,
10555    /// not just the close group that gets the chunk — seize it with junk.
10556    /// Joining one would be worse: the handler tries each queued proof against
10557    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
10558    /// on bytes it never offered.
10559    #[test]
10560    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10561        let genuine_data = vec![0x5Au8; 128];
10562        let key = crate::client::compute_address(&genuine_data);
10563        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10564
10565        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10566            .expect("bytes that do not hash to the advertised key must be refused");
10567        assert!(
10568            rejection.penalise,
10569            "no honest sender offers bytes that do not hash to the advertised key"
10570        );
10571
10572        // Dispatch reaches the entry only past that rejection, so the forged
10573        // offer never touched the key and the genuine one still opens it.
10574        assert!(
10575            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10576            "the offer that actually carries the key's bytes must reach the entry"
10577        );
10578
10579        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10580        assert!(
10581            matches!(
10582                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10583                FreshOfferAdmission::Opened(_)
10584            ),
10585            "an offer refused on payload shape must leave the key openable"
10586        );
10587    }
10588
10589    #[tokio::test]
10590    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
10591        let peer = test_peer(0xA5);
10592        let key = test_key(0xA5);
10593        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10594        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10595        let is_bootstrapping = Arc::new(RwLock::new(true));
10596        let bootstrap_complete_notify = Arc::new(Notify::new());
10597
10598        let now = Instant::now();
10599        queues.write().await.add_pending_verify(
10600            key,
10601            VerificationEntry {
10602                state: VerificationState::PendingVerify,
10603                verified_sources: Vec::new(),
10604                tried_sources: HashSet::new(),
10605                created_at: now,
10606                next_verify_at: now,
10607                hint_sources: HashSet::from([peer]),
10608                replica_hint_sources: HashSet::from([peer]),
10609            },
10610        );
10611        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
10612        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10613        {
10614            let q = queues.read().await;
10615            assert!(
10616                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
10617                "capacity rejection should initially block bootstrap drain"
10618            );
10619        }
10620
10621        update_bootstrap_after_peer_removed(
10622            &peer,
10623            &bootstrap_state,
10624            &queues,
10625            &is_bootstrapping,
10626            &bootstrap_complete_notify,
10627        )
10628        .await;
10629
10630        let state = bootstrap_state.read().await;
10631        assert!(state.capacity_rejected_sources.is_empty());
10632        assert!(state.pending_keys.is_empty());
10633        assert!(state.is_drained());
10634        drop(state);
10635        assert!(!*is_bootstrapping.read().await);
10636    }
10637
10638    /// A fairness displacement forfeits the key but must not stamp its former
10639    /// owner: the owner did nothing wrong, and stamping it lets a flooding
10640    /// source block bootstrap drain through an unrelated honest peer.
10641    #[tokio::test]
10642    async fn fairness_displacement_does_not_stamp_its_victim() {
10643        let displaced_owner = test_peer(0xB1);
10644        let incoming_source = test_peer(0xB2);
10645        let displaced_key = test_key(0xB1);
10646        let admitted_key = test_key(0xB2);
10647        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10648        {
10649            let mut state = bootstrap_state.write().await;
10650            state.pending_keys.insert(displaced_key);
10651            state
10652                .capacity_rejected_sources
10653                .insert(incoming_source, Instant::now());
10654        }
10655        let outcomes = [(
10656            incoming_source,
10657            AdmissionOutcome {
10658                discovered: HashSet::from([admitted_key]),
10659                capacity_rejected_count: 0,
10660                displaced: vec![CapacityDisplacement {
10661                    key: displaced_key,
10662                    owner: displaced_owner,
10663                }],
10664            },
10665        )];
10666
10667        publish_bootstrap_admission_outcomes(
10668            &bootstrap_state,
10669            &outcomes,
10670            &HashSet::from([admitted_key]),
10671        )
10672        .await;
10673
10674        let state = bootstrap_state.read().await;
10675        assert!(!state.pending_keys.contains(&displaced_key));
10676        assert!(state.pending_keys.contains(&admitted_key));
10677        assert!(
10678            !state
10679                .capacity_rejected_sources
10680                .contains_key(&displaced_owner),
10681            "the displaced owner must not be charged for our own fairness reclaim"
10682        );
10683        assert!(!state
10684            .capacity_rejected_sources
10685            .contains_key(&incoming_source));
10686    }
10687
10688    /// A source that keeps overflowing us must not keep its own record fresh.
10689    ///
10690    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
10691    /// rejection the debt could never age out, so `check_bootstrap_drained`
10692    /// stayed false forever and auditing never started (Invariant 19).
10693    #[tokio::test]
10694    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
10695        const REJECTION_ROUNDS: usize = 5;
10696
10697        let source = test_peer(0xB3);
10698        let key = test_key(0xB3);
10699        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10700
10701        let first_seen = {
10702            let outcomes = [(
10703                source,
10704                AdmissionOutcome {
10705                    discovered: HashSet::new(),
10706                    capacity_rejected_count: 1,
10707                    displaced: Vec::new(),
10708                },
10709            )];
10710            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
10711                .await;
10712            bootstrap_state
10713                .read()
10714                .await
10715                .capacity_rejected_sources
10716                .get(&source)
10717                .copied()
10718                .expect("first rejection recorded")
10719        };
10720
10721        for _ in 0..REJECTION_ROUNDS {
10722            let outcomes = [(
10723                source,
10724                AdmissionOutcome {
10725                    discovered: HashSet::from([key]),
10726                    capacity_rejected_count: 1,
10727                    displaced: Vec::new(),
10728                },
10729            )];
10730            publish_bootstrap_admission_outcomes(
10731                &bootstrap_state,
10732                &outcomes,
10733                &HashSet::from([key]),
10734            )
10735            .await;
10736        }
10737
10738        let recorded = bootstrap_state
10739            .read()
10740            .await
10741            .capacity_rejected_sources
10742            .get(&source)
10743            .copied()
10744            .expect("debt still outstanding");
10745        assert_eq!(
10746            recorded, first_seen,
10747            "repeat rejections must not restart the expiry clock"
10748        );
10749    }
10750
10751    /// The verification-worker tick's self-heal path: a capacity rejection
10752    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
10753    /// blocks drain until the TTL expires it, at which point the same tick
10754    /// completes bootstrap without any external event.
10755    #[tokio::test]
10756    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
10757        let peer = test_peer(0xA6);
10758        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
10759        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
10760        let is_bootstrapping = Arc::new(RwLock::new(true));
10761        let bootstrap_complete_notify = Arc::new(Notify::new());
10762
10763        // PeerRemoved was fully processed before the rejection landed, so no
10764        // future event will ever clear this entry.
10765        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
10766
10767        // Within the TTL the tick keeps waiting for re-delivery.
10768        expire_and_recheck_bootstrap_drain(
10769            &bootstrap_state,
10770            &queues,
10771            &is_bootstrapping,
10772            &bootstrap_complete_notify,
10773            ReplicationConfig::default().capacity_rejected_max_age(),
10774        )
10775        .await;
10776        assert!(!bootstrap_state.read().await.is_drained());
10777        assert!(*is_bootstrapping.read().await);
10778
10779        // Past the TTL the tick expires the orphan and completes bootstrap.
10780        expire_and_recheck_bootstrap_drain(
10781            &bootstrap_state,
10782            &queues,
10783            &is_bootstrapping,
10784            &bootstrap_complete_notify,
10785            Duration::ZERO,
10786        )
10787        .await;
10788        assert!(bootstrap_state.read().await.is_drained());
10789        assert!(!*is_bootstrapping.read().await);
10790    }
10791
10792    #[test]
10793    fn first_audit_terminal_outcomes_are_stable() {
10794        let peer = test_peer(1);
10795        let passed = AuditTickResult::Passed {
10796            challenged_peer: peer,
10797            keys_checked: 1,
10798        };
10799        let timed_out = AuditTickResult::Failed {
10800            evidence: FailureEvidence::AuditFailure {
10801                challenge_id: 1,
10802                challenged_peer: peer,
10803                confirmed_failed_keys: vec![test_key(1)],
10804                summary: crate::replication::types::AuditFailureSummary::default(),
10805                reason: AuditFailureReason::Timeout,
10806            },
10807            no_response_class: Some("timeout"),
10808        };
10809
10810        assert_eq!(
10811            first_audit_terminal_outcome(&passed),
10812            FirstAuditTerminalOutcome::Passed
10813        );
10814        assert_eq!(
10815            first_audit_terminal_outcome(&timed_out),
10816            FirstAuditTerminalOutcome::Timeout
10817        );
10818        assert_eq!(
10819            first_audit_terminal_outcome(&AuditTickResult::Idle),
10820            FirstAuditTerminalOutcome::Idle
10821        );
10822        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
10823        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
10824        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
10825        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
10826        assert_eq!(
10827            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
10828            "insufficient_keys"
10829        );
10830        assert_eq!(
10831            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
10832            "bootstrap_claim"
10833        );
10834    }
10835
10836    #[test]
10837    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
10838        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
10839        let mut rng = StdRng::seed_from_u64(7);
10840        let peer = test_peer(1);
10841        let base = MonetizedPinEvent {
10842            peer,
10843            pin: [1; 32],
10844            key_count: 100,
10845            quote_ts: SystemTime::now(),
10846        };
10847
10848        // First insert into an empty slot: Queued.
10849        assert_eq!(
10850            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
10851            FirstAuditQueueOutcome::Queued
10852        );
10853
10854        // A strictly LOWER-count same-peer nomination must NOT displace it.
10855        let lower = MonetizedPinEvent {
10856            pin: [2; 32],
10857            key_count: 50,
10858            ..base
10859        };
10860        assert_eq!(
10861            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
10862            FirstAuditQueueOutcome::SuppressedLower
10863        );
10864        assert_eq!(
10865            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10866            Some(([1; 32], 100)),
10867            "the higher-count pin is retained"
10868        );
10869
10870        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
10871        let higher = MonetizedPinEvent {
10872            pin: [3; 32],
10873            key_count: 400,
10874            ..base
10875        };
10876        assert_eq!(
10877            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
10878            FirstAuditQueueOutcome::Coalesced
10879        );
10880        assert_eq!(
10881            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
10882            Some(([3; 32], 400))
10883        );
10884
10885        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
10886        let equal_newer = MonetizedPinEvent {
10887            pin: [4; 32],
10888            key_count: 400,
10889            ..base
10890        };
10891        assert_eq!(
10892            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
10893            FirstAuditQueueOutcome::Coalesced
10894        );
10895        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10896        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
10897        let equal_older = MonetizedPinEvent {
10898            pin: [5; 32],
10899            key_count: 400,
10900            ..base
10901        };
10902        assert_eq!(
10903            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
10904            FirstAuditQueueOutcome::RetainedOnTie
10905        );
10906        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
10907
10908        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
10909        let other_peer = MonetizedPinEvent {
10910            peer: test_peer(2),
10911            pin: [6; 32],
10912            key_count: 100,
10913            ..base
10914        };
10915        assert_eq!(
10916            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
10917            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
10918        );
10919        assert_eq!(pending.len(), 1);
10920        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
10921    }
10922
10923    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
10924
10925    #[test]
10926    fn first_audit_limiter_enforces_burst_then_refills() {
10927        let base = Instant::now();
10928        let mut limiter = FirstAuditLimiter::new(base);
10929        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
10930
10931        // The full burst is admitted back-to-back (distinct peers).
10932        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
10933            let peer = test_peer(u8::try_from(i).expect("small burst"));
10934            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
10935            limiter.commit_launch(peer, 10, base);
10936        }
10937        // Bucket empty: the next distinct peer is deferred, never dropped.
10938        let extra = test_peer(0xEE);
10939        assert_eq!(
10940            limiter.assess(&extra, 10, base, 0),
10941            LimiterVerdict::RateDeferred
10942        );
10943
10944        // One full interval later exactly one token is available again.
10945        let later = base + interval;
10946        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
10947        limiter.commit_launch(extra, 10, later);
10948        let extra2 = test_peer(0xEF);
10949        assert_eq!(
10950            limiter.assess(&extra2, 10, later, 0),
10951            LimiterVerdict::RateDeferred
10952        );
10953    }
10954
10955    #[test]
10956    fn first_audit_limiter_refill_keeps_fractional_remainder() {
10957        let base = Instant::now();
10958        let mut limiter = FirstAuditLimiter::new(base);
10959        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
10960        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
10961            let peer = test_peer(u8::try_from(i).expect("small burst"));
10962            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
10963            limiter.commit_launch(peer, 1, base);
10964        }
10965        // 1.5 intervals later one token is earned and the half interval is
10966        // NOT lost to drift...
10967        let at_1_5 = base + interval + interval / 2;
10968        let p = test_peer(0xAA);
10969        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
10970        limiter.commit_launch(p, 1, at_1_5);
10971        // ...so the next token arrives at 2.0 intervals, not 2.5.
10972        let at_2_0 = base + interval * 2;
10973        let q = test_peer(0xAB);
10974        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
10975    }
10976
10977    #[test]
10978    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
10979        let base = Instant::now();
10980        let mut limiter = FirstAuditLimiter::new(base);
10981        let peer = test_peer(1);
10982        assert_eq!(
10983            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
10984            LimiterVerdict::RateDeferred
10985        );
10986        // A freed slot admits without any clock movement.
10987        assert_eq!(
10988            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
10989            LimiterVerdict::Admit
10990        );
10991    }
10992
10993    #[test]
10994    fn first_audit_limiter_assess_consumes_nothing() {
10995        let base = Instant::now();
10996        let mut limiter = FirstAuditLimiter::new(base);
10997        let peer = test_peer(3);
10998        // Repeated assessment must not burn budget or stamp the window: only
10999        // `commit_launch` consumes (the cooldown gate between assess and
11000        // commit can defer, and that deferral must be free).
11001        for _ in 0..10 {
11002            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11003        }
11004        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11005            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11006            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11007            limiter.commit_launch(p, 5, base);
11008        }
11009    }
11010
11011    #[test]
11012    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11013        let base = Instant::now();
11014        let mut limiter = FirstAuditLimiter::new(base);
11015        let peer = test_peer(7);
11016        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11017        limiter.commit_launch(peer, 100, base);
11018
11019        // A rotated pin with a similar count inside the window is dropped...
11020        let soon = base + Duration::from_secs(60);
11021        assert_eq!(
11022            limiter.assess(&peer, 100, soon, 0),
11023            LimiterVerdict::WindowDeduped
11024        );
11025        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11026        assert_eq!(
11027            limiter.assess(&peer, 150, soon, 0),
11028            LimiterVerdict::WindowDeduped
11029        );
11030        // ...but a >1.5x committed-count jump re-nominates immediately (an
11031        // inflated sidecar-only pin is invisible to the gossip lottery, so
11032        // the window must not shield it).
11033        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11034
11035        // Window expiry re-admits an unchanged count.
11036        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11037        assert_eq!(
11038            limiter.assess(&peer, 100, expired, 0),
11039            LimiterVerdict::Admit
11040        );
11041    }
11042
11043    #[test]
11044    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11045        // A window-deduped nomination must be DROPPED, not kept pending as
11046        // rate-deferred, even when the bucket is also empty: re-queuing a
11047        // suppressed rotation would hold a pending slot for two hours.
11048        let base = Instant::now();
11049        let mut limiter = FirstAuditLimiter::new(base);
11050        let peer = test_peer(9);
11051        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11052        limiter.commit_launch(peer, 10, base);
11053        let other = test_peer(10);
11054        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11055        limiter.commit_launch(other, 10, base);
11056        assert_eq!(
11057            limiter.assess(&peer, 10, base, 0),
11058            LimiterVerdict::WindowDeduped
11059        );
11060    }
11061
11062    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11063    /// is answerable now but would age out of the answerability window during
11064    /// the launch jitter, so scheduling state is only ever committed for a pin
11065    /// that can still be challenged when it actually sends.
11066    #[test]
11067    fn first_audit_horizon_prefilter_boundary() {
11068        let now = SystemTime::now();
11069        // C = the too-old cutoff; H = the worst-case send horizon.
11070        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11071        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11072        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11073        let boundary = now
11074            .checked_add(h)
11075            .and_then(|t| t.checked_sub(c))
11076            .expect("boundary time");
11077
11078        // In window at `now` (age = C - H < C)...
11079        assert!(quote_within_audit_window(boundary, now));
11080        // ...but the horizon prefilter rejects it (age == C at now + H).
11081        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11082
11083        // A hair newer stays answerable through the horizon; a hair older does
11084        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11085        // a nanosecond step would round to the same instant there.
11086        let newer = boundary
11087            .checked_add(Duration::from_micros(1))
11088            .expect("newer");
11089        let older = boundary
11090            .checked_sub(Duration::from_micros(1))
11091            .expect("older");
11092        assert!(quote_answerable_through_nominal_jitter(newer, now));
11093        assert!(!quote_answerable_through_nominal_jitter(older, now));
11094
11095        // A quote too far in the FUTURE is rejected at `now`, independent of the
11096        // horizon.
11097        let future = now
11098            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11099            .and_then(|t| t.checked_add(Duration::from_secs(60)))
11100            .expect("future");
11101        assert!(!quote_answerable_through_nominal_jitter(future, now));
11102    }
11103
11104    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11105    /// answerability check fails at promotion is fully state-neutral — it stamps
11106    /// no `first_audited`, no per-peer window, refunds its token, releases its
11107    /// in-flight slot, does not flip the lane, and does not count a launch — and
11108    /// a same-peer, same-count successor enqueued DURING the reservation is
11109    /// retained and becomes the next reservation after the cancel. This is the
11110    /// exact hole the reviewer flagged: suppression must never outlive a launch
11111    /// that did not send.
11112    /// A pending pin that has aged past the answerability horizon must not
11113    /// suppress a live lower-count nomination for the same peer: under token
11114    /// starvation no reserve scan ever collects the dead entry, so without the
11115    /// enqueue-time check the peer would stay unauditable through this path
11116    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11117    #[test]
11118    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11119        let obs = Arc::new(FirstAuditObservability::default());
11120        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11121        let peer = test_peer(1);
11122
11123        let dead_quote = SystemTime::now()
11124            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11125            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11126            .expect("past wall time");
11127        let stale_high = MonetizedPinEvent {
11128            peer,
11129            pin: [1; 32],
11130            key_count: 400,
11131            quote_ts: dead_quote,
11132        };
11133        scheduler.enqueue(stale_high, &obs);
11134        assert_eq!(scheduler.pending_len(), 1);
11135
11136        // A fresh, lower-count nomination (a post-prune commitment).
11137        let fresh_lower = MonetizedPinEvent {
11138            peer,
11139            pin: [2; 32],
11140            key_count: 100,
11141            quote_ts: SystemTime::now(),
11142        };
11143        scheduler.enqueue(fresh_lower, &obs);
11144
11145        assert_eq!(scheduler.pending_len(), 1);
11146        assert_eq!(
11147            scheduler.pending.peek(&peer).map(|e| e.pin),
11148            Some([2; 32]),
11149            "the live nomination replaced the dead incumbent"
11150        );
11151        assert_eq!(
11152            obs.suppressed_lower.load(Ordering::Relaxed),
11153            0,
11154            "no self-erasure signal for displacing a dead pin"
11155        );
11156        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11157        assert_eq!(
11158            obs.outside_answerability_window.load(Ordering::Relaxed),
11159            1,
11160            "the dead incumbent is accounted as an expiry"
11161        );
11162    }
11163
11164    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11165    /// nomination still loses to an answerable higher-count pending pin.
11166    #[test]
11167    fn first_audit_live_incumbent_still_suppresses_lower_count() {
11168        let obs = Arc::new(FirstAuditObservability::default());
11169        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11170        let peer = test_peer(1);
11171
11172        let live_high = MonetizedPinEvent {
11173            peer,
11174            pin: [1; 32],
11175            key_count: 400,
11176            quote_ts: SystemTime::now(),
11177        };
11178        scheduler.enqueue(live_high, &obs);
11179        let cheaper = MonetizedPinEvent {
11180            peer,
11181            pin: [2; 32],
11182            key_count: 100,
11183            quote_ts: SystemTime::now(),
11184        };
11185        scheduler.enqueue(cheaper, &obs);
11186
11187        assert_eq!(scheduler.pending_len(), 1);
11188        assert_eq!(
11189            scheduler.pending.peek(&peer).map(|e| e.pin),
11190            Some([1; 32]),
11191            "the higher-count live pin is retained"
11192        );
11193        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11194        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11195    }
11196
11197    /// A fresh nomination for peer `b` (distinct pin per peer).
11198    fn live_nomination(b: u8) -> MonetizedPinEvent {
11199        MonetizedPinEvent {
11200            peer: test_peer(b),
11201            pin: [b; 32],
11202            key_count: 100,
11203            quote_ts: SystemTime::now(),
11204        }
11205    }
11206
11207    /// The pending admission cap must equal the number of usable launches the
11208    /// token budget can perform inside one answerability window, counted by
11209    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11210    /// tokens at age zero, one refill per launch interval), not by repeating
11211    /// the derivation formula. Any larger and admitted work is guaranteed to
11212    /// expire unlaunched; any smaller and the budget idles while nominations
11213    /// are displaced.
11214    #[test]
11215    fn first_audit_pending_cap_matches_strict_launch_horizon() {
11216        let quote_ts = SystemTime::now();
11217        // Burst launches fire at age zero and must pass the reserve predicate.
11218        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11219        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11220        let mut refill = 1u32;
11221        loop {
11222            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11223            let at = quote_ts + age;
11224            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11225                break;
11226            }
11227            usable += 1;
11228            refill += 1;
11229            assert!(refill < 10_000, "runaway horizon simulation");
11230        }
11231        assert_eq!(
11232            FIRST_AUDIT_PENDING_CAP, usable,
11233            "cap must match the simulated strict launch horizon"
11234        );
11235    }
11236
11237    /// The pending queue is sized to the launch budget while the dedup set
11238    /// keeps the commitment-cache bound: shrinking `first_audited` would
11239    /// forget audited pins and re-admit duplicates.
11240    #[test]
11241    fn first_audit_pending_cap_independent_of_dedup_cap() {
11242        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11243        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11244        assert_eq!(
11245            scheduler.first_audited.cap().get(),
11246            MAX_LAST_COMMITMENT_BY_PEER
11247        );
11248    }
11249
11250    /// Admission beyond the cap displaces exactly one incumbent per overflow
11251    /// and every displacement is accounted as `capacity_evicted` — the steady
11252    /// overload signal — never silent loss, and never an admission refusal.
11253    #[test]
11254    fn first_audit_admission_beyond_cap_displaces_and_counts() {
11255        let obs = Arc::new(FirstAuditObservability::default());
11256        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11257        let overflow: usize = 5;
11258        let total = FIRST_AUDIT_PENDING_CAP + overflow;
11259
11260        for i in 0..total {
11261            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11262            scheduler.enqueue(live_nomination(b), &obs);
11263        }
11264
11265        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11266        assert_eq!(
11267            obs.capacity_evicted.load(Ordering::Relaxed),
11268            u64::try_from(overflow).expect("overflow fits u64"),
11269            "each admission past the cap displaces exactly one entry"
11270        );
11271        assert_eq!(
11272            obs.queued.load(Ordering::Relaxed),
11273            u64::try_from(total).expect("total fits u64"),
11274            "displacement is not an admission refusal"
11275        );
11276        // Every arrival was admitted (the newest always enters the sample).
11277        let last = u8::try_from(total).expect("test peer count fits u8");
11278        assert!(
11279            scheduler.pending.peek(&test_peer(last)).is_some(),
11280            "the newest arrival always enters the sample"
11281        );
11282    }
11283
11284    /// The reviewer-demonstrated suppression route: a target followed by an
11285    /// ordered batch of distinct-peer nominations, all inside one ingress
11286    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11287    /// the token bucket EMPTY so no reservation can intervene. Under the old
11288    /// keep-newest LRU the target was evicted with certainty; under random
11289    /// displacement its per-overflow eviction probability is `1/cap`, so
11290    /// across repeated trials the target must survive some runs and be
11291    /// displaced in others — never deterministically flushed, and every
11292    /// displacement accounted.
11293    #[test]
11294    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11295        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11296        assert!(FIRST_AUDIT_PENDING_CAP < flood);
11297        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11298
11299        let trials = 100u64;
11300        let mut survived = 0u32;
11301        let mut evicted = 0u32;
11302        for trial in 0..trials {
11303            let obs = Arc::new(FirstAuditObservability::default());
11304            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11305            // Deterministic per-trial seed: the run is fully reproducible (no
11306            // flake budget at all) while still exercising 100 distinct
11307            // eviction sequences.
11308            scheduler.rng = StdRng::seed_from_u64(trial);
11309            // Drain the burst tokens so the pre-overflow reservation
11310            // opportunity cannot fire: this isolates pure retention.
11311            scheduler.limiter.reserve_token();
11312            scheduler.limiter.reserve_token();
11313
11314            let target = test_peer(200);
11315            scheduler.enqueue(live_nomination(200), &obs);
11316            for i in 0..flood {
11317                let b = u8::try_from(i + 1).expect("flood peer fits u8");
11318                scheduler.enqueue(live_nomination(b), &obs);
11319            }
11320
11321            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11322            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11323                .expect("overflow count fits u64");
11324            assert_eq!(
11325                obs.capacity_evicted.load(Ordering::Relaxed),
11326                overflows,
11327                "every overflow past the cap is accounted, none silent"
11328            );
11329            if scheduler.pending.peek(&target).is_some() {
11330                survived += 1;
11331            } else {
11332                evicted += 1;
11333            }
11334        }
11335        // With eviction probability 1/cap per overflow, P(target survives one
11336        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11337        // 100 seeded trials — and the seeds make the split exactly
11338        // reproducible rather than a (vanishingly small) flake budget.
11339        assert!(
11340            survived > 0,
11341            "target must survive some ordered floods — deterministic eviction \
11342             would mean keep-newest retention regressed"
11343        );
11344        assert!(
11345            evicted > 0,
11346            "target must also be displaceable — otherwise overflow is refusing \
11347             admissions instead of sampling"
11348        );
11349    }
11350
11351    /// With a token AVAILABLE, an overflowing arrival must first give pending
11352    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
11353    /// one entry out of the queue, so admission proceeds without any eviction.
11354    #[test]
11355    fn first_audit_overflow_reserves_before_destructive_eviction() {
11356        let obs = Arc::new(FirstAuditObservability::default());
11357        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11358        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11359
11360        for i in 0..FIRST_AUDIT_PENDING_CAP {
11361            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11362            scheduler.enqueue(live_nomination(b), &obs);
11363        }
11364        let overflowing = live_nomination(250);
11365        assert!(scheduler.would_displace(&overflowing));
11366
11367        // The drainer's pre-overflow sequence: reserve, then enqueue.
11368        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11369        assert!(
11370            !scheduler.would_displace(&overflowing),
11371            "a successful reservation frees the slot"
11372        );
11373        scheduler.enqueue(overflowing, &obs);
11374
11375        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11376        assert_eq!(
11377            obs.capacity_evicted.load(Ordering::Relaxed),
11378            0,
11379            "no destructive eviction when a launch opportunity existed"
11380        );
11381    }
11382
11383    /// Displacement stamps no suppression state: a displaced peer's next
11384    /// nomination re-enters like any newcomer (it is NOT window-deduped or
11385    /// treated as a duplicate), so under overload every peer keeps an
11386    /// unpredictable chance of prompt first audit.
11387    #[test]
11388    fn first_audit_displaced_peer_may_be_renominated() {
11389        let obs = Arc::new(FirstAuditObservability::default());
11390        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11391        let total = FIRST_AUDIT_PENDING_CAP + 1;
11392
11393        for i in 0..total {
11394            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11395            scheduler.enqueue(live_nomination(b), &obs);
11396        }
11397        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11398        // Find whichever peer the random displacement removed.
11399        let displaced = (1..=total)
11400            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11401            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11402            .expect("exactly one admitted peer was displaced");
11403
11404        scheduler.enqueue(live_nomination(displaced), &obs);
11405
11406        assert!(
11407            scheduler.pending.peek(&test_peer(displaced)).is_some(),
11408            "the displaced peer re-enters the sample"
11409        );
11410        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11411        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11412        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11413        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11414    }
11415
11416    /// The periodic sweep collects expired pending entries even when the token
11417    /// bucket is empty — the reserve path returns at the budget gate and never
11418    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
11419    /// honest under fleet-wide starvation.
11420    #[test]
11421    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11422        let obs = Arc::new(FirstAuditObservability::default());
11423        let mono = Instant::now();
11424        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11425
11426        let dead_quote = SystemTime::now()
11427            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11428            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11429            .expect("past wall time");
11430        scheduler.enqueue(
11431            MonetizedPinEvent {
11432                peer: test_peer(1),
11433                pin: [1; 32],
11434                key_count: 100,
11435                quote_ts: dead_quote,
11436            },
11437            &obs,
11438        );
11439        scheduler.enqueue(
11440            MonetizedPinEvent {
11441                peer: test_peer(2),
11442                pin: [2; 32],
11443                key_count: 100,
11444                quote_ts: SystemTime::now(),
11445            },
11446            &obs,
11447        );
11448        assert_eq!(scheduler.pending_len(), 2);
11449
11450        // Empty the bucket so the reserve path is budget-gated (fleet-wide
11451        // starvation) and cannot collect the dead entry itself.
11452        scheduler.limiter.tokens = 0;
11453        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11454        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11455        assert_eq!(
11456            scheduler.pending_len(),
11457            2,
11458            "budget-gated reserve scans nothing"
11459        );
11460
11461        let wall_now = SystemTime::now();
11462        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11463        assert_eq!(scheduler.pending_len(), 1);
11464        assert!(
11465            scheduler.pending.peek(&test_peer(2)).is_some(),
11466            "the live entry survives the sweep"
11467        );
11468        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11469        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11470        assert!(
11471            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11472            "the age gauge reflects only live work after the sweep"
11473        );
11474    }
11475
11476    #[test]
11477    #[allow(clippy::too_many_lines)]
11478    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11479        let obs = Arc::new(FirstAuditObservability::default());
11480        let mono = Instant::now();
11481        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11482
11483        // A pre-existing window sentinel for an UNRELATED peer must survive the
11484        // cancel byte-for-byte (cancel never touches `recent`).
11485        let sentinel_peer = test_peer(0xAA);
11486        scheduler.limiter.promote(sentinel_peer, 500, mono);
11487        let sentinel_before = scheduler
11488            .limiter
11489            .recent
11490            .peek(&sentinel_peer)
11491            .copied()
11492            .expect("sentinel present");
11493
11494        let peer = test_peer(1);
11495        let a = MonetizedPinEvent {
11496            peer,
11497            pin: [1; 32],
11498            key_count: 100,
11499            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
11500        };
11501        scheduler.enqueue(a, &obs);
11502
11503        let tokens_before = scheduler.tokens();
11504        let lane_before = scheduler.oldest_first_lane;
11505        let launched_before = obs.launched.load(Ordering::Relaxed);
11506        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11507
11508        // Reserve A (jitter 0 so it is immediately due).
11509        let inflight0 = obs.inflight.load(Ordering::Relaxed);
11510        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11511        assert_eq!(scheduler.reserved_peer(), Some(peer));
11512        assert_eq!(
11513            scheduler.tokens(),
11514            tokens_before - 1,
11515            "reserve consumes a token"
11516        );
11517        assert_eq!(
11518            obs.inflight.load(Ordering::Relaxed),
11519            1,
11520            "reserve holds a slot"
11521        );
11522
11523        // A same-peer, same-count successor arrives DURING the reservation. It
11524        // must be retained (bypasses the window for the reserved peer) and must
11525        // NOT create a second reservation.
11526        let b = MonetizedPinEvent {
11527            peer,
11528            pin: [2; 32],
11529            key_count: 100,
11530            quote_ts: SystemTime::now(),
11531        };
11532        scheduler.enqueue(b, &obs);
11533        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11534        assert!(
11535            !scheduler.try_reserve(
11536                mono,
11537                obs.inflight.load(Ordering::Relaxed),
11538                Duration::ZERO,
11539                &cooldown,
11540                &obs
11541            ),
11542            "no second reservation while one is outstanding"
11543        );
11544
11545        // Resolve A with an injected wall time PAST A's answerability cutoff.
11546        let reservation = scheduler
11547            .take_due_reservation(mono)
11548            .expect("A is due at jitter 0");
11549        let wall_fail = a
11550            .quote_ts
11551            .checked_add(GOSSIP_ANSWERABILITY_TTL)
11552            .and_then(|t| t.checked_add(Duration::from_secs(1)))
11553            .expect("past-cutoff wall time");
11554        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11555        assert!(
11556            promoted.is_none(),
11557            "answerability lapsed -> cancelled, not promoted"
11558        );
11559
11560        // State-neutral cancel.
11561        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11562        assert!(
11563            scheduler.limiter.recent.peek(&peer).is_none(),
11564            "cancel stamps no per-peer window"
11565        );
11566        assert_eq!(
11567            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11568            Some(sentinel_before),
11569            "unrelated window sentinel untouched"
11570        );
11571        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11572        assert_eq!(
11573            scheduler.tokens(),
11574            tokens_before,
11575            "token refunded on cancel"
11576        );
11577        assert_eq!(
11578            obs.inflight.load(Ordering::Relaxed),
11579            0,
11580            "in-flight slot released"
11581        );
11582        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11583        assert_eq!(
11584            obs.launched.load(Ordering::Relaxed),
11585            launched_before,
11586            "no launch counted"
11587        );
11588        assert_eq!(
11589            obs.outside_answerability_window.load(Ordering::Relaxed),
11590            1,
11591            "the cancel reason is recorded"
11592        );
11593
11594        // The successor is still pending and is now fully schedulable: a fresh
11595        // reserve makes B the next reservation (proving eligibility, not merely
11596        // that the limiter would admit it).
11597        assert_eq!(
11598            scheduler.pending_len(),
11599            1,
11600            "successor still pending after cancel"
11601        );
11602        assert!(scheduler.reserved.is_none());
11603        assert!(scheduler.try_reserve(
11604            mono,
11605            obs.inflight.load(Ordering::Relaxed),
11606            Duration::ZERO,
11607            &cooldown,
11608            &obs
11609        ));
11610        assert_eq!(
11611            scheduler.reserved_peer(),
11612            Some(peer),
11613            "the retained successor becomes the next reservation"
11614        );
11615    }
11616
11617    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
11618    /// race, the reserved event is requeued ONLY if no same-peer successor is
11619    /// already pending. A successor arrived after the reservation, so it is the
11620    /// newer nomination (e.g. a count jump) and must not be overwritten by the
11621    /// older reserved event.
11622    #[test]
11623    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
11624        let obs = Arc::new(FirstAuditObservability::default());
11625        let mono = Instant::now();
11626        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11627        let peer = test_peer(1);
11628
11629        // Reserve A.
11630        let a = MonetizedPinEvent {
11631            peer,
11632            pin: [1; 32],
11633            key_count: 100,
11634            quote_ts: SystemTime::now(),
11635        };
11636        scheduler.enqueue(a, &obs);
11637        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
11638        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
11639
11640        // A newer same-peer successor B (a count jump) arrives during the
11641        // reservation and is retained.
11642        let b = MonetizedPinEvent {
11643            peer,
11644            pin: [2; 32],
11645            key_count: 400,
11646            quote_ts: SystemTime::now(),
11647        };
11648        scheduler.enqueue(b, &obs);
11649        assert_eq!(scheduler.pending_len(), 1);
11650
11651        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
11652        // is already stamped for the peer, so promotion loses the race.
11653        let reservation = scheduler.take_due_reservation(mono).expect("due");
11654        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11655        cooldown.insert(peer, mono); // freshly on cooldown
11656        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
11657        assert!(promoted.is_none(), "cooldown race -> not promoted");
11658
11659        // B (newer) is preserved; A did NOT overwrite it.
11660        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
11661        assert_eq!(
11662            scheduler.pending.peek(&peer).map(|e| e.pin),
11663            Some([2; 32]),
11664            "the newer successor B is retained, not the older reserved A"
11665        );
11666        assert!(scheduler.first_audited.is_empty());
11667        assert!(scheduler.limiter.recent.peek(&peer).is_none());
11668    }
11669
11670    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
11671    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
11672    /// and saturates to `0` for a future-dated quote (clock skew) without
11673    /// panicking. A climbing value is the pending-work-aging-out signal.
11674    #[test]
11675    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
11676        let now = SystemTime::now();
11677        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11678        assert_eq!(
11679            scheduler.oldest_pending_quote_age_ms(now),
11680            0,
11681            "empty pending -> zero"
11682        );
11683
11684        // Two peers: quotes 10s and 2s old. The gauge must track the older.
11685        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
11686            let _ = coalesce_first_audit_event(
11687                &mut scheduler.pending,
11688                MonetizedPinEvent {
11689                    peer: test_peer(peer_id),
11690                    pin,
11691                    key_count: 100,
11692                    quote_ts: now - Duration::from_secs(secs),
11693                },
11694                true,
11695                &mut scheduler.rng,
11696            );
11697        }
11698        assert_eq!(
11699            scheduler.oldest_pending_quote_age_ms(now),
11700            10_000,
11701            "tracks the oldest (10s), not the newest (2s)"
11702        );
11703
11704        // A future-dated quote (clock skew) saturates to zero, never panics.
11705        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11706        let _ = coalesce_first_audit_event(
11707            &mut skewed.pending,
11708            MonetizedPinEvent {
11709                peer: test_peer(3),
11710                pin: [3; 32],
11711                key_count: 100,
11712                quote_ts: now + Duration::from_secs(5),
11713            },
11714            true,
11715            &mut skewed.rng,
11716        );
11717        assert_eq!(
11718            skewed.oldest_pending_quote_age_ms(now),
11719            0,
11720            "future quote_ts saturates to zero"
11721        );
11722    }
11723
11724    /// A flood of strictly-lower-count same-peer nominations must neither
11725    /// displace the retained higher pin NOR disturb its recency position (each
11726    /// is suppressed via `peek`, no `push`), and each must be counted as
11727    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
11728    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
11729    /// (the documented `lru` contract that also drives the reserve scan's lane
11730    /// ordering), deliberately independent of the overflow policy: eviction is
11731    /// random-victim, so no assertion may require a particular peer to be
11732    /// displaced.
11733    #[test]
11734    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
11735        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
11736            LruCache::new(NonZeroUsize::new(2).unwrap());
11737        let mut rng = StdRng::seed_from_u64(11);
11738        let victim = test_peer(1);
11739        let other = test_peer(2);
11740        // Victim (high count) inserted first (older), then `other` (newer/MRU).
11741        let _ = coalesce_first_audit_event(
11742            &mut pending,
11743            MonetizedPinEvent {
11744                peer: victim,
11745                pin: [1; 32],
11746                key_count: 400,
11747                quote_ts: SystemTime::now(),
11748            },
11749            true,
11750            &mut rng,
11751        );
11752        let _ = coalesce_first_audit_event(
11753            &mut pending,
11754            MonetizedPinEvent {
11755                peer: other,
11756                pin: [9; 32],
11757                key_count: 100,
11758                quote_ts: SystemTime::now(),
11759            },
11760            true,
11761            &mut rng,
11762        );
11763        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11764        assert_eq!(
11765            order_before,
11766            vec![other, victim],
11767            "sanity: `other` is MRU, the victim is LRU"
11768        );
11769
11770        // Flood the victim with cheaper nominations.
11771        let mut suppressed = 0u64;
11772        for i in 0..8u8 {
11773            let out = coalesce_first_audit_event(
11774                &mut pending,
11775                MonetizedPinEvent {
11776                    peer: victim,
11777                    pin: [i; 32],
11778                    key_count: 50,
11779                    quote_ts: SystemTime::now(),
11780                },
11781                true,
11782                &mut rng,
11783            );
11784            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
11785            suppressed += 1;
11786        }
11787        assert_eq!(suppressed, 8);
11788        // Victim pin/count unchanged.
11789        assert_eq!(
11790            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
11791            Some(([1; 32], 400))
11792        );
11793        // Recency untouched: the iteration order (which the reserve lanes
11794        // consume) is byte-for-byte what it was before the flood.
11795        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
11796        assert_eq!(
11797            order_after, order_before,
11798            "the suppressed-lower flood must not have changed any recency position"
11799        );
11800    }
11801
11802    /// The cooldown-race requeue counts a genuine different-peer capacity
11803    /// eviction (the ADR promises capacity loss is observable).
11804    #[test]
11805    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
11806        let obs = Arc::new(FirstAuditObservability::default());
11807        let mono = Instant::now();
11808        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11809        // Pending capacity 1 so a requeue of a different peer must evict.
11810        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11811        let reserved_peer = test_peer(1);
11812        let other_peer = test_peer(2);
11813
11814        // Reserve peer 1.
11815        scheduler.enqueue(
11816            MonetizedPinEvent {
11817                peer: reserved_peer,
11818                pin: [1; 32],
11819                key_count: 100,
11820                quote_ts: SystemTime::now(),
11821            },
11822            &obs,
11823        );
11824        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11825        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11826
11827        // A DIFFERENT peer fills the single pending slot during the reservation.
11828        scheduler.enqueue(
11829            MonetizedPinEvent {
11830                peer: other_peer,
11831                pin: [2; 32],
11832                key_count: 100,
11833                quote_ts: SystemTime::now(),
11834            },
11835            &obs,
11836        );
11837        assert_eq!(scheduler.pending_len(), 1);
11838
11839        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
11840        let reservation = scheduler.take_due_reservation(mono).expect("due");
11841        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11842        cooldown.insert(reserved_peer, mono);
11843        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
11844        assert!(scheduler
11845            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11846            .is_none());
11847        assert_eq!(
11848            obs.capacity_evicted.load(Ordering::Relaxed),
11849            cap_before + 1,
11850            "the requeue eviction of a different peer is counted"
11851        );
11852        assert_eq!(
11853            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
11854            Some([1; 32])
11855        );
11856    }
11857
11858    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
11859    /// nomination arriving while an inflated pin is PENDING must not displace it.
11860    /// The inflated pin stays and is the one launched.
11861    #[test]
11862    fn first_audit_pending_lower_count_does_not_replace_higher() {
11863        let obs = Arc::new(FirstAuditObservability::default());
11864        let mono = Instant::now();
11865        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11866        let peer = test_peer(1);
11867
11868        // Inflated (high-count) sidecar pin lands in pending.
11869        scheduler.enqueue(
11870            MonetizedPinEvent {
11871                peer,
11872                pin: [1; 32],
11873                key_count: 400,
11874                quote_ts: SystemTime::now(),
11875            },
11876            &obs,
11877        );
11878        // A cheaper same-peer settlement arrives right after.
11879        scheduler.enqueue(
11880            MonetizedPinEvent {
11881                peer,
11882                pin: [2; 32],
11883                key_count: 100,
11884                quote_ts: SystemTime::now(),
11885            },
11886            &obs,
11887        );
11888
11889        assert_eq!(scheduler.pending_len(), 1);
11890        assert_eq!(
11891            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11892            Some(([1; 32], 400)),
11893            "the inflated pin must not be erased by the cheaper successor"
11894        );
11895        // The dropped cheaper nomination is counted through the enqueue path.
11896        assert_eq!(
11897            obs.suppressed_lower.load(Ordering::Relaxed),
11898            1,
11899            "the attempted cheaper-pin self-erasure is observable"
11900        );
11901
11902        // It reserves and promotes as the inflated pin/count.
11903        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11904        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11905        let reservation = scheduler.take_due_reservation(mono).expect("due");
11906        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11907        let (event, _slot) = scheduler
11908            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11909            .expect("promotes");
11910        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
11911    }
11912
11913    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
11914    /// loses the cooldown race must be requeued OVER a lower-count same-peer
11915    /// successor that arrived during its jitter, and must remain launchable once
11916    /// the shared cooldown expires — the cheaper successor cannot suppress it.
11917    #[test]
11918    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
11919        let obs = Arc::new(FirstAuditObservability::default());
11920        let mono = Instant::now();
11921        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11922        let peer = test_peer(1);
11923
11924        // Reserve the inflated pin.
11925        scheduler.enqueue(
11926            MonetizedPinEvent {
11927                peer,
11928                pin: [1; 32],
11929                key_count: 400,
11930                quote_ts: SystemTime::now(),
11931            },
11932            &obs,
11933        );
11934        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
11935        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
11936
11937        // A cheaper successor arrives during the reservation (bypasses the
11938        // window as the reserved peer) and sits in pending.
11939        scheduler.enqueue(
11940            MonetizedPinEvent {
11941                peer,
11942                pin: [2; 32],
11943                key_count: 100,
11944                quote_ts: SystemTime::now(),
11945            },
11946            &obs,
11947        );
11948        assert_eq!(scheduler.pending_len(), 1);
11949
11950        // Resolve: answerability passes but the shared cooldown is already
11951        // stamped, so the reservation loses the race and requeues.
11952        let reservation = scheduler.take_due_reservation(mono).expect("due");
11953        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11954        cooldown.insert(peer, mono);
11955        assert!(scheduler
11956            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
11957            .is_none());
11958
11959        // The inflated pin (400) replaced the cheaper successor (100).
11960        assert_eq!(scheduler.pending_len(), 1);
11961        assert_eq!(
11962            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11963            Some(([1; 32], 400)),
11964            "the inflated reserved pin must survive the requeue over the cheaper successor"
11965        );
11966        assert!(scheduler.first_audited.is_empty());
11967        assert!(scheduler.limiter.recent.peek(&peer).is_none());
11968
11969        // Once the shared cooldown expires, the inflated pin reserves and
11970        // promotes with its intended pin/count.
11971        let later = mono
11972            .checked_add(Duration::from_secs(
11973                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
11974            ))
11975            .expect("later");
11976        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
11977        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
11978        let reservation = scheduler.take_due_reservation(later).expect("due");
11979        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
11980        let (event, _slot) = scheduler
11981            .resolve(
11982                reservation,
11983                SystemTime::now(),
11984                later,
11985                &mut cooldown_later,
11986                &obs,
11987            )
11988            .expect("promotes after cooldown");
11989        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
11990    }
11991
11992    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
11993    /// launch lane, driven through the real scheduler (reserve -> resolve ->
11994    /// promote), so a stream of fresh nominations cannot keep every launch on
11995    /// the newest lane and starve the oldest.
11996    #[test]
11997    fn first_audit_lane_alternates_across_promotions() {
11998        let obs = Arc::new(FirstAuditObservability::default());
11999        let mono = Instant::now();
12000        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12001        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12002
12003        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12004        let oldest_peer = test_peer(1);
12005        let newest_peer = test_peer(2);
12006        scheduler.enqueue(
12007            MonetizedPinEvent {
12008                peer: oldest_peer,
12009                pin: [1; 32],
12010                key_count: 100,
12011                quote_ts: SystemTime::now(),
12012            },
12013            &obs,
12014        );
12015        scheduler.enqueue(
12016            MonetizedPinEvent {
12017                peer: newest_peer,
12018                pin: [2; 32],
12019                key_count: 100,
12020                quote_ts: SystemTime::now(),
12021            },
12022            &obs,
12023        );
12024
12025        let mut launched_peers = Vec::new();
12026        for _ in 0..2 {
12027            assert!(scheduler.try_reserve(
12028                mono,
12029                obs.inflight.load(Ordering::Relaxed),
12030                Duration::ZERO,
12031                &cooldown,
12032                &obs
12033            ));
12034            let reservation = scheduler.take_due_reservation(mono).expect("due");
12035            // Answerable wall time == the quote's own time (age 0).
12036            let (event, _slot) = scheduler
12037                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12038                .expect("fresh in-window quote promotes");
12039            launched_peers.push(event.peer);
12040        }
12041
12042        // First launch takes the newest lane (lane starts false = newest), the
12043        // second takes the oldest lane: strict alternation.
12044        assert_eq!(
12045            launched_peers,
12046            vec![newest_peer, oldest_peer],
12047            "consecutive promotions alternate newest-then-oldest lane"
12048        );
12049    }
12050
12051    #[test]
12052    fn first_audit_count_jump_boundaries() {
12053        // Exactly 1.5x is NOT a jump; strictly above is.
12054        assert!(!first_audit_count_jump(100, 150));
12055        assert!(first_audit_count_jump(100, 151));
12056        // Anything beats an audited zero; zero never jumps.
12057        assert!(first_audit_count_jump(0, 1));
12058        assert!(!first_audit_count_jump(0, 0));
12059        // Equal max counts must not jump (and must not overflow).
12060        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12061    }
12062
12063    /// A verified payment's quote list includes the local node's own quote, so
12064    /// the verifier emits a monetized-pin event for the local peer on every
12065    /// payment it verifies. The node cannot network-audit itself, so the
12066    /// scheduler must drop such an event at ingress: never queued, and hence
12067    /// never launched nor marked first-audited.
12068    #[test]
12069    fn first_audit_queue_drops_self_targeting_events() {
12070        let obs = Arc::new(FirstAuditObservability::default());
12071        let self_peer = test_peer(1);
12072        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12073        let self_event = MonetizedPinEvent {
12074            peer: self_peer,
12075            pin: [7; 32],
12076            key_count: 1,
12077            quote_ts: SystemTime::now(),
12078        };
12079
12080        scheduler.enqueue(self_event, &obs);
12081        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12082        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12083        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12084
12085        // A remote peer's event still queues normally under the same filter.
12086        let remote_event = MonetizedPinEvent {
12087            peer: test_peer(2),
12088            pin: [8; 32],
12089            ..self_event
12090        };
12091        scheduler.enqueue(remote_event, &obs);
12092        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12093        assert_eq!(scheduler.pending_len(), 1);
12094        assert_eq!(
12095            obs.self_target_skipped.load(Ordering::Relaxed),
12096            1,
12097            "remote event must not count as a self-target skip"
12098        );
12099    }
12100
12101    #[test]
12102    fn fresh_offer_runs_store_admission_payment_checks() {
12103        let context = fresh_offer_payment_context();
12104        assert_eq!(context, VerificationContext::FreshReplication);
12105        // Fresh replication must keep verifying exactly like a direct client
12106        // PUT (store-strength cache, same live checks); the variant only
12107        // exists so price-floor telemetry can tell the two paths apart.
12108        assert!(context.is_store_admission());
12109    }
12110
12111    #[test]
12112    fn paid_notify_uses_paid_list_admission_payment_checks() {
12113        assert_eq!(
12114            paid_notify_payment_context(),
12115            VerificationContext::PaidListAdmission
12116        );
12117    }
12118
12119    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12120    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12121    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12122    #[test]
12123    fn monetized_quote_audit_window_fails_closed_both_ends() {
12124        let now = SystemTime::now();
12125        // Fresh (just quoted) and small future/past skew -> audited.
12126        assert!(quote_within_audit_window(now, now));
12127        assert!(quote_within_audit_window(
12128            now + Duration::from_secs(60),
12129            now
12130        ));
12131        assert!(quote_within_audit_window(
12132            now - Duration::from_secs(3600),
12133            now
12134        ));
12135        // Far future (badly-skewed / replayed) -> skipped.
12136        assert!(!quote_within_audit_window(
12137            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12138            now
12139        ));
12140        // Older than the window -> skipped (pin may have aged out).
12141        assert!(!quote_within_audit_window(
12142            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12143            now
12144        ));
12145    }
12146
12147    #[tokio::test]
12148    async fn replication_branch_lagged_events_are_counted() {
12149        let before = audit_metrics::replication_event_lagged_total();
12150        let flow = handle_replication_event_recv_error(
12151            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12152        );
12153        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12154        let after = audit_metrics::replication_event_lagged_total();
12155        assert_eq!(after.saturating_sub(before), 3);
12156    }
12157
12158    #[tokio::test]
12159    async fn replication_branch_closed_events_stop_the_loop() {
12160        let flow =
12161            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12162        assert_eq!(flow, std::ops::ControlFlow::Break(()));
12163    }
12164
12165    #[tokio::test]
12166    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12167        let (sender, mut receiver) = mpsc::channel(1);
12168        let dropped_body =
12169            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12170                keys: Vec::new(),
12171                paid_list_check_indices: Vec::new(),
12172            });
12173        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12174        let first = InboundReplicationMessage {
12175            source: test_peer(0xC1),
12176            msg: ReplicationMessage {
12177                request_id: 1,
12178                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12179                    key: test_key(1),
12180                }),
12181            },
12182            rr_message_id: None,
12183            received_at: Instant::now(),
12184        };
12185        let second = InboundReplicationMessage {
12186            source: test_peer(0xC2),
12187            msg: ReplicationMessage {
12188                request_id: 2,
12189                body: dropped_body.clone(),
12190            },
12191            rr_message_id: None,
12192            received_at: Instant::now(),
12193        };
12194
12195        assert!(try_enqueue_serial_message(&sender, first).is_ok());
12196        let dropped = try_enqueue_serial_message(&sender, second)
12197            .expect_err("a full serial queue must refuse the second message");
12198        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12199        assert_eq!(dropped.message_class, "verification_request");
12200        assert_eq!(dropped.queue_depth, 1);
12201        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12202        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12203
12204        let queued = receiver
12205            .recv()
12206            .await
12207            .expect("first message should remain queued");
12208        assert_eq!(queued.msg.request_id, 1);
12209        assert!(receiver.try_recv().is_err());
12210    }
12211
12212    #[tokio::test]
12213    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12214        let peer = test_peer(0x44);
12215        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12216
12217        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12218        let mut digest_guards = Vec::new();
12219        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12220            let guard = admit_audit_responder(
12221                &semaphore,
12222                &digest_inflight,
12223                &peer,
12224                AuditResponderClass::Digest,
12225            )
12226            .await;
12227            assert!(guard.is_ok());
12228            digest_guards.push(guard);
12229        }
12230        assert!(
12231            admit_audit_responder(
12232                &semaphore,
12233                &digest_inflight,
12234                &peer,
12235                AuditResponderClass::Digest,
12236            )
12237            .await
12238            .is_err(),
12239            "digest class must stop at its documented per-source cap"
12240        );
12241        drop(digest_guards);
12242
12243        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12244        let mut subtree_guards = Vec::new();
12245        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12246            let guard = admit_audit_responder(
12247                &semaphore,
12248                &subtree_inflight,
12249                &peer,
12250                AuditResponderClass::Subtree,
12251            )
12252            .await;
12253            assert!(guard.is_ok());
12254            subtree_guards.push(guard);
12255        }
12256        assert!(
12257            admit_audit_responder(
12258                &semaphore,
12259                &subtree_inflight,
12260                &peer,
12261                AuditResponderClass::Subtree,
12262            )
12263            .await
12264            .is_err(),
12265            "subtree class must retain the deployed cap of two"
12266        );
12267        drop(subtree_guards);
12268    }
12269
12270    #[test]
12271    fn in_scope_audit_deadlines_share_one_formula() {
12272        let config = config::ReplicationConfig::default();
12273        for key_count in [1, 4, 16] {
12274            assert_eq!(
12275                audit::responsible_audit_response_timeout(&config, key_count),
12276                config.audit_response_timeout(key_count)
12277            );
12278            assert_eq!(
12279                pruning::prune_audit_response_timeout(&config, key_count),
12280                config.audit_response_timeout(key_count)
12281            );
12282        }
12283        assert_eq!(
12284            possession::possession_probe_response_timeout(&config),
12285            config.audit_response_timeout(1)
12286        );
12287    }
12288
12289    #[test]
12290    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12291        const EXISTING_SOURCE_ID: u8 = 1;
12292        const HINT_SENDER_ID: u8 = 2;
12293
12294        let existing_source = test_peer(EXISTING_SOURCE_ID);
12295        let hint_sender = test_peer(HINT_SENDER_ID);
12296        let mut sources = vec![existing_source];
12297
12298        let hint_sources = HashSet::from([hint_sender]);
12299        add_replica_hint_sources(&mut sources, &hint_sources);
12300        add_replica_hint_sources(&mut sources, &hint_sources);
12301
12302        // A paid-only advertiser leaves the claim set empty (see
12303        // `queue_admitted_hints`), so it contributes no fetch source.
12304        add_replica_hint_sources(&mut sources, &HashSet::new());
12305
12306        assert_eq!(sources, vec![existing_source, hint_sender]);
12307    }
12308
12309    #[test]
12310    fn audit_timeout_preserves_active_bootstrap_claim() {
12311        assert!(!audit_failure_clears_bootstrap_claim(
12312            &AuditFailureReason::Timeout
12313        ));
12314    }
12315
12316    fn strike_peer(b: u8) -> PeerId {
12317        let mut bytes = [0u8; 32];
12318        bytes[0] = b;
12319        PeerId::from_bytes(bytes)
12320    }
12321
12322    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12323    // cooldown must collapse a gossip flood into at most one audit per window.
12324
12325    #[test]
12326    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12327        let peer = strike_peer(1);
12328        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12329        let t0 = Instant::now();
12330        // First gossip in the window passes; a burst of further gossips at the
12331        // same instant are all suppressed.
12332        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12333        let mut passed = 1;
12334        for _ in 0..100 {
12335            if cooldown_allows_audit(&mut map, &peer, t0) {
12336                passed += 1;
12337            }
12338        }
12339        assert_eq!(
12340            passed, 1,
12341            "a flood at one instant must trigger exactly one audit"
12342        );
12343    }
12344
12345    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12346    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12347    // consumes the window. This is the property the isolated cooldown tests above
12348    // cannot see: they never sample the lottery, so a regression that reordered
12349    // the gates (sample probability first, only stamp the cooldown on a win)
12350    // would still pass them while breaking flood-resistance: a flood would then
12351    // re-roll the lottery on EVERY message until one won, multiplying audits.
12352    //
12353    // We model the exact production gate order (attempt-window, lottery,
12354    // shared cooldown) with a lottery driven by a fixed outcome instead of
12355    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
12356    // messages all WIN. With the production order, the losing first ticket
12357    // burns the ATTEMPT window and every later winner in the same window is
12358    // blocked, so there are 0 audits this window. If the gates were flipped,
12359    // the second message's winning ticket would slip through. The window only
12360    // reopens after it elapses.
12361    //
12362    // FLIPS IF: the lottery is sampled before the attempt-window
12363    // check-and-stamp (a losing ticket no longer consumes the window),
12364    // re-enabling a flood-amplified audit storm.
12365    #[test]
12366    fn losing_lottery_still_consumes_attempt_window() {
12367        // Calls the SHIPPED `audit_launch_decision` (the same function
12368        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
12369        // production fails this test — not a local reimplementation.
12370        let peer = strike_peer(3);
12371        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12372        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12373        let t0 = Instant::now();
12374
12375        // First flooded message at t0 LOSES the lottery, but the attempt window
12376        // is stamped BEFORE the lottery is consulted, so the window is consumed.
12377        assert!(
12378            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12379            "a losing ticket launches no audit"
12380        );
12381
12382        // 99 more flooded messages at the same instant would all WIN the lottery,
12383        // yet every one must be blocked by the attempt window the loser stamped.
12384        // (If production sampled the lottery FIRST, these would each get a fresh
12385        // roll and audits would multiply — this assertion catches that reorder.)
12386        let mut audits = 0;
12387        for _ in 0..99 {
12388            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12389                audits += 1;
12390            }
12391        }
12392        assert_eq!(
12393            audits, 0,
12394            "a losing first ticket must consume the attempt window so no later \
12395             flooded message in the same window can audit"
12396        );
12397
12398        // The window only reopens after it elapses; the next winning ticket
12399        // then launches exactly one audit and stamps the SHARED cooldown.
12400        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12401        assert!(
12402            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12403            "after the window a winning ticket audits again"
12404        );
12405        assert!(
12406            launched.contains_key(&peer),
12407            "a real launch stamps the shared cooldown"
12408        );
12409    }
12410
12411    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
12412    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
12413    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
12414    /// first audit deferred until its answerability window expires.
12415    ///
12416    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
12417    /// loss (the pre-split behavior, where both paths shared one map).
12418    #[test]
12419    fn losing_lottery_does_not_suppress_monetized_first_audit() {
12420        let peer = strike_peer(4);
12421        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12422        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12423        let t0 = Instant::now();
12424
12425        // A losing ticket consumes the gossip attempt window...
12426        assert!(!audit_launch_decision(
12427            &mut attempts,
12428            &mut launched,
12429            &peer,
12430            t0,
12431            false
12432        ));
12433        // ...but leaves the shared map untouched, so the first-audit reserve
12434        // gate (read-only) and the authoritative promotion check-and-stamp both
12435        // still allow the paid audit to launch immediately.
12436        assert!(
12437            cooldown_would_allow(&launched, &peer, t0),
12438            "reserve gate must not see a losing ticket as audit coverage"
12439        );
12440        assert!(
12441            cooldown_allows_audit(&mut launched, &peer, t0),
12442            "promotion must not be deferred by a losing ticket"
12443        );
12444
12445        // Conversely a WINNING ticket (real audit sent) does suppress the
12446        // first audit for the window, which is the intended shared semantics.
12447        let peer_won = strike_peer(5);
12448        assert!(audit_launch_decision(
12449            &mut attempts,
12450            &mut launched,
12451            &peer_won,
12452            t0,
12453            true
12454        ));
12455        assert!(
12456            !cooldown_would_allow(&launched, &peer_won, t0),
12457            "a real gossip audit still covers the peer for the window"
12458        );
12459    }
12460
12461    #[test]
12462    fn cooldown_lets_audit_through_after_the_window() {
12463        let peer = strike_peer(2);
12464        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12465        let t0 = Instant::now();
12466        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12467        // Within the window: suppressed.
12468        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12469        assert!(!cooldown_allows_audit(&mut map, &peer, within));
12470        // Past the window: allowed again.
12471        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12472        assert!(cooldown_allows_audit(&mut map, &peer, after));
12473    }
12474
12475    #[test]
12476    fn cooldown_is_per_peer_independent() {
12477        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12478        let t0 = Instant::now();
12479        // Different peers each get their own first-audit pass at the same instant.
12480        for i in 0..20u8 {
12481            assert!(
12482                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12483                "peer {i} should be auditable independently"
12484            );
12485        }
12486    }
12487
12488    #[test]
12489    fn audit_on_gossip_constants_match_adr() {
12490        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
12491        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
12492        // values above 5 would silently never be requested).
12493        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12494        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12495        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12496    }
12497
12498    // (d) A confirmed storage-integrity failure penalizes immediately and
12499    // revokes credit; it is not a timeout.
12500    #[test]
12501    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12502        assert!(audit_failure_clears_bootstrap_claim(
12503            &AuditFailureReason::DigestMismatch
12504        ));
12505        assert!(audit_failure_revokes_holder_credit(
12506            &AuditFailureReason::DigestMismatch
12507        ));
12508    }
12509
12510    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
12511    /// uses: confirmed failures revoke credit, `Timeout` does not.
12512    #[test]
12513    fn confirmed_failures_revoke_credit_timeout_does_not() {
12514        for reason in [
12515            AuditFailureReason::MalformedResponse,
12516            AuditFailureReason::DigestMismatch,
12517            AuditFailureReason::KeyAbsent,
12518            AuditFailureReason::Rejected,
12519        ] {
12520            assert!(
12521                audit_failure_revokes_holder_credit(&reason),
12522                "confirmed failure {reason:?} must revoke holder credit"
12523            );
12524        }
12525        assert!(
12526            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12527            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12528        );
12529    }
12530
12531    /// Wiring test for the security fix: the helper the handler calls
12532    /// actually strips a credited peer on a confirmed failure
12533    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
12534    /// Records genuine credit first so neither assertion is vacuous;
12535    /// this fails if `forget_peer` stops being called, or if the
12536    /// `Timeout` exclusion is dropped (both verified by mutation).
12537    #[test]
12538    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12539        let peer = test_peer(0xAB);
12540        let key = test_key(1);
12541        let hash = [0xCD; 32];
12542
12543        // Confirmed failure -> credit revoked.
12544        let mut provers = RecentProvers::new();
12545        provers.record_proof(key, peer, hash, Instant::now());
12546        assert!(
12547            provers.is_credited_holder(&key, &peer, &hash),
12548            "precondition: peer credited before failure"
12549        );
12550        apply_audit_failure_credit_revocation(
12551            &mut provers,
12552            &peer,
12553            &AuditFailureReason::DigestMismatch,
12554        );
12555        assert!(
12556            !provers.is_credited_holder(&key, &peer, &hash),
12557            "DigestMismatch must strip the peer's holder credit"
12558        );
12559
12560        // Timeout -> credit retained.
12561        let mut provers_timeout = RecentProvers::new();
12562        provers_timeout.record_proof(key, peer, hash, Instant::now());
12563        apply_audit_failure_credit_revocation(
12564            &mut provers_timeout,
12565            &peer,
12566            &AuditFailureReason::Timeout,
12567        );
12568        assert!(
12569            provers_timeout.is_credited_holder(&key, &peer, &hash),
12570            "Timeout must retain holder credit (deliberate liveness cushion)"
12571        );
12572    }
12573
12574    #[test]
12575    fn decoded_audit_failures_clear_active_bootstrap_claim() {
12576        for reason in [
12577            AuditFailureReason::MalformedResponse,
12578            AuditFailureReason::DigestMismatch,
12579            AuditFailureReason::KeyAbsent,
12580            AuditFailureReason::Rejected,
12581        ] {
12582            assert!(
12583                audit_failure_clears_bootstrap_claim(&reason),
12584                "decoded non-bootstrap failure {reason:?} should clear active claim"
12585            );
12586        }
12587    }
12588
12589    #[test]
12590    fn first_failed_key_label_truncates_to_16_hex_chars() {
12591        // The high-order 8 bytes of the XorName determine the label so an
12592        // operator can group audit-failures on the same chunk prefix.
12593        let mut key = [0u8; 32];
12594        key[0] = 0x18;
12595        key[7] = 0xff;
12596        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
12597        // to verify they are NOT included in the label.
12598        for byte in &mut key[8..] {
12599            *byte = 0xAA;
12600        }
12601        let label = first_failed_key_label(&[key]);
12602        // Only the first 8 bytes are encoded, low-order bytes are dropped.
12603        assert_eq!(label, "0x18000000000000ff");
12604        assert_eq!(label.len(), "0x".len() + 16);
12605    }
12606
12607    #[test]
12608    fn first_failed_key_label_falls_back_when_empty() {
12609        // Should never happen in production (audit failure handling rejects
12610        // empty sets), but the formatter must still produce a valid label
12611        // so the log line doesn't contain a misleading default.
12612        assert_eq!(first_failed_key_label(&[]), "0x");
12613    }
12614
12615    #[test]
12616    fn first_failed_key_label_uses_first_key_only() {
12617        let first = [0x11u8; 32];
12618        let second = [0x22u8; 32];
12619        assert_eq!(
12620            first_failed_key_label(&[first, second]),
12621            format!("0x{}", hex::encode(&first[..8]))
12622        );
12623    }
12624
12625    // -- apply_fetch_result --------------------------------------------------
12626    //
12627    // The worker's disposition of a fetch outcome. Note there is no trust
12628    // handle in `apply_fetch_result`'s signature: the worker cannot report a
12629    // trust event for ANY outcome, and `execute_single_fetch` returns
12630    // `NoLongerResponsible` before its trust-reporting paths — the source did
12631    // nothing wrong when this node's own responsibility lapsed.
12632
12633    /// Route `key` through the real pipeline stages (pending → promoted →
12634    /// dequeued → in-flight) so it carries a verification retry-slot
12635    /// reservation, exactly as a worker-dequeued key does. Returns the
12636    /// in-flight source.
12637    fn drive_key_in_flight(
12638        q: &mut ReplicationQueues,
12639        key: XorName,
12640        sources: Vec<PeerId>,
12641    ) -> PeerId {
12642        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
12643        let now = Instant::now();
12644        let entry = VerificationEntry {
12645            state: VerificationState::PendingVerify,
12646            verified_sources: Vec::new(),
12647            tried_sources: HashSet::new(),
12648            created_at: now,
12649            next_verify_at: now,
12650            hint_sources: HashSet::from([hinter]),
12651            replica_hint_sources: HashSet::from([hinter]),
12652        };
12653        assert!(q.add_pending_verify(key, entry).admitted());
12654        assert!(q.promote_pending_to_fetch(key, key, sources));
12655        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
12656        let source = *candidate.sources.first().expect("candidate has a source");
12657        q.start_dequeued_fetch(candidate, source);
12658        source
12659    }
12660
12661    #[test]
12662    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
12663        const RETRY_AFTER: Duration = Duration::from_secs(60);
12664
12665        let mut q = ReplicationQueues::new();
12666        let key = test_key(0xAB);
12667        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
12668        assert_eq!(q.retry_reserved_slot_count(), 1);
12669
12670        let follow_up =
12671            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
12672
12673        assert_eq!(
12674            follow_up,
12675            FetchFollowUp::Terminal,
12676            "lapsed responsibility must run the caller's terminal bootstrap accounting"
12677        );
12678        assert!(
12679            !q.contains_key(&key),
12680            "the key must leave every pipeline stage — alternate sources included"
12681        );
12682        assert_eq!(
12683            q.pending_count(),
12684            0,
12685            "a lapsed-responsibility key must not be requeued for verification"
12686        );
12687        assert_eq!(
12688            q.retry_reserved_slot_count(),
12689            0,
12690            "terminal exit must release the verification retry-slot reservation"
12691        );
12692    }
12693
12694    #[test]
12695    fn no_longer_responsible_shares_the_stored_terminal_path() {
12696        const RETRY_AFTER: Duration = Duration::from_secs(60);
12697
12698        // Both variants must walk the identical terminal gate so the
12699        // battle-tested Stored accounting (retry-slot release + bootstrap
12700        // pending-set shrink in the caller) covers lapsed responsibility too.
12701        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
12702            let mut q = ReplicationQueues::new();
12703            let key = test_key(0xCD);
12704            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
12705
12706            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
12707
12708            assert_eq!(follow_up, FetchFollowUp::Terminal);
12709            assert!(!q.contains_key(&key));
12710            assert_eq!(q.retry_reserved_slot_count(), 0);
12711        }
12712    }
12713
12714    #[test]
12715    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
12716        const RETRY_AFTER: Duration = Duration::from_secs(60);
12717
12718        let mut q = ReplicationQueues::new();
12719        let key = test_key(0xEF);
12720        let first = test_peer(0x04);
12721        let second = test_peer(0x05);
12722        drive_key_in_flight(&mut q, key, vec![first, second]);
12723
12724        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12725        assert_eq!(
12726            follow_up,
12727            FetchFollowUp::RetryFrom(second),
12728            "a failed source must not abandon the remaining verified sources"
12729        );
12730        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
12731
12732        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12733        assert_eq!(
12734            follow_up,
12735            FetchFollowUp::RequeuedForVerification,
12736            "exhausted sources must restore the reserved verification entry"
12737        );
12738        assert_eq!(q.pending_count(), 1);
12739        assert_eq!(
12740            q.retry_reserved_slot_count(),
12741            0,
12742            "the reservation converts back into the pending entry itself"
12743        );
12744    }
12745
12746    #[test]
12747    fn source_failure_without_retry_metadata_is_terminal() {
12748        const RETRY_AFTER: Duration = Duration::from_secs(60);
12749
12750        // Direct enqueue (no pending entry) models a fetch with no
12751        // verification retry reservation to restore.
12752        let mut q = ReplicationQueues::new();
12753        let key = test_key(0x1F);
12754        let source = test_peer(0x06);
12755        assert!(q.enqueue_fetch(key, key, vec![source]));
12756        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
12757        q.start_dequeued_fetch(candidate, source);
12758
12759        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
12760
12761        assert_eq!(follow_up, FetchFollowUp::Terminal);
12762        assert!(!q.contains_key(&key));
12763    }
12764}