Skip to main content

ant_node/replication/
mod.rs

1//! Replication subsystem for the Autonomi network.
2//!
3//! Implements Kademlia-style replication with:
4//! - Fresh replication with `PoP` verification
5//! - Neighbor sync with round-robin cycle management
6//! - Batched quorum verification
7//! - Storage audit protocol (anti-outsourcing)
8//! - `PaidForList` persistence and convergence
9//! - Responsibility pruning with hysteresis
10
11// The replication engine intentionally holds `RwLock` read guards across await
12// boundaries (e.g. reading sync_history while calling audit_tick). Clippy's
13// nursery lint `significant_drop_tightening` flags these, but the guards must
14// remain live for the duration of the call.
15#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod possession;
29pub mod protocol;
30pub mod pruning;
31pub mod quorum;
32pub mod recent_provers;
33pub mod scheduling;
34pub mod slice;
35pub mod storage_commitment_audit;
36pub mod subtree;
37pub mod types;
38
39use std::collections::{HashMap, HashSet, VecDeque};
40use std::fmt;
41use std::num::NonZeroUsize;
42use std::ops::ControlFlow;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::Arc;
46use std::time::{Duration, Instant, SystemTime};
47
48use lru::LruCache;
49use std::pin::Pin;
50
51use crate::logging::{debug, error, info, warn};
52use futures::stream::FuturesUnordered;
53use futures::{future::join_all, Future, StreamExt};
54use parking_lot::Mutex;
55use rand::rngs::StdRng;
56use rand::{Rng, SeedableRng};
57use tokio::sync::broadcast::error::RecvError;
58use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
59use tokio::task::JoinHandle;
60use tokio_util::sync::CancellationToken;
61use tokio_util::task::TaskTracker;
62
63use crate::ant_protocol::XorName;
64use crate::error::{Error, Result};
65use crate::payment::{
66    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
67    MIN_PAYMENT_PROOF_SIZE_BYTES,
68};
69use crate::replication::audit::AuditTickResult;
70use crate::replication::audit_coordinator::AuditChallengeCoordinator;
71use crate::replication::audit_metrics::{
72    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
73    ReplicationResponderClass, ResponderAdmissionCeiling,
74};
75use crate::replication::commitment::{commitment_hash, StorageCommitment};
76use crate::replication::commitment_state::{
77    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
78};
79use crate::replication::config::{
80    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
81    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
82    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
83    MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
84    REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
85    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
86};
87use crate::replication::paid_list::PaidList;
88use crate::replication::protocol::{
89    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
90    VerificationResponse,
91};
92use crate::replication::quorum::KeyVerificationOutcome;
93use crate::replication::recent_provers::RecentProvers;
94use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
95use crate::replication::types::{
96    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
97    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
98    VerificationState,
99};
100use crate::storage::{CapacityVerdict, LmdbStorage};
101use saorsa_core::identity::{NodeIdentity, PeerId};
102use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
103use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
104
105/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
106/// because it was full (Amendment 2). Process-global because the producer is
107/// the payment verifier (a different module) and the drop happens before the
108/// per-drainer `received` counter. A non-zero value is the rollout signal that
109/// nomination ingress is saturating — benign (penalty-free, lottery/next-
110/// payment covered) but worth watching. `Closed` (engine shut down) is not
111/// counted: it is not a saturation signal.
112static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
113
114/// Record one ingress-full drop. Called by the payment verifier's `try_send`
115/// sites; read by the drainer's periodic summary.
116pub(crate) fn note_monetized_ingress_drop() {
117    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
118}
119
120#[derive(Default)]
121struct FirstAuditObservability {
122    received: AtomicU64,
123    queued: AtomicU64,
124    coalesced: AtomicU64,
125    duplicates: AtomicU64,
126    capacity_evicted: AtomicU64,
127    /// An event targeting the local peer itself, dropped at ingress: the node
128    /// cannot network-audit itself (no dialable address for the local peer).
129    self_target_skipped: AtomicU64,
130    /// A strictly-lower-count same-peer nomination that was dropped so a
131    /// higher-count pending pin survived. A sustained rise is the signal of an
132    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
133    suppressed_lower: AtomicU64,
134    cooldown_deferred_attempts: AtomicU64,
135    rate_deferred_attempts: AtomicU64,
136    window_deduped: AtomicU64,
137    launched: AtomicU64,
138    passed: AtomicU64,
139    timed_out: AtomicU64,
140    failed: AtomicU64,
141    bootstrap_claims: AtomicU64,
142    idle: AtomicU64,
143    insufficient_keys: AtomicU64,
144    outside_answerability_window: AtomicU64,
145    inflight: AtomicU64,
146}
147
148/// Test-only snapshot of the first-audit scheduler counters.
149///
150/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
151/// self-targeting monetized pin was dropped and never launched) instead of
152/// scraping log lines.
153#[cfg(any(test, feature = "test-utils"))]
154#[derive(Debug, Clone, Copy)]
155pub struct FirstAuditStats {
156    /// Events ingested from the monetized-pin channel.
157    pub received: u64,
158    /// Events accepted into the pending first-audit queue.
159    pub queued: u64,
160    /// Events dropped because they targeted the local peer.
161    pub self_target_skipped: u64,
162    /// Audits launched.
163    pub launched: u64,
164    /// Launched audits that passed.
165    pub passed: u64,
166    /// Launched audits that timed out (non-response lane).
167    pub timed_out: u64,
168    /// Launched audits that ended in a confirmed failure.
169    pub failed: u64,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum FirstAuditTerminalOutcome {
174    Passed,
175    Timeout,
176    Failed,
177    BootstrapClaim,
178    Idle,
179    InsufficientKeys,
180}
181
182impl FirstAuditTerminalOutcome {
183    #[cfg(any(feature = "logging", test))]
184    const fn as_str(self) -> &'static str {
185        match self {
186            Self::Passed => "passed",
187            Self::Timeout => "timeout",
188            Self::Failed => "failed",
189            Self::BootstrapClaim => "bootstrap_claim",
190            Self::Idle => "idle",
191            Self::InsufficientKeys => "insufficient_keys",
192        }
193    }
194}
195
196fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
197    match result {
198        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
199        AuditTickResult::Failed {
200            evidence:
201                FailureEvidence::AuditFailure {
202                    reason: AuditFailureReason::Timeout,
203                    ..
204                },
205            ..
206        } => FirstAuditTerminalOutcome::Timeout,
207        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
208        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
209        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
210        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
211    }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum FirstAuditQueueOutcome {
216    /// New peer inserted with free capacity.
217    Queued,
218    /// Collapsed with an existing same-peer entry; the incoming won (higher
219    /// count, or equal count and newer) and replaced it.
220    Coalesced,
221    /// Collapsed with an existing same-peer entry; the incoming LOST because it
222    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
223    /// in place. This is the attempted cheaper-pin self-erasure signal.
224    SuppressedLower,
225    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
226    /// lost the freshness tie (it was not the newer of the two) and the
227    /// existing entry was retained. Benign, not an attack signal.
228    RetainedOnTie,
229    /// A DIFFERENT peer's entry was displaced from the capped pending queue
230    /// (random victim) to make room.
231    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
232}
233
234/// Coalesce a monetized nomination into the per-peer pending queue with a
235/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
236/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
237///
238/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
239/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
240/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
241/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
242/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
243/// cannot promote the retained pin's lane position.
244///
245/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
246/// last, so it wins an equal-count tie for freshness) from a cooldown-race
247/// requeue of an older reserved event (the pending successor is newer, so it
248/// wins the tie).
249fn coalesce_first_audit_event(
250    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
251    incoming: MonetizedPinEvent,
252    incoming_is_newer: bool,
253    rng: &mut StdRng,
254) -> FirstAuditQueueOutcome {
255    if let Some(existing) = pending.peek(&incoming.peer) {
256        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
257        // the retained pin's recency (the security-relevant self-erasure case).
258        if incoming.key_count < existing.key_count {
259            return FirstAuditQueueOutcome::SuppressedLower;
260        }
261        // Equal count -> keep the fresher; an older incoming loses a benign tie.
262        if incoming.key_count == existing.key_count && !incoming_is_newer {
263            return FirstAuditQueueOutcome::RetainedOnTie;
264        }
265        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
266        // the value and bumps MRU; replacing an existing key never evicts a
267        // different peer.
268        let _ = pending.push(incoming.peer, incoming);
269        return FirstAuditQueueOutcome::Coalesced;
270    }
271    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
272    // never the LRU: deterministic keep-newest would let an ordered batch of
273    // `cap` distinct-peer nominations flush a chosen target before any launch
274    // lane sees it, cutting the eviction cost from probabilistic to exact. A
275    // random victim caps an attacker's per-nomination eviction probability at
276    // `1/cap` regardless of arrival order or timing, so suppressing a specific
277    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
278    // nominations and is never certain (ADR-0004 Amendment 4).
279    if pending.len() >= pending.cap().get() {
280        let victim = {
281            let idx = rng.gen_range(0..pending.len());
282            pending.iter().nth(idx).map(|(p, _)| *p)
283        };
284        if let Some(victim_peer) = victim {
285            if let Some(evicted) = pending.pop(&victim_peer) {
286                let _ = pending.push(incoming.peer, incoming);
287                return FirstAuditQueueOutcome::CapacityEvicted {
288                    peer: victim_peer,
289                    pin: evicted.pin,
290                };
291            }
292        }
293    }
294    match pending.push(incoming.peer, incoming) {
295        None => FirstAuditQueueOutcome::Queued,
296        // Unreachable: the random-displacement branch above guarantees
297        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
298        // exists). Kept so any future logic error surfaces as an ACCOUNTED
299        // eviction rather than silent loss — but note this arm would be
300        // LRU-order, not random, so it must stay unreachable.
301        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
302            peer: evicted_peer,
303            pin: evicted.pin,
304        },
305    }
306}
307
308/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
309/// prefiltering a nomination's answerability at schedule time, covering the
310/// spawn/dispatch latency between the timer firing and the wire challenge so a
311/// jitter==MAX pin is not admitted only to fail the authoritative check by a
312/// few milliseconds. Tiny against the multi-hour answerability window.
313const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
314
315/// A first audit the limiter recently launched at a peer: when, and the
316/// committed key count that was audited (for the count-jump override).
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318struct RecentFirstAudit {
319    launched_at: Instant,
320    key_count: u32,
321}
322
323/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
324/// panicking or cancelled audit task can never leak a slot and wedge the
325/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
326struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
327
328impl FirstAuditInflightSlot {
329    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
330        observability.inflight.fetch_add(1, Ordering::Relaxed);
331        Self(Arc::clone(observability))
332    }
333}
334
335impl Drop for FirstAuditInflightSlot {
336    fn drop(&mut self) {
337        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
338    }
339}
340
341/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
342/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
343/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
344/// overflow-free integer math). A jump re-nominates a peer despite a recent
345/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
346/// only, so no gossip-lottery audit can ever cover it.
347const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
348    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
349        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
350}
351
352/// The launch limiter's verdict for one pending monetized pin.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum LimiterVerdict {
355    /// Within budget and window: the caller may reserve a launch (and consumes
356    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
357    Admit,
358    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
359    /// pin pending and retry on a later tick.
360    RateDeferred,
361    /// The peer had a first audit within
362    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
363    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
364    /// gossip-lottery re-audit path is unaffected).
365    WindowDeduped,
366}
367
368/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
369/// (launch rate), an in-flight cap, and a per-peer re-audit window that
370/// survives pin rotation.
371///
372/// This is the load-bearing aggregate bound the original scheduler lacked:
373/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
374/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
375/// `now`/`inflight` values so every decision is unit-testable without a
376/// runtime.
377struct FirstAuditLimiter {
378    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
379    tokens: u32,
380    /// Refill anchor. While the bucket is full this tracks `now` (a full
381    /// bucket accrues nothing); while below capacity it advances only by
382    /// whole refill intervals so fractional elapsed time is never lost.
383    last_refill: Instant,
384    /// Peers given a first audit recently, with the audited key count.
385    /// Bounded like the drainer's other per-peer maps.
386    recent: LruCache<PeerId, RecentFirstAudit>,
387}
388
389impl FirstAuditLimiter {
390    fn new(now: Instant) -> Self {
391        Self {
392            tokens: config::FIRST_AUDIT_BUDGET_BURST,
393            last_refill: now,
394            recent: LruCache::new(
395                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
396            ),
397        }
398    }
399
400    /// Whether the per-peer re-audit window admits a nomination for `peer`
401    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
402    /// call at ENQUEUE time — suppressed nominations never occupy pending
403    /// slots — without disturbing LRU recency.
404    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
405        self.recent.peek(peer).map_or(true, |prev| {
406            now.saturating_duration_since(prev.launched_at)
407                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
408                || first_audit_count_jump(prev.key_count, key_count)
409        })
410    }
411
412    /// Refill the token bucket for the time elapsed up to `now`.
413    fn refill(&mut self, now: Instant) {
414        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
415            // Full bucket accrues nothing; keep the anchor current so the
416            // next consumption starts its interval from here.
417            self.last_refill = now;
418            return;
419        }
420        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
421        let elapsed = now.saturating_duration_since(self.last_refill);
422        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
423        if earned == 0 {
424            return;
425        }
426        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
427        if earned >= capacity_gap {
428            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
429            self.last_refill = now;
430        } else {
431            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
432            self.tokens = self
433                .tokens
434                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
435            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
436            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
437        }
438    }
439
440    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
441    /// caller runs the remaining (per-peer cooldown) gate and calls
442    /// [`Self::commit_launch`] only for a launch that actually happens, so a
443    /// deferral elsewhere never burns budget or stamps the window.
444    fn assess(
445        &mut self,
446        peer: &PeerId,
447        key_count: u32,
448        now: Instant,
449        inflight: u64,
450    ) -> LimiterVerdict {
451        if !self.window_allows(peer, key_count, now) {
452            return LimiterVerdict::WindowDeduped;
453        }
454        self.refill(now);
455        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
456            return LimiterVerdict::RateDeferred;
457        }
458        LimiterVerdict::Admit
459    }
460
461    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
462    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
463    /// only at [`Self::promote`], after the authoritative post-jitter
464    /// answerability check, so a reservation that is later cancelled leaves no
465    /// suppression behind.
466    fn reserve_token(&mut self) {
467        self.tokens = self.tokens.saturating_sub(1);
468    }
469
470    /// Return a token consumed by a reservation that was cancelled before it
471    /// launched (answerability lapsed or a concurrent gossip audit won the
472    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
473    /// the bucket.
474    fn refund_token(&mut self) {
475        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
476    }
477
478    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
479    /// (promotion). Separated from token consumption so suppression is only
480    /// ever recorded for a real send.
481    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
482        self.recent.put(
483            peer,
484            RecentFirstAudit {
485                launched_at: now,
486                key_count,
487            },
488        );
489    }
490
491    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
492    /// and stamp the window in one call. Production splits these across
493    /// reservation and promotion; the limiter's own budget/window unit tests do
494    /// not model the jitter reservation and use this shorthand.
495    #[cfg(test)]
496    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
497        self.reserve_token();
498        self.promote(peer, key_count, now);
499    }
500}
501
502/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
503/// across the ENTIRE launch-jitter window ending at
504/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
505/// for it cannot later require aborting an out-of-window challenge. The
506/// too-future bound is enforced at `now` (a jitter delay only ages a pin
507/// forward, never toward the future); the too-old bound is enforced at the
508/// latest possible send time. This is a conservative admission prefilter; the
509/// authoritative answerability check still runs at promotion against the real
510/// send-time wall clock, so A1 (no false conviction) holds regardless of how
511/// jitter and the answerability margin are sized. `checked_add` overflow fails
512/// closed (skip the pin).
513fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
514    let Some(latest_send) = now
515        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
516        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
517    else {
518        return false;
519    };
520    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
521}
522
523/// Open the single first-audit reservation from `pending` if none is
524/// outstanding: samples the launch jitter, snapshots the shared cooldown
525/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
526/// shared implementation for both drainer call sites — the per-wake launch
527/// phase and the pre-overflow opportunity inside the ingress batch — so the
528/// two cannot drift.
529async fn open_first_audit_reservation(
530    scheduler: &mut FirstAuditScheduler,
531    cooldown: &RwLock<HashMap<PeerId, Instant>>,
532    observability: &Arc<FirstAuditObservability>,
533) {
534    if scheduler.has_reservation() {
535        return;
536    }
537    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
538        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
539    ));
540    let inflight = observability.inflight.load(Ordering::Relaxed);
541    let reserved = {
542        let cooldown = cooldown.read().await;
543        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
544    };
545    if reserved {
546        if let Some(peer) = scheduler.reserved_peer() {
547            debug!(
548                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
549                scheduler.pending_len()
550            );
551        }
552    }
553}
554
555/// A far-future `Instant` used to effectively DISABLE the promotion-timer
556/// select arm when no reservation is outstanding. The drainer still wakes at
557/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
558/// needs to be comfortably past the next tick.
559fn first_audit_far_future() -> Instant {
560    Instant::now()
561        .checked_add(Duration::from_secs(3600))
562        .unwrap_or_else(Instant::now)
563}
564
565/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
566/// its in-flight slot and launch token from schedule time until the jitter
567/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
568/// only if the authoritative post-jitter answerability + cooldown checks pass at
569/// promotion, so a cancelled reservation leaves NO suppression behind.
570struct FirstAuditReservation {
571    event: MonetizedPinEvent,
572    ready_at: Instant,
573    inflight: FirstAuditInflightSlot,
574}
575
576/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
577/// pending queue, the dedup set, the launch limiter, the alternating lane, and
578/// the single outstanding reservation. All mutation is single-threaded in the
579/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
580/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
581/// state machine is unit-testable with injected clocks.
582struct FirstAuditScheduler {
583    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
584    /// (a real send), never at reservation, so a cancelled reservation can be
585    /// re-nominated.
586    first_audited: LruCache<[u8; 32], ()>,
587    /// Highest-count-per-peer pending nominations not yet launched. Capped at
588    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
589    /// one effective answerability window); at capacity a uniformly RANDOM
590    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
591    /// of a specific entry can never be forced deterministically. One further
592    /// entry may be held in `reserved` outside this queue — a deliberate
593    /// one-entry guard slot, so total schedulable occupancy is at most
594    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
595    pending: LruCache<PeerId, MonetizedPinEvent>,
596    /// Token bucket + per-peer re-audit window.
597    limiter: FirstAuditLimiter,
598    /// The single outstanding reservation (E′ serializes reservations so the
599    /// per-launch lane alternation is preserved and at most one jitter timer is
600    /// live).
601    reserved: Option<FirstAuditReservation>,
602    /// Alternating launch lane, flipped on every PROMOTION (real launch).
603    oldest_first_lane: bool,
604    /// The local node's own peer ID. A verified payment's quote list includes
605    /// the node's own quote, so the verifier emits a monetized-pin event for
606    /// the local peer on every payment it verifies. The node cannot
607    /// network-audit itself (there is no dialable address for the local peer,
608    /// so the challenge fails instantly and is miscounted as a timeout), while
609    /// any other payee that verifies the same payment schedules its own first
610    /// audit of this node's pin — a self-dial adds no coverage either way.
611    /// Such an event is dropped at ingress: never queued, and hence never
612    /// launched nor marked first-audited.
613    self_peer: PeerId,
614    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
615    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
616    /// production seeds from OS entropy at construction.
617    rng: StdRng,
618}
619
620impl FirstAuditScheduler {
621    fn new(now: Instant, self_peer: PeerId) -> Self {
622        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
623        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
624        Self {
625            first_audited: LruCache::new(dedup_cap),
626            pending: LruCache::new(pending_cap),
627            limiter: FirstAuditLimiter::new(now),
628            reserved: None,
629            oldest_first_lane: false,
630            self_peer,
631            rng: StdRng::from_entropy(),
632        }
633    }
634
635    /// Observability getter: used by the scheduler summary log and unit tests,
636    /// both absent from a release `--no-default-features` build, so it is dead
637    /// only in that configuration.
638    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
639    fn pending_len(&self) -> usize {
640        self.pending.len()
641    }
642
643    /// Observability getter (see [`Self::pending_len`]).
644    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
645    fn tokens(&self) -> u32 {
646        self.limiter.tokens
647    }
648
649    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
650    /// signed quote timestamp of the oldest pin still awaiting a first audit:
651    /// how close the longest-waiting pending pin is to aging out of the
652    /// answerability window. A value climbing toward the window means pending
653    /// work is expiring unaudited instead of launching; a small, steady value
654    /// means the queue is draining promptly. Returns `0` when `pending` is empty
655    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
656    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
657    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
658        self.pending
659            .iter()
660            .map(|(_, e)| e.quote_ts)
661            .min()
662            .and_then(|oldest| now.duration_since(oldest).ok())
663            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
664    }
665
666    /// Drop every pending nomination that has aged past the answerability
667    /// horizon. `try_reserve` collects expired entries only while it can scan —
668    /// under token starvation it returns at the budget gate first — so without
669    /// a periodic sweep dead entries squat the capped pending queue (displacing
670    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
671    /// telemetry. Each removal is accounted as `outside_answerability_window`,
672    /// exactly like a scan-time expiry. Returns how many entries were dropped;
673    /// survivor recency is untouched.
674    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
675        let expired: Vec<PeerId> = self
676            .pending
677            .iter()
678            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
679            .map(|(peer, _)| *peer)
680            .collect();
681        for peer in &expired {
682            self.pending.pop(peer);
683        }
684        if !expired.is_empty() {
685            obs.outside_answerability_window.fetch_add(
686                u64::try_from(expired.len()).unwrap_or(u64::MAX),
687                Ordering::Relaxed,
688            );
689        }
690        expired.len()
691    }
692
693    fn has_reservation(&self) -> bool {
694        self.reserved.is_some()
695    }
696
697    /// Whether admitting `event` would displace a DIFFERENT peer's pending
698    /// entry: the queue is at capacity and `event.peer` has no incumbent to
699    /// coalesce into. The drainer checks this before enqueueing so pending
700    /// work gets a reservation opportunity BEFORE destructive overflow
701    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
702    /// of `pending`, freeing the slot without any eviction.
703    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
704        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
705    }
706
707    /// When the outstanding reservation becomes eligible for promotion.
708    fn reserved_ready_at(&self) -> Option<Instant> {
709        self.reserved.as_ref().map(|r| r.ready_at)
710    }
711
712    /// The peer of the outstanding reservation, if any.
713    fn reserved_peer(&self) -> Option<PeerId> {
714        self.reserved.as_ref().map(|r| r.event.peer)
715    }
716
717    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
718    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
719    /// if already first-audited; the window screen is bypassed for the currently
720    /// reserved peer (so a successor is retained across the reservation, never
721    /// window-dropped); otherwise window-screened. Coalescing is
722    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
723    /// displaces a higher-count pending pin. An incumbent that has aged past
724    /// the answerability horizon is dropped (and accounted as an expiry) before
725    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
726    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
727    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
728    /// displacement is accounted as `capacity_evicted` and stamps no
729    /// suppression, so a displaced peer's next nomination is judged like any
730    /// newcomer. The drainer additionally offers a reservation opportunity
731    /// via [`Self::would_displace`] before calling this on an overflowing
732    /// arrival.
733    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
734        if event.peer == self.self_peer {
735            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
736            return;
737        }
738        if self.first_audited.contains(&event.pin) {
739            obs.duplicates.fetch_add(1, Ordering::Relaxed);
740            return;
741        }
742        let reserved_peer = self.reserved_peer();
743        let is_reserved_peer = reserved_peer == Some(event.peer);
744        if !is_reserved_peer
745            && !self
746                .limiter
747                .window_allows(&event.peer, event.key_count, Instant::now())
748        {
749            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
750            return;
751        }
752        // A pending incumbent past the answerability horizon can never launch,
753        // yet its (possibly higher) key count would still win the coalesce
754        // against a live incoming — e.g. a fresh post-prune lower-count pin —
755        // and under token starvation no reserve scan runs to collect it. Drop
756        // it first so the incoming is judged on its own merits.
757        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
758            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
759        });
760        if stale_incumbent {
761            self.pending.pop(&event.peer);
762            obs.outside_answerability_window
763                .fetch_add(1, Ordering::Relaxed);
764        }
765        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
766        // tie.
767        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
768            FirstAuditQueueOutcome::Queued => {
769                obs.queued.fetch_add(1, Ordering::Relaxed);
770            }
771            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
772                obs.coalesced.fetch_add(1, Ordering::Relaxed);
773            }
774            FirstAuditQueueOutcome::SuppressedLower => {
775                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
776            }
777            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
778                obs.queued.fetch_add(1, Ordering::Relaxed);
779                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
780            }
781        }
782    }
783
784    /// Attempt to create the single reservation from `pending` (E′ reserve).
785    /// Scans in the current lane order and reserves the FIRST eligible pin:
786    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
787    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
788    /// flip the lane — those happen only at promotion. Returns whether a
789    /// reservation was made. `cooldown` is a read-only snapshot (the
790    /// authoritative check-and-stamp is at promotion).
791    fn try_reserve(
792        &mut self,
793        mono_now: Instant,
794        inflight: u64,
795        jitter: Duration,
796        cooldown: &HashMap<PeerId, Instant>,
797        obs: &Arc<FirstAuditObservability>,
798    ) -> bool {
799        if self.reserved.is_some() || self.pending.is_empty() {
800            return false;
801        }
802        self.limiter.refill(mono_now);
803        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
804            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
805            return false;
806        }
807        // MRU->LRU order; reverse for the oldest-first lane so the preferred
808        // end is at the front.
809        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
810            .pending
811            .iter()
812            .enumerate()
813            .map(|(i, (p, e))| (i, *p, *e))
814            .collect();
815        self.pending.clear();
816        if self.oldest_first_lane {
817            ordered.reverse();
818        }
819        let mut chosen: Option<MonetizedPinEvent> = None;
820        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
821        for (idx, peer, event) in ordered {
822            if chosen.is_some() {
823                kept.push((idx, peer, event));
824                continue;
825            }
826            if self.first_audited.contains(&event.pin) {
827                obs.duplicates.fetch_add(1, Ordering::Relaxed);
828                continue; // drop: already audited
829            }
830            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
831                obs.outside_answerability_window
832                    .fetch_add(1, Ordering::Relaxed);
833                continue; // drop: cannot stay answerable through the jitter
834            }
835            // Window + budget + inflight. Tokens do not decrease during the
836            // scan (reserve happens after the loop) and `inflight` is fixed, so
837            // after the upfront budget gate `assess` never returns RateDeferred
838            // here; a defensive RateDeferred keeps the pin.
839            match self
840                .limiter
841                .assess(&peer, event.key_count, mono_now, inflight)
842            {
843                LimiterVerdict::WindowDeduped => {
844                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
845                    continue; // drop: recently first-audited, no count jump
846                }
847                LimiterVerdict::RateDeferred => {
848                    kept.push((idx, peer, event));
849                    continue; // keep (defensive; unreachable after upfront gate)
850                }
851                LimiterVerdict::Admit => {}
852            }
853            if !cooldown_would_allow(cooldown, &peer, mono_now) {
854                obs.cooldown_deferred_attempts
855                    .fetch_add(1, Ordering::Relaxed);
856                kept.push((idx, peer, event));
857                continue; // keep: on shared cooldown, retry later
858            }
859            chosen = Some(event);
860        }
861        // Restore relative recency (oldest re-put first -> newest stays MRU).
862        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
863        for (_, peer, event) in kept {
864            self.pending.put(peer, event);
865        }
866        let Some(event) = chosen else {
867            return false;
868        };
869        self.limiter.reserve_token();
870        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
871        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
872        self.reserved = Some(FirstAuditReservation {
873            event,
874            ready_at,
875            inflight: inflight_slot,
876        });
877        true
878    }
879
880    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
881    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
882        if self
883            .reserved
884            .as_ref()
885            .is_some_and(|r| mono_now >= r.ready_at)
886        {
887            self.reserved.take()
888        } else {
889            None
890        }
891    }
892
893    /// Authoritative promotion of a due reservation (E′). The caller holds the
894    /// shared cooldown write lock and passes the real send-time `wall_now` and
895    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
896    /// launch, or `None` when the launch was cancelled (answerability lapsed
897    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
898    /// On both `None` paths the token is refunded, the in-flight slot released,
899    /// and NO suppression is recorded.
900    ///
901    /// Known operational residual: suppression is stamped here, at promotion,
902    /// while the wire challenge is sent by the detached task the caller spawns
903    /// with the returned event. A task-start or encoding failure between the
904    /// two therefore leaves a stamped-but-unsent window. No remote input can
905    /// force that failure (it requires local task-spawn/alloc failure), so it
906    /// is accepted rather than closed; closing it would require stamping from
907    /// inside the spawned task and re-introduce the cancel-leaves-suppression
908    /// race this design exists to prevent.
909    fn resolve(
910        &mut self,
911        reservation: FirstAuditReservation,
912        wall_now: SystemTime,
913        mono_now: Instant,
914        cooldown: &mut HashMap<PeerId, Instant>,
915        obs: &Arc<FirstAuditObservability>,
916    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
917        let FirstAuditReservation {
918            event, inflight, ..
919        } = reservation;
920        // Authoritative answerability at the REAL send time.
921        if !quote_within_audit_window(event.quote_ts, wall_now) {
922            self.limiter.refund_token();
923            obs.outside_answerability_window
924                .fetch_add(1, Ordering::Relaxed);
925            drop(inflight);
926            return None; // cancelled; nothing stamped, nothing to roll back
927        }
928        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
929        // concurrent gossip audit requeues the reserved event through the SAME
930        // security-aware coalescing: the reserved event is OLDER than any
931        // same-peer successor (`incoming_is_newer = false`), so a higher-count
932        // reserved event still wins over a lower-count successor (the inflated
933        // pin must be audited), while an equal/higher successor is preserved.
934        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
935            self.limiter.refund_token();
936            obs.cooldown_deferred_attempts
937                .fetch_add(1, Ordering::Relaxed);
938            drop(inflight);
939            // Account for the requeue outcome (the nomination itself was already
940            // counted at ingress, so `queued` is not re-incremented): a capacity
941            // eviction of a DIFFERENT peer and a suppressed reserved event are
942            // both observable per the ADR funnel.
943            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
944                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
945                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
946                }
947                FirstAuditQueueOutcome::SuppressedLower => {
948                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
949                }
950                FirstAuditQueueOutcome::Queued
951                | FirstAuditQueueOutcome::Coalesced
952                | FirstAuditQueueOutcome::RetainedOnTie => {}
953            }
954            return None;
955        }
956        // Promote: stamp durable suppression, flip the lane, count the launch.
957        self.limiter.promote(event.peer, event.key_count, mono_now);
958        self.first_audited.put(event.pin, ());
959        self.oldest_first_lane = !self.oldest_first_lane;
960        obs.launched.fetch_add(1, Ordering::Relaxed);
961        Some((event, inflight))
962    }
963}
964
965// ---------------------------------------------------------------------------
966// Constants
967// ---------------------------------------------------------------------------
968
969/// Prefix used by saorsa-core's request-response mechanism.
970const RR_PREFIX: &str = "/rr/";
971
972/// Bounded handoff from the P2P broadcast receiver to serial non-audit
973/// replication processing.
974///
975/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
976/// bulk/non-audit messages here. If this fills, the message is **dropped** —
977/// `start_message_handler` must never block on a full queue, because a stalled
978/// receiver laps the P2P broadcast ring and silently loses messages it never
979/// observed. Every serial-lane class has protocol recovery, so a drop costs a
980/// retry rather than the message.
981///
982/// This bounds a message COUNT, but a queued item is an owned decoded message
983/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
984/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
985/// for: the lane carries small requests and challenges alongside
986/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
987/// right for both. Responses never reach here — `replication_payload_from_event`
988/// filters them out and their requesters correlate them. ADR-0005 decision 12
989/// records the trade and why byte accounting is the correct eventual fix.
990const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
991
992/// Maximum fresh-replication offers processed concurrently, away from the
993/// serial non-audit loop.
994///
995/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
996/// write. Four workers keep that latency off the responder dispatch path while
997/// keeping concurrent EVM/storage pressure small and predictable.
998const FRESH_OFFER_WORKER_LIMIT: usize = 4;
999
1000/// Maximum fresh offers admitted at once, counting both those running on a
1001/// worker and those queued for one.
1002///
1003/// An admitted offer holds its payload until it completes, so this bounds
1004/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1005/// Offers past the bound are refused rather than queued or handled inline —
1006/// handling one on the message loop stalls every other non-audit message behind
1007/// a payment verification and a multi-MiB write. A refusal is not free: the
1008/// sender does not read it, so it resurfaces as a missing key at the delayed
1009/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1010/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1011/// bound is sized to make refusal rare rather than cheap.
1012const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1013
1014/// Distinct payment proofs queued for one fresh-offer key.
1015///
1016/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1017/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1018/// chunk out to the close group, so a receiver sees the same key from about that
1019/// many senders. They differ only in their proof — the bytes are provably
1020/// identical, since `fresh_offer_structural_rejection` has confirmed
1021/// `key == BLAKE3(data)` before any of them is queued.
1022///
1023/// Sizing the queue to the number of legitimate senders is what lets a failing
1024/// proof fall through to the next one instead of costing the node the record.
1025///
1026/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1027/// admitted, and a proof the handler has popped has spent its slot rather than
1028/// returned it. That distinction is what bounds the work an attacker can buy —
1029/// at most this many on-chain verifications per key, after which the entry
1030/// refuses everyone until it closes. Gating on the queue's instantaneous length
1031/// instead would let a stream of distinct sources refill each popped slot and
1032/// run unbounded sequential verifications while holding one of the four worker
1033/// slots. One attempt per source additionally means a single peer can only ever
1034/// consume one of these.
1035const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1036
1037/// Fresh-offer slots kept reachable by sources that hold none.
1038///
1039/// The property worth guaranteeing is that one peer cannot *starve* others, not
1040/// that any peer is held to a small quota. Expressing the bound as a reserve
1041/// rather than a quota is what keeps those two apart.
1042const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1043
1044/// Maximum fresh offers admitted from one source peer.
1045///
1046/// Without a per-source bound, one peer can hold every slot in the global pool
1047/// and every honest offer arriving in that window is refused — and because a
1048/// refusal is later read as absence by the sender's delayed possession check,
1049/// those refusals land as audit-severity trust penalties on the *refuser*.
1050/// That makes an unbounded global pool a targeted eviction primitive.
1051///
1052/// The bound is deliberately far looser than the other responder classes'
1053/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1054/// the opposite shape. Those are request/response: a requester needs only a
1055/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1056/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1057/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1058/// for request/response traffic therefore binds on completely legitimate
1059/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1060/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1061/// ceiling and none to the global pool.
1062///
1063/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1064/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1065/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1066// The cast is from a compile-time constant difference of two small literals
1067// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1068// relationship visible in the code rather than only in a test.
1069#[allow(clippy::cast_possible_truncation)]
1070const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1071    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1072
1073/// Maximum paid-list notifications served concurrently.
1074///
1075/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1076/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1077/// Two workers keep cross-peer progress without multiplying concurrent EVM
1078/// and DHT lookup pressure.
1079const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1080
1081/// Maximum paid-list notifications admitted across workers and their waiters.
1082///
1083/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1084/// is one-way: the protocol defines no response and the sender never retries,
1085/// so a refused notify is information permanently lost to this node until a
1086/// later verification cycle happens to re-derive the key's paid status from a
1087/// paid-list quorum. A tight admission bound therefore does not shed load, it
1088/// discards durable state — which is why the class's real protection is
1089/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1090/// is actually expensive, rather than this queue depth.
1091///
1092/// A client PUT fans one notify per key out to the whole paid close group, so
1093/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1094/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1095/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1096/// carry no chunk payload.
1097const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1098
1099/// Maximum admitted paid-list notifications from one source peer.
1100///
1101/// A quarter of the pool. One peer legitimately supplies a whole upload's
1102/// worth of notifies, so this must comfortably exceed a typical file's chunk
1103/// count in flight; it exists to stop a single source evicting every other
1104/// peer's durable paid-list evidence, not to ration ordinary traffic.
1105const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1106
1107/// Maximum fetch responses served concurrently.
1108///
1109/// Each successful response can upload a 4 MiB chunk. Matching
1110/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1111/// simultaneous chunk data, which avoids saturating typical home upload links.
1112const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1113
1114/// Maximum fetch requests admitted across workers and their bounded waiters.
1115///
1116/// Four worker waves absorb short bursts without retaining chunk bytes—the
1117/// request contains only a key—while the dequeue deadline sheds work before a
1118/// sustained flood can keep the node serving requests whose callers timed out.
1119const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1120
1121/// Maximum admitted fetch requests from one source peer.
1122///
1123/// Two requests let one peer pipeline useful reads while leaving at least one
1124/// of the three workers available to other peers under a single-source flood.
1125const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1126
1127/// Maximum verification batches served concurrently.
1128///
1129/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1130/// workers isolate that synchronous work from message dispatch without turning
1131/// large batches into an I/O fan-out throughput contest.
1132const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1133
1134/// Maximum verification batches admitted across workers and bounded waiters.
1135///
1136/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1137/// deadline prevents queued batches from consuming lookup capacity after their
1138/// requesters have stopped waiting.
1139const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1140
1141/// Maximum admitted verification batches from one source peer.
1142///
1143/// Senders already aggregate a peer's keys into one batch. One outstanding
1144/// batch therefore preserves useful work while reserving the other worker and
1145/// the bounded queue for different peers.
1146const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1147
1148/// Maximum neighbor-sync requests served concurrently across source peers.
1149///
1150/// Building a response scans local keys and performs DHT lookups, so two
1151/// workers allow cross-peer progress without multiplying that expensive scan
1152/// into broad network and storage contention.
1153const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1154
1155/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1156///
1157/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1158/// payloads bounded; expired waiters are shed before any key scan begins.
1159const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1160
1161/// Maximum admitted neighbor-sync requests from one source peer.
1162///
1163/// Sync history must be updated before repair proofs for the same peer. A
1164/// single slot preserves that ordering while independent peers remain parallel.
1165const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1166
1167/// Match an inbound topic against the replication protocol ids, in both the bare
1168/// gossip form and the `/rr/<id>` request-response form.
1169///
1170/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1171/// was the RR form. The matched id is carried into the handler so it can enforce
1172/// that subtree messages only arrive on the subtree id.
1173fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1174    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1175        if topic == id {
1176            return Some((id, false));
1177        }
1178        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1179            if rest == id {
1180                return Some((id, true));
1181            }
1182        }
1183    }
1184    None
1185}
1186
1187/// Whether a decoded body belongs on the protocol id it arrived on:
1188/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1189/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1190///
1191/// The receive guard drops any mismatch (a cross-version or misrouted message);
1192/// sharing this one predicate between the guard and its regression test means a
1193/// change to the rule cannot pass the test unnoticed.
1194fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1195    protocol == response_protocol_for(body)
1196}
1197
1198/// The protocol id a body belongs on — the single source of truth for BOTH
1199/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1200/// response selector in `send_replication_response_checked`.
1201///
1202/// Sharing one function makes the subtree/core isolation symmetric.
1203fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1204    if body.is_subtree_audit() {
1205        SUBTREE_AUDIT_PROTOCOL_ID
1206    } else {
1207        REPLICATION_PROTOCOL_ID
1208    }
1209}
1210
1211fn fresh_offer_payment_context() -> VerificationContext {
1212    VerificationContext::FreshReplication
1213}
1214
1215fn paid_notify_payment_context() -> VerificationContext {
1216    VerificationContext::PaidListAdmission
1217}
1218
1219/// Boxed future type for in-flight fetch tasks.
1220type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1221
1222/// Fresh-offer keys currently being handled, each with the proofs still to try.
1223///
1224/// Concurrent duplicates are routine: a client PUT is confirmed by
1225/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1226/// commonly arrives from several senders at once. Collapsing them onto one
1227/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1228/// and an on-chain verification per copy.
1229///
1230/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1231/// refusing every later offer outright made the first arrival the only arrival:
1232/// if its proof failed, the record was lost even though a valid proof for the
1233/// same bytes was queued behind it, and the resulting absence was charged to
1234/// this node by the delayed possession check. So the entry holds the bytes once
1235/// and queues each sender's proof, and the handler works down that queue. A
1236/// later offer therefore costs a proof, not a payload — sound only because
1237/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1238/// every one of them before it is queued, which is what makes their bytes
1239/// provably identical.
1240///
1241/// Entries are exact keys rather than hash shards. A node only receives offers
1242/// for keys it is close to, so the accepted key set clusters tightly around its
1243/// own ID — any index derived from the key would land nearly every offer on one
1244/// shard and serialize unrelated keys behind each other. Exact keys keep them
1245/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1246/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1247///
1248/// The critical section is a map insert, pop, or remove and is never held across
1249/// an await, so this is a blocking mutex rather than an async one.
1250type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1251
1252/// One sender's unverified claim to have paid for a key already in flight.
1253///
1254/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1255/// content-address check ran before this attempt was queued.
1256struct FreshOfferAttempt {
1257    source: PeerId,
1258    proof_of_payment: Vec<u8>,
1259    request_id: u64,
1260    rr_message_id: Option<String>,
1261}
1262
1263/// Proofs still to try for one in-flight key, and who supplied them.
1264///
1265/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1266/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1267struct FreshOfferEntry {
1268    /// Untried proofs in arrival order. The handler holds the current one.
1269    pending: VecDeque<FreshOfferAttempt>,
1270    /// Sources already represented, so one peer cannot fill the queue alone.
1271    sources: HashSet<PeerId>,
1272    /// Proofs admitted over this entry's whole life, **never decremented**.
1273    ///
1274    /// The budget has to be spent by admissions rather than held by the queue.
1275    /// The handler pops a proof before verifying it, so gating on
1276    /// `pending.len()` would let a fresh source refill the slot that pop just
1277    /// freed, and a stream of distinct sources could then run unbounded
1278    /// sequential payment verifications while holding one of only four worker
1279    /// slots. Counting admissions makes the cap a lifetime budget instead.
1280    admitted: usize,
1281}
1282
1283/// How an arriving fresh offer joined the work already in flight for its key.
1284enum FreshOfferAdmission {
1285    /// Opened the entry. This offer's handler owns the key and drives every
1286    /// queued proof, including proofs that arrive later.
1287    Opened(Box<FreshOfferEntryGuard>),
1288    /// Merged into an entry another offer opened; its handler reaches this proof
1289    /// if the ones ahead of it fail.
1290    Joined,
1291    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1292    Full,
1293    /// This source already has a proof queued for this key.
1294    DuplicateSource,
1295}
1296
1297// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1298// `debug!`, which compiles to nothing without the feature.
1299#[cfg(feature = "logging")]
1300impl FreshOfferAdmission {
1301    /// Why the offer added nothing to the work already queued for its key.
1302    ///
1303    /// Local logging only — the wire reason stays uniform so a probing peer
1304    /// cannot tell a full queue from a repeat of its own proof.
1305    const fn surplus_reason(&self) -> &'static str {
1306        match self {
1307            Self::DuplicateSource => "this source already has a proof queued",
1308            Self::Full => "the key already holds its full complement of proofs",
1309            Self::Opened(_) | Self::Joined => "not surplus",
1310        }
1311    }
1312}
1313
1314/// RAII ownership of one in-flight fresh-offer key.
1315///
1316/// Clears the entry on drop, so an early return, an error, or a panic cannot
1317/// strand a key as permanently in flight. Also owns the single copy of the
1318/// offered bytes that every queued proof is tried against.
1319struct FreshOfferEntryGuard {
1320    in_flight: FreshOfferInFlight,
1321    key: XorName,
1322    /// The bytes every attempt for this key shares, held exactly once.
1323    data: Vec<u8>,
1324    /// Arrival of the offer that opened the entry.
1325    received_at: Instant,
1326    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1327    /// a *later* offer has since opened for the same key.
1328    holds_entry: bool,
1329}
1330
1331impl FreshOfferEntryGuard {
1332    /// Open an entry for this offer's key, or queue its proof behind the entry
1333    /// already open.
1334    ///
1335    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1336    /// on every other outcome they are dropped here rather than held for the
1337    /// lifetime of the entry.
1338    fn admit(
1339        in_flight: &FreshOfferInFlight,
1340        offer: protocol::FreshReplicationOffer,
1341        source: PeerId,
1342        request_id: u64,
1343        rr_message_id: Option<String>,
1344        received_at: Instant,
1345    ) -> FreshOfferAdmission {
1346        let key = offer.key;
1347        let attempt = FreshOfferAttempt {
1348            source,
1349            proof_of_payment: offer.proof_of_payment,
1350            request_id,
1351            rr_message_id,
1352        };
1353
1354        let mut in_flight_map = in_flight.lock();
1355        if let Some(entry) = in_flight_map.get_mut(&key) {
1356            if entry.sources.contains(&source) {
1357                return FreshOfferAdmission::DuplicateSource;
1358            }
1359            // Lifetime budget, not queue depth: a proof the handler has already
1360            // popped has spent its slot, not returned it.
1361            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1362                return FreshOfferAdmission::Full;
1363            }
1364            entry.admitted = entry.admitted.saturating_add(1);
1365            entry.sources.insert(source);
1366            entry.pending.push_back(attempt);
1367            return FreshOfferAdmission::Joined;
1368        }
1369
1370        let mut sources = HashSet::new();
1371        sources.insert(source);
1372        let mut pending = VecDeque::new();
1373        pending.push_back(attempt);
1374        in_flight_map.insert(
1375            key,
1376            FreshOfferEntry {
1377                pending,
1378                sources,
1379                admitted: 1,
1380            },
1381        );
1382        drop(in_flight_map);
1383        FreshOfferAdmission::Opened(Box::new(Self {
1384            in_flight: Arc::clone(in_flight),
1385            key,
1386            data: offer.data,
1387            received_at,
1388            holds_entry: true,
1389        }))
1390    }
1391
1392    /// The bytes every proof for this key is tried against.
1393    fn data(&self) -> &[u8] {
1394        &self.data
1395    }
1396
1397    /// When the first offer for this key arrived.
1398    fn received_at(&self) -> Instant {
1399        self.received_at
1400    }
1401
1402    /// Take the next untried proof, releasing the key when none remain.
1403    ///
1404    /// Popping and releasing happen under one lock so a proof arriving exactly
1405    /// as the queue empties is never silently discarded: it either lands in this
1406    /// entry and is returned here, or finds no entry and opens its own.
1407    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1408        let mut in_flight = self.in_flight.lock();
1409        let Some(entry) = in_flight.get_mut(&self.key) else {
1410            self.holds_entry = false;
1411            return None;
1412        };
1413        if let Some(attempt) = entry.pending.pop_front() {
1414            return Some(attempt);
1415        }
1416        in_flight.remove(&self.key);
1417        self.holds_entry = false;
1418        None
1419    }
1420
1421    /// Release the key and return the proofs that were never tried, so their
1422    /// senders can be told the outcome the key reached without them.
1423    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1424        let mut in_flight = self.in_flight.lock();
1425        self.holds_entry = false;
1426        in_flight
1427            .remove(&self.key)
1428            .map(|entry| entry.pending.into_iter().collect())
1429            .unwrap_or_default()
1430    }
1431}
1432
1433impl Drop for FreshOfferEntryGuard {
1434    fn drop(&mut self) {
1435        if self.holds_entry {
1436            self.in_flight.lock().remove(&self.key);
1437        }
1438    }
1439}
1440
1441/// Shared dependencies for one verification worker cycle.
1442struct VerificationCycleContext<'a> {
1443    p2p_node: &'a Arc<P2PNode>,
1444    paid_list: &'a Arc<PaidList>,
1445    storage: &'a Arc<LmdbStorage>,
1446    queues: &'a Arc<RwLock<ReplicationQueues>>,
1447    config: &'a ReplicationConfig,
1448    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1449    is_bootstrapping: &'a Arc<RwLock<bool>>,
1450    bootstrap_complete_notify: &'a Arc<Notify>,
1451    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1452    /// peer's Present claim to Unresolved unless they're a credited
1453    /// holder of the key (i.e. they recently passed a commitment-bound
1454    /// audit on it under their currently-credited commitment hash).
1455    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1456    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1457    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1458}
1459
1460/// Fetch worker polling interval in milliseconds.
1461const FETCH_WORKER_POLL_MS: u64 = 100;
1462
1463/// Verification worker polling interval in milliseconds.
1464const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1465
1466/// Verification cycle duration that is worth surfacing at info level.
1467const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1468
1469/// Standard trust event weight for per-operation success/failure signals.
1470///
1471/// Used for individual replication fetch outcomes, integrity check failures,
1472/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1473/// is reserved for confirmed audit failures.
1474const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1475/// Bound trust updates from one verification cycle. A malicious peer can
1476/// advertise thousands of bad singleton keys at once; a few independent
1477/// contradictions are enough for the trust engine without flooding it.
1478const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1479
1480/// Bootstrap drain check interval in seconds.
1481const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1482
1483/// Grace period `shutdown()` waits for each long-lived background task to
1484/// observe the cancellation token and terminate before aborting it.
1485///
1486/// Detached tasks are drained without a timeout because storage-capable work
1487/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1488/// if its async waiter is dropped.
1489const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1490
1491/// How often the responder rebuilds + rotates its storage commitment.
1492///
1493/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1494/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1495/// rotation-anchored: the responder stays answerable for the current
1496/// commitment plus every root it recently gossiped that is still in-window
1497/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1498/// its last emission (see `commitment_state`). So the rotation cadence does
1499/// not by itself bound answerability — a gossiped commitment stays
1500/// answerable across rotations until its gossip TTL lapses.
1501///
1502/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1503/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1504/// comfortably exceeds the gap between our rotation and the next gossip
1505/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1506/// Idle audit-skip pattern from being the common case.
1507///
1508/// Why not faster: the v12 pin is bound to a specific point-in-time
1509/// commitment, so rotation isn't security-critical for pin freshness —
1510/// only for keeping the committed key set current as the responder
1511/// writes new keys. 1 hour is plenty for that, and slow enough that
1512/// honest auditors mostly hit `current` or `previous` rather than the
1513/// "rotated past" case.
1514const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1515
1516/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1517/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1518/// durable well before it could matter to a restart, while the write-on-change
1519/// guard keeps idle nodes from needless disk writes.
1520const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1521
1522/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1523/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1524/// default that keeps log volume negligible.
1525const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1526
1527/// Cadence of the read-only bootstrap state snapshot used to separate drain
1528/// debt from cache and broader connectivity failures in fleet logs.
1529#[cfg(feature = "logging")]
1530const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1531
1532/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1533/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1534/// for first audit only if its SIGNED `quote_ts` lands in
1535/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1536/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1537/// badly-skewed or replayed quote) and one too old (the responder may have aged
1538/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1539/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1540/// within this margin); a legit first audit fires moments after payment
1541/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1542/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1543/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1544const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_secs(30 * 60);
1545
1546/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1547/// inside the answerability window relative to `now`, so first-auditing it cannot
1548/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1549/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1550/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1551/// All comparisons use `duration_since` (no `Duration` overflow).
1552fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1553    let too_future = quote_ts
1554        .duration_since(now)
1555        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1556    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1557    let too_old = now
1558        .duration_since(quote_ts)
1559        .is_ok_and(|age| age >= audit_cutoff);
1560    !(too_future || too_old)
1561}
1562
1563/// Minimum interval between commitment signature verifications for a
1564/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1565///
1566/// A sybil that bypasses the routing-table gate (e.g. by transient
1567/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1568/// per gossip message. This rate limit caps the verify-per-peer rate
1569/// at 1/min, which is comfortably above the legitimate gossip cadence
1570/// (the 10-20 min neighbor-sync round on each peer).
1571const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_secs(60);
1572
1573/// Hard cap on the size of `last_commitment_by_peer`.
1574///
1575/// Bounds the per-process memory cost of the auditor's per-peer
1576/// commitment cache. Each entry holds a `StorageCommitment`
1577/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1578/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1579/// realistic close-group neighborhood. When the cap is hit, one
1580/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1581/// order is unspecified; we do not track insertion order). The
1582/// `PeerRemoved` handler proactively drops entries as the DHT
1583/// detects departures, and `ingest_peer_commitment` only admits
1584/// commitments from peers currently in the routing table — together
1585/// the cap is the third line of defence against sybil/churn flooding.
1586const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1587
1588/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1589/// sized to the launch budget instead of the commitment cache.
1590///
1591/// The token bucket can launch at most one audit per
1592/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1593/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1594/// launchable for at most the effective answerability window
1595/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1596/// occupancy beyond `window / interval + burst` is work that cannot launch
1597/// before it expires, so admitting it only builds an aging backlog whose
1598/// telemetry measures the backlog instead of schedulable work.
1599///
1600/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1601/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1602/// rolling sample in which no arrival order lets an attacker deterministically
1603/// flush a chosen target; a fresh pin always enters the sample with an
1604/// unpredictable chance of near-immediate audit, whereas refusing at the door
1605/// would let a sustained payment flood guarantee that every later pin is never
1606/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1607/// ADR-0004 Amendment 4 for the eviction-cost math.
1608///
1609/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1610/// is usable only if the quote stays answerable through `a` plus the maximum
1611/// launch jitter and send slack, so the last usable refill is the largest
1612/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1613/// simulates the shipped predicate instant-by-instant and must agree.
1614#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1615const FIRST_AUDIT_PENDING_CAP: usize = {
1616    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1617        .as_secs()
1618        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1619        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1620        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1621    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1622    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1623    // if the launch interval is ever zeroed: a zero interval makes the budget
1624    // (and this cap) meaningless.
1625    let refills =
1626        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1627    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1628};
1629
1630// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1631// strictly tighter than the commitment-cache bound it replaced.
1632const _: () = {
1633    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1634    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1635};
1636
1637/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1638/// long-running bootstrap node cannot have the set grow without limit
1639/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1640/// the set comfortably outlives normal LRU churn but still caps the
1641/// blast radius of identity-rotation attacks. Once full we refuse new
1642/// inserts (no eviction) — keeps the historic set stable; new v12
1643/// peers above the cap are treated as legacy on rejoin, which matches
1644/// the behaviour before this set existed, not a security regression.
1645const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1646
1647// ---------------------------------------------------------------------------
1648// ReplicationEngine
1649// ---------------------------------------------------------------------------
1650
1651/// The replication engine manages all replication background tasks and state.
1652pub struct ReplicationEngine {
1653    /// Replication configuration (shared across spawned tasks).
1654    config: Arc<ReplicationConfig>,
1655    /// P2P networking node.
1656    p2p_node: Arc<P2PNode>,
1657    /// Local chunk storage.
1658    storage: Arc<LmdbStorage>,
1659    /// Persistent paid-for-list.
1660    paid_list: Arc<PaidList>,
1661    /// Payment verifier for `PoP` validation.
1662    payment_verifier: Arc<PaymentVerifier>,
1663    /// Replication pipeline queues.
1664    queues: Arc<RwLock<ReplicationQueues>>,
1665    /// Neighbor sync cycle state.
1666    sync_state: Arc<RwLock<NeighborSyncState>>,
1667    /// Per-peer sync history (for `RepairOpportunity`).
1668    ///
1669    /// This map grows with peer churn and is intentionally unbounded: entries
1670    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1671    /// naturally bounded by the routing table's k-bucket capacity.
1672    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1673    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1674    ///
1675    /// Records when each peer was last audited so a burst of gossiped
1676    /// commitment changes cannot spawn back-to-back audits of the same peer.
1677    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1678    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1679    /// Gossip-private lottery attempt window (one roll per peer per window,
1680    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1681    /// ticket never stamps the shared map and thus never defers a monetized
1682    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1683    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1684    /// Completed local neighbor-sync cycle epoch for proof maturity.
1685    sync_cycle_epoch: Arc<RwLock<u64>>,
1686    /// Per-key repair proof tracking for audit eligibility.
1687    repair_proofs: Arc<RwLock<RepairProofs>>,
1688    /// Bootstrap state tracking.
1689    bootstrap_state: Arc<RwLock<BootstrapState>>,
1690    /// Whether this node is currently bootstrapping.
1691    is_bootstrapping: Arc<RwLock<bool>>,
1692    /// Trigger for early neighbor sync (signalled on topology changes).
1693    sync_trigger: Arc<Notify>,
1694    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1695    bootstrap_complete_notify: Arc<Notify>,
1696    /// Node identity (for signing storage commitments).
1697    ///
1698    /// Phase 3 of the v12 storage-bound audit design. The responder
1699    /// uses this to sign its periodically-built `StorageCommitment`.
1700    identity: Arc<NodeIdentity>,
1701    /// Responder-side commitment state (two-slot atomic rotation).
1702    ///
1703    /// Periodically rebuilt from the live LMDB key set; gossiped on
1704    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1705    /// commitment-bound audit handler.
1706    commitment_state: Arc<ResponderCommitmentState>,
1707    /// Path to the persisted responder retention snapshot
1708    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1709    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1710    /// removing audit grace safe (an unanswerable in-window pin is then provable
1711    /// misbehaviour, not an honest crash-restart).
1712    retention_path: PathBuf,
1713    /// Auditor-side per-peer commitment record (last known commitment +
1714    /// sticky `commitment_capable` flag).
1715    ///
1716    /// Populated whenever an inbound gossip carries a verified
1717    /// commitment from the sender. Used by `audit_tick` to snapshot
1718    /// `expected_commitment_hash` into outbound challenges, and by
1719    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1720    /// proof should be honoured. The sticky `commitment_capable` flag
1721    /// flips true on first successful ingest and never reverts (§2
1722    /// step 5).
1723    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1724    /// Sticky set of peer IDs we have EVER seen carrying a v12
1725    /// commitment, independent of whether their commitment bytes are
1726    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1727    /// closure consults this set to keep treating churned-out
1728    /// previously-v12 peers as v12-capable (rather than degrading them
1729    /// to "legacy" credit-unconditionally) when they re-appear on the
1730    /// network before their next gossip arrives. Bounded growth: even
1731    /// at one million peers seen over the node's lifetime, the set is
1732    /// 32 MB.
1733    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1734    /// Auditor-side holder-eligibility cache (v12 §6).
1735    ///
1736    /// Recorded on successful commitment-bound audit; read by future
1737    /// quorum / paid-list eligibility checks (phase-3 stretch).
1738    recent_provers: Arc<RwLock<RecentProvers>>,
1739    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1740    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1741    /// failure) so a peer we've never successfully verified can't burn
1742    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1743    /// Lives separately from `last_commitment_by_peer` because that
1744    /// map's records only exist after a successful verify.
1745    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1746    /// Limits concurrent outbound replication sends to prevent bandwidth
1747    /// saturation on home broadband connections.
1748    send_semaphore: Arc<Semaphore>,
1749    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1750    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1751    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1752    /// message loop so disk
1753    /// reads don't block replication; the semaphore restores a global
1754    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1755    /// / multi-MiB byte serves.
1756    audit_responder_semaphore: Arc<Semaphore>,
1757    /// Per-source in-flight audit-responder counts, capped at
1758    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1759    /// flood-fair: one peer spamming challenges could occupy every slot and
1760    /// starve honest auditors, whose dropped challenges then convert to
1761    /// audit timeouts against HONEST peers (codex-r2 A). This
1762    /// per-peer cap guarantees no single source can hold more than its share,
1763    /// so a flood self-throttles without denying service to everyone else.
1764    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1765    /// Windowed per-origin capacity and processing-time telemetry for every
1766    /// request sharing the audit responder pool.
1767    audit_responder_metrics: Arc<AuditResponderMetrics>,
1768    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1769    ///
1770    /// Responsible-chunk audits, prune confirmations, and possession checks
1771    /// all use this before sending so local bursts wait instead of breaching
1772    /// the responder's deployed per-source admission cap.
1773    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1774    /// Worker permits for bandwidth-bound fetch responses.
1775    fetch_responder_worker_semaphore: Arc<Semaphore>,
1776    /// Admission permits bounding fetch workers and queued waiters together.
1777    fetch_responder_admission_semaphore: Arc<Semaphore>,
1778    /// Per-source fetch responder counts for flood-fair admission.
1779    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1780    /// Worker permits for lookup-heavy verification batches.
1781    verification_responder_worker_semaphore: Arc<Semaphore>,
1782    /// Admission permits bounding verification workers and queued waiters.
1783    verification_responder_admission_semaphore: Arc<Semaphore>,
1784    /// Per-source verification responder counts for flood-fair admission.
1785    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1786    /// Worker permits for expensive inbound neighbor-sync requests.
1787    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1788    /// Admission permits bounding sync workers and queued waiters together.
1789    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1790    /// Per-source sync responder counts; capped at one to preserve ordering.
1791    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1792    /// Bounded worker permits for expensive fresh-offer handling.
1793    fresh_offer_worker_semaphore: Arc<Semaphore>,
1794    /// Admission permits bounding offers running on a worker or queued for one.
1795    fresh_offer_admission_semaphore: Arc<Semaphore>,
1796    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1797    /// and turn honest senders' refusals into trust penalties on this node.
1798    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1799    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1800    /// duplicates collapse onto one verification and one write.
1801    fresh_offer_in_flight: FreshOfferInFlight,
1802    /// Bounded worker permits for paid-list notification proof verification.
1803    paid_notify_worker_semaphore: Arc<Semaphore>,
1804    /// Admission permits bounding notifies on a worker or queued for one.
1805    paid_notify_admission_semaphore: Arc<Semaphore>,
1806    /// Per-source paid-notify counts for flood-fair admission.
1807    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1808    /// Resource controls for the HEAVY subtree-audit round 1: its own
1809    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1810    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1811    /// sessions binding a slice challenge to a matching round 1.
1812    subtree_round1: SubtreeRound1Limiter,
1813    /// Receiver for fresh-write events from the chunk PUT handler.
1814    ///
1815    /// When present, `start()` spawns a drainer task that calls
1816    /// `replicate_fresh` for each event.
1817    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1818    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1819    /// drainer pushes the responsible close-group peers here after each fresh
1820    /// replication; the possession-check scheduler drains the paired receiver.
1821    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1822    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1823    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1824    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1825    /// for a deterministic first audit. The matching receiver is drained by
1826    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1827    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1828    /// like launches; a dropped nomination is penalty-free — the peer's
1829    /// gossiped commitments stay lottery-covered and its next settled payment
1830    /// re-nominates the paid pin.
1831    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1832    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1833    /// `start_first_audit_drainer`.
1834    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1835    /// Counters shared with the first-audit drainer task, so the scheduler's
1836    /// decisions (queued / launched / self-target skipped / outcome) stay
1837    /// observable from the engine after the drainer takes the receiver.
1838    first_audit_observability: Arc<FirstAuditObservability>,
1839    /// Shutdown token.
1840    shutdown: CancellationToken,
1841    /// Background task handles.
1842    task_handles: Vec<JoinHandle<()>>,
1843    /// Tracks detached, short-lived work spawned by background producers.
1844    ///
1845    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1846    /// tasks, and delayed possession checks may retain storage or P2P state
1847    /// after their producer exits, so shutdown drains them before those
1848    /// resources may be reopened.
1849    detached_task_tracker: TaskTracker,
1850}
1851
1852impl ReplicationEngine {
1853    /// Create a new replication engine.
1854    ///
1855    /// # Errors
1856    ///
1857    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1858    /// or if the configuration fails validation.
1859    #[allow(clippy::too_many_arguments)]
1860    pub async fn new(
1861        config: ReplicationConfig,
1862        p2p_node: Arc<P2PNode>,
1863        storage: Arc<LmdbStorage>,
1864        payment_verifier: Arc<PaymentVerifier>,
1865        identity: Arc<NodeIdentity>,
1866        root_dir: &Path,
1867        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1868        shutdown: CancellationToken,
1869    ) -> Result<Self> {
1870        config.validate().map_err(Error::Config)?;
1871
1872        let paid_list = Arc::new(
1873            PaidList::new(root_dir)
1874                .await
1875                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1876        );
1877
1878        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1879        let config = Arc::new(config);
1880        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1881
1882        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1883        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1884        // now capacity-limited — ingress queue here, pending set (LRU), and
1885        // launch rate (token bucket).
1886        let (monetized_pin_tx, monetized_pin_rx) =
1887            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1888
1889        let engine = Self {
1890            config: Arc::clone(&config),
1891            p2p_node,
1892            storage,
1893            paid_list,
1894            payment_verifier,
1895            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1896            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1897            sync_history: Arc::new(RwLock::new(HashMap::new())),
1898            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1899            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1900            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1901            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1902            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1903            is_bootstrapping: Arc::new(RwLock::new(true)),
1904            sync_trigger: Arc::new(Notify::new()),
1905            bootstrap_complete_notify: Arc::new(Notify::new()),
1906            identity,
1907            commitment_state: Arc::new(ResponderCommitmentState::new()),
1908            retention_path: root_dir.join("commitment_retention.bin"),
1909            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1910            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1911            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1912            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1913            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1914            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1915            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1916            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1917            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1918            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1919                FETCH_RESPONDER_WORKER_LIMIT,
1920            )),
1921            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1922                FETCH_RESPONDER_MAX_OUTSTANDING,
1923            )),
1924            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1925            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1926                VERIFICATION_RESPONDER_WORKER_LIMIT,
1927            )),
1928            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1929                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1930            )),
1931            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1932            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1933                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1934            )),
1935            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1936                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1937            )),
1938            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1939            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1940            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1941            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1942            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1943            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1944            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1945            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1946            subtree_round1: SubtreeRound1Limiter::new(
1947                config.subtree_round1_responder_cooldown,
1948                config.subtree_round1_max_concurrent,
1949            ),
1950            fresh_write_rx: Some(fresh_write_rx),
1951            possession_check_tx,
1952            possession_check_rx: Some(possession_check_rx),
1953            monetized_pin_tx,
1954            monetized_pin_rx: Some(monetized_pin_rx),
1955            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1956            shutdown,
1957            task_handles: Vec::new(),
1958            detached_task_tracker: TaskTracker::new(),
1959        };
1960        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1961        // spawns, so an honest restarted node is answerable for its pre-restart
1962        // pins from the first audit it serves, and the persist loop never races
1963        // an empty snapshot over the good on-disk file.
1964        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1965        Ok(engine)
1966    }
1967
1968    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1969    /// (commitments that backed a payment) for a first audit. Cloneable; the
1970    /// engine drains the matching receiver. Bounded: senders must `try_send`
1971    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1972    #[must_use]
1973    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1974        self.monetized_pin_tx.clone()
1975    }
1976
1977    /// Get a reference to the `PaidList`.
1978    #[must_use]
1979    pub fn paid_list(&self) -> &Arc<PaidList> {
1980        &self.paid_list
1981    }
1982
1983    /// Get a reference to the responder's commitment state. Used by audit
1984    /// handlers to look up commitments by hash; used by the rotation tick
1985    /// to install fresh ones.
1986    #[must_use]
1987    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1988        &self.commitment_state
1989    }
1990
1991    /// Get a reference to the auditor's last-commitment-by-peer table.
1992    #[must_use]
1993    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
1994        &self.last_commitment_by_peer
1995    }
1996
1997    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
1998    /// will be read by quorum / paid-list eligibility checks.
1999    #[must_use]
2000    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2001        &self.recent_provers
2002    }
2003
2004    /// Test-only: rebuild + rotate this node's storage commitment now over its
2005    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2006    /// just stored without waiting for the rotation cadence.
2007    ///
2008    /// # Errors
2009    ///
2010    /// Propagates any error from reading the local key set or building/signing
2011    /// the commitment.
2012    #[cfg(any(test, feature = "test-utils"))]
2013    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2014        rebuild_and_rotate_commitment(
2015            &self.storage,
2016            &self.identity,
2017            &self.commitment_state,
2018            &self.p2p_node,
2019            &self.config,
2020        )
2021        .await
2022    }
2023
2024    /// Test-only: directly seed this node's cached commitment for `peer`,
2025    /// simulating "we received `peer`'s gossiped commitment" without depending
2026    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2027    /// peer's commitment deterministically.
2028    #[cfg(any(feature = "test-utils", test))]
2029    pub async fn inject_peer_commitment_for_test(
2030        &self,
2031        peer: &PeerId,
2032        commitment: StorageCommitment,
2033    ) {
2034        let now = Instant::now();
2035        self.last_commitment_by_peer
2036            .write()
2037            .await
2038            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2039        self.ever_capable_peers.write().await.insert(*peer);
2040    }
2041
2042    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2043    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2044    /// window and clears any shared cooldown stamped by an earlier gossip
2045    /// launch. The locks follow the production gossip-audit lock order.
2046    #[cfg(any(test, feature = "test-utils"))]
2047    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2048        let now = Instant::now();
2049        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2050        let mut launched = self.audit_on_gossip_cooldown.write().await;
2051        lottery_attempts.insert(*peer, now);
2052        launched.remove(peer);
2053    }
2054
2055    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2056    /// commitment this node has cached for it (from gossip), over the live wire.
2057    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2058    /// in a real two-node setting without waiting for the gossip cadence.
2059    ///
2060    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2061    /// peer yet (gossip hasn't reached us). Gated to test builds.
2062    #[cfg(any(test, feature = "test-utils"))]
2063    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2064        let target = {
2065            let map = self.last_commitment_by_peer.read().await;
2066            map.get(peer)
2067                .and_then(PeerCommitmentRecord::last_commitment)
2068                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2069        };
2070        let Some((pin, key_count)) = target else {
2071            return audit::AuditTickResult::Idle;
2072        };
2073        let credit = storage_commitment_audit::AuditCredit {
2074            recent_provers: &self.recent_provers,
2075        };
2076        storage_commitment_audit::run_subtree_audit(
2077            &self.p2p_node,
2078            &self.config,
2079            peer,
2080            pin,
2081            key_count,
2082            Some(&credit),
2083        )
2084        .await
2085    }
2086
2087    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2088    /// tests assert what the live drainer decided for an injected
2089    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2090    #[cfg(any(test, feature = "test-utils"))]
2091    #[must_use]
2092    pub fn first_audit_stats(&self) -> FirstAuditStats {
2093        let o = &self.first_audit_observability;
2094        FirstAuditStats {
2095            received: o.received.load(Ordering::Relaxed),
2096            queued: o.queued.load(Ordering::Relaxed),
2097            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2098            launched: o.launched.load(Ordering::Relaxed),
2099            passed: o.passed.load(Ordering::Relaxed),
2100            timed_out: o.timed_out.load(Ordering::Relaxed),
2101            failed: o.failed.load(Ordering::Relaxed),
2102        }
2103    }
2104
2105    /// Test-only: run the possession check immediately for `key` against
2106    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2107    ///
2108    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2109    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2110    /// deterministically without waiting for the scheduled check.
2111    #[cfg(any(test, feature = "test-utils"))]
2112    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2113        possession::run_possession_check(
2114            key,
2115            peers,
2116            &self.p2p_node,
2117            &self.storage,
2118            &self.config,
2119            &self.sync_state,
2120            &self.audit_challenge_coordinator,
2121            &self.shutdown,
2122        )
2123        .await;
2124    }
2125
2126    /// Test-only: place `key` directly into the fetch queue as though a
2127    /// verification cycle had just promoted it, with `sources` as its
2128    /// verified holders. Returns whether the key was enqueued.
2129    ///
2130    /// Bypasses admission, verification, and the promotion-time
2131    /// responsibility pre-filter, modelling a promotion decision that has
2132    /// since gone stale (topology churn between promotion and download).
2133    /// The only guard left standing is the per-attempt recheck inside
2134    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2135    /// exercise.
2136    #[cfg(any(test, feature = "test-utils"))]
2137    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2138        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2139        self.queues
2140            .write()
2141            .await
2142            .enqueue_fetch(key, distance, sources)
2143    }
2144
2145    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2146    /// (pending verification, fetch queue, or in-flight fetch).
2147    #[cfg(any(test, feature = "test-utils"))]
2148    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2149        self.queues.read().await.contains_key(key)
2150    }
2151
2152    /// Test-only: place `key` into pending verification as though `hinter` had
2153    /// just advertised it with a replica hint. Returns whether it was admitted.
2154    ///
2155    /// Enters the pipeline one stage earlier than
2156    /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2157    /// decides about the key is observable.
2158    #[cfg(any(test, feature = "test-utils"))]
2159    pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2160        let now = Instant::now();
2161        let entry = VerificationEntry {
2162            state: VerificationState::PendingVerify,
2163            verified_sources: Vec::new(),
2164            tried_sources: HashSet::new(),
2165            created_at: now,
2166            next_verify_at: now,
2167            hint_sources: HashSet::from([hinter]),
2168            replica_hint_sources: HashSet::from([hinter]),
2169            unresolved_retries: 0,
2170            no_holder_reported: false,
2171        };
2172        self.queues
2173            .write()
2174            .await
2175            .add_pending_verify(key, entry)
2176            .admitted()
2177    }
2178
2179    /// Test-only: how far ahead `key`'s next verification round is scheduled,
2180    /// or `None` when the key is not pending verification.
2181    #[cfg(any(test, feature = "test-utils"))]
2182    pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2183        self.queues.read().await.get_pending(key).map(|entry| {
2184            entry
2185                .next_verify_at
2186                .saturating_duration_since(Instant::now())
2187        })
2188    }
2189
2190    /// Start all background tasks.
2191    ///
2192    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2193    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2194    /// missed by the bootstrap-sync gate.
2195    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2196        if !self.task_handles.is_empty() {
2197            error!("ReplicationEngine::start() called while already running — ignoring");
2198            return;
2199        }
2200        info!("Starting replication engine");
2201
2202        self.start_message_handler();
2203        self.start_neighbor_sync_loop();
2204        self.start_self_lookup_loop();
2205        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2206        // chunks they SHOULD store (responsibility + prior hint).
2207        self.start_audit_loop();
2208        // Audit #1 (storage-commitment) is gossip-triggered in the message
2209        // handler when a peer's commitment is ingested, not on a periodic tick.
2210        self.start_commitment_rotation_loop();
2211        self.start_retention_persist_loop();
2212        self.start_fetch_worker();
2213        self.start_verification_worker();
2214        self.start_bootstrap_sync(dht_events);
2215        self.start_fresh_write_drainer();
2216        self.start_possession_check_scheduler();
2217        // ADR-0004: deterministic first audit of commitments that backed a
2218        // payment (surfaced by the verifier cross-check).
2219        self.start_first_audit_drainer();
2220        // V2-623: periodic cumulative per-variant traffic accounting.
2221        self.start_traffic_summary_loop();
2222        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2223        #[cfg(feature = "logging")]
2224        self.start_bootstrap_state_snapshot_loop();
2225        #[cfg(feature = "logging")]
2226        self.start_audit_responder_summary_loop();
2227
2228        info!(
2229            "Replication engine started with {} background tasks",
2230            self.task_handles.len()
2231        );
2232    }
2233
2234    /// Returns `true` if the node is still in the replication bootstrap phase.
2235    ///
2236    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2237    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2238    pub async fn is_bootstrapping(&self) -> bool {
2239        *self.is_bootstrapping.read().await
2240    }
2241
2242    /// Wait until the replication bootstrap phase completes.
2243    ///
2244    /// Returns immediately if bootstrap has already completed. Useful for
2245    /// readiness probes, health checks, and test harnesses that need the
2246    /// node to be fully operational before proceeding.
2247    ///
2248    /// Returns `true` if bootstrap completed within the timeout, `false`
2249    /// if the timeout elapsed first.
2250    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2251        // Register the notification future *before* checking the flag so that
2252        // a transition between the read and the await is not missed.
2253        let notified = self.bootstrap_complete_notify.notified();
2254        tokio::pin!(notified);
2255        notified.as_mut().enable();
2256
2257        if !*self.is_bootstrapping.read().await {
2258            return true;
2259        }
2260
2261        tokio::time::timeout(timeout, notified).await.is_ok()
2262    }
2263
2264    /// Cancel all background tasks and wait for them to terminate.
2265    ///
2266    /// This must be awaited before dropping the engine when the caller needs
2267    /// the `Arc<LmdbStorage>` references held by background tasks to be
2268    /// released (e.g. before reopening the same LMDB environment).
2269    ///
2270    /// When this returns, no engine-spawned task still holds
2271    /// `Arc<LmdbStorage>` or `Arc<PaidList>`, and no LMDB blocking operation
2272    /// (read or write, on either the chunk store or the paid-list
2273    /// environment) is still running.  Engine tasks race their work against
2274    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2275    /// LMDB transaction running detached, so this method additionally waits
2276    /// for both storage layers to go quiescent before returning.
2277    pub async fn shutdown(&mut self) {
2278        self.shutdown.cancel();
2279        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2280            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2281                Ok(Ok(())) => {}
2282                Ok(Err(e)) if e.is_cancelled() => {}
2283                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2284                Err(_) => {
2285                    warn!(
2286                        "Replication task {i} did not stop within {}s, aborting",
2287                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2288                    );
2289                    handle.abort();
2290                    // `abort` only requests cancellation. Await the handle so
2291                    // synchronous sections finish and the task drops every
2292                    // storage/P2P clone before we claim producer quiescence.
2293                    match handle.await {
2294                        Ok(()) => {}
2295                        Err(e) if e.is_cancelled() => {}
2296                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2297                    }
2298                }
2299            }
2300        }
2301
2302        // Close the responder worker pools. Detached tasks still queued for a
2303        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2304        // rather than waiting for a slot that will never free up — without
2305        // this, work admitted just before shutdown would queue behind the last
2306        // in-flight batch and hold the drain below open for its full duration.
2307        self.fresh_offer_worker_semaphore.close();
2308        self.paid_notify_worker_semaphore.close();
2309        self.fetch_responder_worker_semaphore.close();
2310        self.verification_responder_worker_semaphore.close();
2311        self.neighbor_sync_responder_worker_semaphore.close();
2312
2313        // All producers have stopped, so close and drain their detached work.
2314        // A started storage operation must run to completion: dropping an async
2315        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2316        // while an LMDB transaction still owns the environment.
2317        //
2318        // Deliberately unbounded: the LMDB contract requires every worker to
2319        // release its `Arc<LmdbStorage>` before the caller may reopen the
2320        // environment, and a timeout here could return with one still held.
2321        // What makes that safe is that every detached task is now guaranteed to
2322        // finish — the pools above are closed, stale work is shed at dequeue,
2323        // and the one genuinely unbounded await (payment verification) races
2324        // `self.shutdown` via `verify_payment_until_shutdown`.
2325        self.detached_task_tracker.close();
2326        self.detached_task_tracker.wait().await;
2327
2328        // Every producer is gone, but a select! racing the shutdown token may
2329        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2330        // (fetch `storage.put`, prune `storage.delete` /
2331        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2332        // detached blocking closure owns a cloned `Env`; wait for both
2333        // environments to go quiescent — bounded by one in-flight transaction
2334        // per op — so the caller may reopen them.
2335        self.storage.wait_idle().await;
2336        self.paid_list.wait_idle().await;
2337    }
2338
2339    /// Trigger an early neighbor sync round.
2340    ///
2341    /// Useful after topology changes (new nodes joining, network heal after
2342    /// partition) when the caller wants replication to converge faster than
2343    /// the regular 10-20 minute cadence.
2344    pub fn trigger_neighbor_sync(&self) {
2345        self.sync_trigger.notify_one();
2346    }
2347
2348    /// Execute fresh replication for a newly stored record, then schedule the
2349    /// delayed possession check for the responsible close-group peers
2350    /// (ADR-0003). The production PUT path schedules via the fresh-write
2351    /// drainer; this direct entry point schedules here so callers (and tests)
2352    /// that drive replication directly still get the possession check.
2353    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2354        let peers = fresh::replicate_fresh(
2355            key,
2356            data,
2357            proof_of_payment,
2358            &self.p2p_node,
2359            &self.paid_list,
2360            &self.config,
2361            &self.send_semaphore,
2362        )
2363        .await;
2364        if !peers.is_empty() {
2365            let _ = self
2366                .possession_check_tx
2367                .send(possession::PossessionCheckEvent { key: *key, peers });
2368        }
2369    }
2370
2371    // =======================================================================
2372    // Background task launchers
2373    // =======================================================================
2374
2375    /// Spawn a task that drains the fresh-write channel and triggers
2376    /// replication for each newly-stored chunk.
2377    fn start_fresh_write_drainer(&mut self) {
2378        let Some(mut rx) = self.fresh_write_rx.take() else {
2379            return;
2380        };
2381        let p2p = Arc::clone(&self.p2p_node);
2382        let paid_list = Arc::clone(&self.paid_list);
2383        let config = Arc::clone(&self.config);
2384        let send_semaphore = Arc::clone(&self.send_semaphore);
2385        let possession_tx = self.possession_check_tx.clone();
2386        let shutdown = self.shutdown.clone();
2387
2388        let handle = tokio::spawn(async move {
2389            loop {
2390                tokio::select! {
2391                    () = shutdown.cancelled() => break,
2392                    event = rx.recv() => {
2393                        let Some(event) = event else { break };
2394                        let peers = fresh::replicate_fresh(
2395                            &event.key,
2396                            &event.data,
2397                            &event.payment_proof,
2398                            &p2p,
2399                            &paid_list,
2400                            &config,
2401                            &send_semaphore,
2402                        )
2403                        .await;
2404                        // Schedule the delayed possession check (ADR-0003) for
2405                        // the responsible close-group peers. A closed receiver
2406                        // (engine shutting down) is ignored.
2407                        if !peers.is_empty() {
2408                            let _ = possession_tx.send(possession::PossessionCheckEvent {
2409                                key: event.key,
2410                                peers,
2411                            });
2412                        }
2413                    }
2414                }
2415            }
2416            debug!("Fresh-write drainer shut down");
2417        });
2418        self.task_handles.push(handle);
2419    }
2420
2421    /// Spawn the possession-check scheduler (ADR-0003).
2422    ///
2423    /// Drains scheduled possession-check events and, for each, waits a
2424    /// randomised 5-15 minute settle delay before probing every responsible
2425    /// peer for actual possession. A peer that fails to prove possession or does
2426    /// not answer is penalised at `AuditChallenge` severity.
2427    fn start_possession_check_scheduler(&mut self) {
2428        let Some(mut rx) = self.possession_check_rx.take() else {
2429            return;
2430        };
2431        let p2p = Arc::clone(&self.p2p_node);
2432        let storage = Arc::clone(&self.storage);
2433        let config = Arc::clone(&self.config);
2434        let sync_state = Arc::clone(&self.sync_state);
2435        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2436        let shutdown = self.shutdown.clone();
2437        let detached_task_tracker = self.detached_task_tracker.clone();
2438
2439        let handle = tokio::spawn(async move {
2440            loop {
2441                tokio::select! {
2442                    () = shutdown.cancelled() => break,
2443                    event = rx.recv() => {
2444                        let Some(event) = event else { break };
2445                        // Spawn a per-chunk delayed check so the drain loop
2446                        // keeps pace with the write rate. Each check sleeps the
2447                        // randomised settle delay, then probes every peer.
2448                        let p2p = Arc::clone(&p2p);
2449                        let storage = Arc::clone(&storage);
2450                        let config = Arc::clone(&config);
2451                        let sync_state = Arc::clone(&sync_state);
2452                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2453                        let shutdown = shutdown.clone();
2454                        let delay_min = config.possession_check_delay_min;
2455                        let delay_max = config.possession_check_delay_max;
2456                        detached_task_tracker.spawn(async move {
2457                            let delay = possession::random_delay(delay_min, delay_max);
2458                            // Race shutdown against the whole settle-then-probe
2459                            // sequence, not just the sleep. Once a check starts it
2460                            // may park on the per-target audit coordinator, which
2461                            // has no deadline of its own: with the settle delay
2462                            // inside the branch BODY the select is already resolved,
2463                            // so those waiters would drain only at the probe timeout
2464                            // (roughly `queued / per-target-limit` probes deep) while
2465                            // `detached_task_tracker.wait()` — deliberately unbounded
2466                            // for the LMDB contract — held shutdown open.
2467                            //
2468                            // Dropping this future mid-probe is safe and is the same
2469                            // shape the neighbor-sync round uses: a parked coordinator
2470                            // acquire releases its counted reference via
2471                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2472                            // covered by the storage-quiescence wait in `shutdown`.
2473                            tokio::select! {
2474                                () = shutdown.cancelled() => {}
2475                                () = async {
2476                                    tokio::time::sleep(delay).await;
2477                                    possession::run_possession_check(
2478                                        event.key,
2479                                        event.peers,
2480                                        &p2p,
2481                                        &storage,
2482                                        &config,
2483                                        &sync_state,
2484                                        &audit_challenge_coordinator,
2485                                        &shutdown,
2486                                    )
2487                                    .await;
2488                                } => {}
2489                            }
2490                        });
2491                    }
2492                }
2493            }
2494            debug!("Possession-check scheduler shut down");
2495        });
2496        self.task_handles.push(handle);
2497    }
2498
2499    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2500    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2501    /// as the gossip path, under the same per-peer cooldown and concurrency
2502    /// caps, but with the probability lottery BYPASSED (the lottery governs
2503    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2504    /// deterministic first audit; a peer minting fresh pins faster than the
2505    /// cooldown forfeits the older ones' coverage, never the newest's (the
2506    /// channel surfaces newest pins as they are monetized).
2507    #[allow(clippy::too_many_lines)]
2508    fn start_first_audit_drainer(&mut self) {
2509        let Some(mut rx) = self.monetized_pin_rx.take() else {
2510            return;
2511        };
2512        let gossip_audit = GossipAuditTrigger {
2513            p2p_node: Arc::clone(&self.p2p_node),
2514            config: Arc::clone(&self.config),
2515            recent_provers: Arc::clone(&self.recent_provers),
2516            sync_state: Arc::clone(&self.sync_state),
2517            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2518            detached_task_tracker: self.detached_task_tracker.clone(),
2519            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2520        };
2521        let shutdown = self.shutdown.clone();
2522        let observability = Arc::clone(&self.first_audit_observability);
2523        let self_peer = *self.p2p_node.peer_id();
2524
2525        let handle = tokio::spawn(async move {
2526            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2527            // scheduler. Payments only NOMINATE pins; the token bucket launches
2528            // them at a fixed per-node rate, and durable suppression is stamped
2529            // only at PROMOTION (after an authoritative post-jitter answerability
2530            // + cooldown check), so a cancelled reservation leaves nothing behind.
2531            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2532            // Periodic retry tick so budget/cooldown-deferred pins get retried
2533            // even when no new nomination arrives. `Skip` collapses a backlog.
2534            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2535            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2536            let mut last_summary = Instant::now();
2537            loop {
2538                // The reservation's jitter deadline is a wake source: if a
2539                // reservation is outstanding, sleep until it is due; otherwise
2540                // a far-future deadline effectively disables that arm and only
2541                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2542                // newly reserved (earlier) deadline is honoured next turn.
2543                let promotion_due = scheduler
2544                    .reserved_ready_at()
2545                    .unwrap_or_else(first_audit_far_future);
2546                tokio::select! {
2547                    () = shutdown.cancelled() => break,
2548                    event = rx.recv() => match event {
2549                        Some(e) => {
2550                            observability.received.fetch_add(1, Ordering::Relaxed);
2551                            // Pre-overflow reservation opportunity: before an
2552                            // arrival may displace a DIFFERENT peer, let the
2553                            // queue launch — a successful reservation frees the
2554                            // slot without eviction. One reservation can be
2555                            // outstanding at a time, so this consumes at most
2556                            // one slot per jitter window; arrivals beyond it
2557                            // fall through to random displacement (ADR-0004
2558                            // Amendment 4).
2559                            if scheduler.would_displace(&e) {
2560                                open_first_audit_reservation(
2561                                    &mut scheduler,
2562                                    &gossip_audit.cooldown,
2563                                    &observability,
2564                                )
2565                                .await;
2566                            }
2567                            scheduler.enqueue(e, &observability);
2568                            // Drain a bounded burst so a flood cannot starve the
2569                            // launch phase.
2570                            let mut drained = 1usize;
2571                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2572                                match rx.try_recv() {
2573                                    Ok(e) => {
2574                                        observability.received.fetch_add(1, Ordering::Relaxed);
2575                                        if scheduler.would_displace(&e) {
2576                                            open_first_audit_reservation(
2577                                                &mut scheduler,
2578                                                &gossip_audit.cooldown,
2579                                                &observability,
2580                                            )
2581                                            .await;
2582                                        }
2583                                        scheduler.enqueue(e, &observability);
2584                                        drained += 1;
2585                                    }
2586                                    Err(_) => break,
2587                                }
2588                            }
2589                        }
2590                        None => break,
2591                    },
2592                    _ = tick.tick() => {}
2593                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2594                }
2595
2596                // 1) Promote a due reservation. Resolved after EVERY wake (not
2597                //    only when the timer arm wins) so a continuously-ready `rx`
2598                //    cannot indefinitely delay a due promotion. The authoritative
2599                //    answerability + cooldown check-and-stamp happens here under
2600                //    the shared cooldown write lock, immediately before the send.
2601                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2602                    let promoted = {
2603                        let mut cooldown = gossip_audit.cooldown.write().await;
2604                        scheduler.resolve(
2605                            reservation,
2606                            SystemTime::now(),
2607                            Instant::now(),
2608                            &mut cooldown,
2609                            &observability,
2610                        )
2611                    };
2612                    if let Some((event, inflight_slot)) = promoted {
2613                        debug!(
2614                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2615                            event.peer, hex::encode(event.pin), event.key_count,
2616                            observability.inflight.load(Ordering::Relaxed)
2617                        );
2618                        let trigger = gossip_audit.clone();
2619                        let audit_observability = Arc::clone(&observability);
2620                        // Track the launch so `shutdown()`'s detached drain
2621                        // covers it. This task outlives the drainer loop that
2622                        // spawned it — the loop breaks on the shutdown token
2623                        // while the audit is still awaiting its response — so a
2624                        // bare spawn would let an in-flight subtree audit keep
2625                        // running, and keep its `Arc<P2PNode>`, past the point
2626                        // `shutdown()` claims every engine task has stopped.
2627                        let tracker = trigger.detached_task_tracker.clone();
2628                        tracker.spawn(async move {
2629                            // The jitter already elapsed as the reservation's
2630                            // timer; the slot is held for the audit's duration
2631                            // and released on drop (panic-safe).
2632                            let inflight_slot = inflight_slot;
2633                            let started = Instant::now();
2634                            let credit = storage_commitment_audit::AuditCredit {
2635                                recent_provers: &trigger.recent_provers,
2636                            };
2637                            let result = storage_commitment_audit::run_subtree_audit(
2638                                &trigger.p2p_node,
2639                                &trigger.config,
2640                                &event.peer,
2641                                event.pin,
2642                                event.key_count,
2643                                Some(&credit),
2644                            )
2645                            .await;
2646                            let outcome = first_audit_terminal_outcome(&result);
2647                            match outcome {
2648                                FirstAuditTerminalOutcome::Passed => {
2649                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2650                                }
2651                                FirstAuditTerminalOutcome::Timeout => {
2652                                    audit_observability
2653                                        .timed_out
2654                                        .fetch_add(1, Ordering::Relaxed);
2655                                }
2656                                FirstAuditTerminalOutcome::Failed => {
2657                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2658                                }
2659                                FirstAuditTerminalOutcome::BootstrapClaim => {
2660                                    audit_observability
2661                                        .bootstrap_claims
2662                                        .fetch_add(1, Ordering::Relaxed);
2663                                }
2664                                FirstAuditTerminalOutcome::Idle => {
2665                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2666                                }
2667                                FirstAuditTerminalOutcome::InsufficientKeys => {
2668                                    audit_observability
2669                                        .insufficient_keys
2670                                        .fetch_add(1, Ordering::Relaxed);
2671                                }
2672                            }
2673                            drop(inflight_slot);
2674                            debug!(
2675                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2676                                outcome.as_str(),
2677                                event.peer, hex::encode(event.pin), event.key_count,
2678                                started.elapsed().as_millis(),
2679                                audit_observability.inflight.load(Ordering::Relaxed)
2680                            );
2681                            handle_subtree_audit_result(
2682                                &result,
2683                                &trigger.p2p_node,
2684                                &trigger.sync_state,
2685                                &trigger.recent_provers,
2686                                &trigger.config,
2687                            )
2688                            .await;
2689                        });
2690                    }
2691                }
2692
2693                // 2) Open the single reservation from the pending queue if none
2694                //    is outstanding (read-only cooldown snapshot; the
2695                //    authoritative stamp is at promotion). Serializing
2696                //    reservations preserves per-launch lane alternation and keeps
2697                //    at most one jitter timer live.
2698                open_first_audit_reservation(
2699                    &mut scheduler,
2700                    &gossip_audit.cooldown,
2701                    &observability,
2702                )
2703                .await;
2704
2705                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2706                    // Token-independent hygiene: collect entries that aged past
2707                    // the answerability horizon while the budget gate kept the
2708                    // reserve scan from running, so the summary below reports
2709                    // only live work.
2710                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2711                    if swept > 0 {
2712                        debug!(
2713                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2714                            scheduler.pending_len()
2715                        );
2716                    }
2717                    info!(
2718                        "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={}",
2719                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2720                        observability.received.load(Ordering::Relaxed),
2721                        observability.queued.load(Ordering::Relaxed),
2722                        observability.coalesced.load(Ordering::Relaxed),
2723                        observability.suppressed_lower.load(Ordering::Relaxed),
2724                        observability.duplicates.load(Ordering::Relaxed),
2725                        observability.capacity_evicted.load(Ordering::Relaxed),
2726                        observability.self_target_skipped.load(Ordering::Relaxed),
2727                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2728                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2729                        observability.window_deduped.load(Ordering::Relaxed),
2730                        observability.launched.load(Ordering::Relaxed),
2731                        observability.passed.load(Ordering::Relaxed),
2732                        observability.timed_out.load(Ordering::Relaxed),
2733                        observability.failed.load(Ordering::Relaxed),
2734                        observability.bootstrap_claims.load(Ordering::Relaxed),
2735                        observability.idle.load(Ordering::Relaxed),
2736                        observability.insufficient_keys.load(Ordering::Relaxed),
2737                        observability.outside_answerability_window.load(Ordering::Relaxed),
2738                        scheduler.pending_len(),
2739                        FIRST_AUDIT_PENDING_CAP,
2740                        u8::from(scheduler.has_reservation()),
2741                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2742                        observability.inflight.load(Ordering::Relaxed),
2743                        scheduler.tokens(),
2744                    );
2745                    last_summary = Instant::now();
2746                }
2747            }
2748            debug!("First-audit drainer shut down");
2749        });
2750        self.task_handles.push(handle);
2751    }
2752
2753    #[allow(clippy::too_many_lines)]
2754    fn start_message_handler(&mut self) {
2755        let mut p2p_events = self.p2p_node.subscribe_events();
2756        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2757        let p2p = Arc::clone(&self.p2p_node);
2758        let storage = Arc::clone(&self.storage);
2759        let paid_list = Arc::clone(&self.paid_list);
2760        let payment_verifier = Arc::clone(&self.payment_verifier);
2761        let queues = Arc::clone(&self.queues);
2762        let config = Arc::clone(&self.config);
2763        let shutdown = self.shutdown.clone();
2764        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2765        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2766        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2767        let sync_history = Arc::clone(&self.sync_history);
2768        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2769        let repair_proofs = Arc::clone(&self.repair_proofs);
2770        let sync_trigger = Arc::clone(&self.sync_trigger);
2771        let my_commitment_state = Arc::clone(&self.commitment_state);
2772        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2773        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2774        let recent_provers = Arc::clone(&self.recent_provers);
2775        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2776        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2777        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2778        let sync_state = Arc::clone(&self.sync_state);
2779        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2780        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2781        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2782        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2783        let fetch_responder_admission_semaphore =
2784            Arc::clone(&self.fetch_responder_admission_semaphore);
2785        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2786        let verification_responder_worker_semaphore =
2787            Arc::clone(&self.verification_responder_worker_semaphore);
2788        let verification_responder_admission_semaphore =
2789            Arc::clone(&self.verification_responder_admission_semaphore);
2790        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2791        let neighbor_sync_responder_worker_semaphore =
2792            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2793        let neighbor_sync_responder_admission_semaphore =
2794            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2795        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2796        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2797        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2798        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2799        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2800        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2801        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2802        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2803        let detached_task_tracker = self.detached_task_tracker.clone();
2804        let subtree_round1 = self.subtree_round1.clone();
2805
2806        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2807        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2808        let gossip_audit = GossipAuditTrigger {
2809            p2p_node: Arc::clone(&p2p),
2810            config: Arc::clone(&config),
2811            recent_provers: Arc::clone(&recent_provers),
2812            sync_state: Arc::clone(&sync_state),
2813            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2814            detached_task_tracker: detached_task_tracker.clone(),
2815            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2816        };
2817
2818        let handler_context = ReplicationMessageHandlerContext {
2819            p2p_node: Arc::clone(&p2p),
2820            storage,
2821            paid_list,
2822            payment_verifier,
2823            queues,
2824            config: Arc::clone(&config),
2825            is_bootstrapping,
2826            bootstrap_state,
2827            sync_history,
2828            sync_cycle_epoch,
2829            repair_proofs: Arc::clone(&repair_proofs),
2830            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2831            ever_capable_peers,
2832            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2833            my_commitment_state,
2834            gossip_audit,
2835            audit_responder_semaphore,
2836            audit_responder_inflight,
2837            audit_responder_metrics,
2838            subtree_round1,
2839            fetch_responder_worker_semaphore,
2840            fetch_responder_admission_semaphore,
2841            fetch_responder_inflight,
2842            verification_responder_worker_semaphore,
2843            verification_responder_admission_semaphore,
2844            verification_responder_inflight,
2845            neighbor_sync_responder_worker_semaphore,
2846            neighbor_sync_responder_admission_semaphore,
2847            neighbor_sync_responder_inflight,
2848            fresh_offer_worker_semaphore,
2849            fresh_offer_admission_semaphore,
2850            fresh_offer_responder_inflight,
2851            fresh_offer_in_flight,
2852            paid_notify_worker_semaphore,
2853            paid_notify_admission_semaphore,
2854            paid_notify_responder_inflight,
2855            shutdown: shutdown.clone(),
2856            detached_task_tracker,
2857        };
2858
2859        let (replication_tx, mut replication_rx) =
2860            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2861        let serial_context = handler_context.clone();
2862        let serial_shutdown = shutdown.clone();
2863        let serial_handle = tokio::spawn(async move {
2864            loop {
2865                tokio::select! {
2866                    () = serial_shutdown.cancelled() => break,
2867                    inbound = replication_rx.recv() => {
2868                        let Some(inbound) = inbound else { break };
2869                        let source = inbound.source;
2870                        match handle_replication_message(
2871                            &source,
2872                            inbound.msg,
2873                            &serial_context,
2874                            inbound.received_at,
2875                            inbound.rr_message_id.as_deref(),
2876                        )
2877                        .await
2878                        {
2879                            Ok(()) => {}
2880                            Err(e) => {
2881                                debug!("Replication message from {source} error: {e}");
2882                            }
2883                        }
2884                    }
2885                }
2886            }
2887            debug!("Replication non-audit serial handler shut down");
2888        });
2889        self.task_handles.push(serial_handle);
2890
2891        let handle = tokio::spawn(async move {
2892            loop {
2893                tokio::select! {
2894                    () = shutdown.cancelled() => break,
2895                    event = p2p_events.recv() => {
2896                        let event = match event {
2897                            Ok(event) => event,
2898                            Err(error) => match handle_replication_event_recv_error(&error) {
2899                                ControlFlow::Continue(()) => continue,
2900                                ControlFlow::Break(()) => break,
2901                            },
2902                        };
2903                        let Some((source, payload, inbound_protocol, rr_message_id)) =
2904                            replication_payload_from_event(event)
2905                        else {
2906                            continue;
2907                        };
2908                        let received_at = Instant::now();
2909                        let msg = match ReplicationMessage::decode(&payload) {
2910                            Ok(msg) => msg,
2911                            Err(e) => {
2912                                debug!("Replication message from {source} decode error: {e}");
2913                                continue;
2914                            }
2915                        };
2916                        if !body_matches_protocol(&msg.body, inbound_protocol) {
2917                            debug!(
2918                                "Dropping replication body (variant {}) on protocol \
2919                                 {inbound_protocol}: wrong id for its family \
2920                                 (cross-version or misrouted)",
2921                                msg.body.variant_index()
2922                            );
2923                            continue;
2924                        }
2925                        if let Some(class) = audit_responder_class(&msg.body) {
2926                            handler_context
2927                                .audit_responder_metrics
2928                                .record_received(source, class);
2929                        }
2930                        let inbound = InboundReplicationMessage {
2931                            source,
2932                            msg,
2933                            rr_message_id,
2934                            received_at,
2935                        };
2936                        if matches!(
2937                            inbound.msg.body,
2938                            ReplicationMessageBody::AuditChallenge(_)
2939                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
2940                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
2941                        ) {
2942                            let source = inbound.source;
2943                            match handle_replication_message(
2944                                &source,
2945                                inbound.msg,
2946                                &handler_context,
2947                                inbound.received_at,
2948                                inbound.rr_message_id.as_deref(),
2949                            )
2950                            .await
2951                            {
2952                                Ok(()) => {}
2953                                Err(e) => {
2954                                    debug!("Replication message from {source} error: {e}");
2955                                }
2956                            }
2957                            continue;
2958                        }
2959                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2960                            if dropped.audit_responder_class.is_some() {
2961                                handler_context
2962                                    .audit_responder_metrics
2963                                    .record_serial_queue_drop(dropped.source);
2964                            }
2965                            // Every serial-lane class has protocol recovery: syncs rerun,
2966                            // fetches retry, verification re-asks, and a dropped fresh
2967                            // offer is refilled by neighbor sync (the possession check
2968                            // penalises the absence but never re-offers). Responses are
2969                            // covered by their requester's deadline/retry path. Never run
2970                            // a bulk handler here: event receipt must remain non-blocking.
2971                            warn!(
2972                                message_class = dropped.message_class,
2973                                source = %dropped.source,
2974                                queue_depth = dropped.queue_depth,
2975                                reason = dropped.reason.as_str(),
2976                                "Replication serial-queue message dropped"
2977                            );
2978                        }
2979                    }
2980                    // Gap 4: Topology churn handling (Section 13).
2981                    //
2982                    // The DHT routing table emits KClosestPeersChanged when the
2983                    // K-closest peer set actually changes, which is the precise
2984                    // signal for triggering neighbor sync. This replaces the
2985                    // previous approach of checking every PeerConnected /
2986                    // PeerDisconnected event against the close group.
2987                    dht_event = dht_events.recv() => {
2988                        let dht_event = match dht_event {
2989                            Ok(event) => event,
2990                            Err(RecvError::Lagged(missed)) => {
2991                                // Under heavy churn the broadcast buffer can overflow
2992                                // and drop routing-table events — the moment
2993                                // convergence matters most. A dropped
2994                                // KClosestPeersChanged means its entrants were never
2995                                // queued and its departures were never pruned, so
2996                                // draining priority_order cannot recover either.
2997                                // Resync from ground truth instead: snapshot the
2998                                // current close-peer set, prune pending peers that
2999                                // left it during the lost window (retain_sync_peers,
3000                                // as the normal topology-change path does), and queue
3001                                // every member. Dedup (queue_priority_peers) and
3002                                // per-peer cooldown (select_next_sync_peer) drop peers
3003                                // already queued or recently synced, so only genuine
3004                                // entrants surface.
3005                                warn!(
3006                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3007                                );
3008                                let self_id = *p2p.peer_id();
3009                                let neighbors = neighbor_sync::snapshot_close_neighbors(
3010                                    &p2p,
3011                                    &self_id,
3012                                    config.neighbor_sync_scope,
3013                                )
3014                                .await;
3015                                let neighbor_set =
3016                                    neighbors.iter().copied().collect::<HashSet<_>>();
3017                                let (requeued, sync_removals) = {
3018                                    let mut state = sync_state.write().await;
3019                                    let sync_removals =
3020                                        state.retain_sync_peers(&neighbor_set);
3021                                    let requeued = state.queue_priority_peers(neighbors);
3022                                    (requeued, sync_removals)
3023                                };
3024                                if sync_removals > 0 {
3025                                    debug!(
3026                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3027                                    );
3028                                }
3029                                if requeued > 0 {
3030                                    debug!(
3031                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3032                                    );
3033                                    sync_trigger.notify_one();
3034                                }
3035                                continue;
3036                            }
3037                            Err(RecvError::Closed) => {
3038                                // A closed broadcast channel never yields again;
3039                                // continuing would spin the select! loop forever.
3040                                warn!(
3041                                    "DHT event stream closed on replication branch; stopping message handler"
3042                                );
3043                                break;
3044                            }
3045                        };
3046                        match dht_event {
3047                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3048                                let old_peers = old
3049                                    .iter()
3050                                    .take(config.neighbor_sync_scope)
3051                                    .copied()
3052                                    .collect::<HashSet<_>>();
3053                                let new_scoped = new
3054                                    .iter()
3055                                    .take(config.neighbor_sync_scope)
3056                                    .copied()
3057                                    .collect::<Vec<_>>();
3058                                let new_peers =
3059                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3060                                let entrants = new_scoped
3061                                    .iter()
3062                                    .copied()
3063                                    .filter(|peer| !old_peers.contains(peer))
3064                                    .collect::<Vec<_>>();
3065                                let entrant_count = entrants.len();
3066                                let (priority_insertions, sync_removals) = {
3067                                    let mut state = sync_state.write().await;
3068                                    let sync_removals = state.retain_sync_peers(&new_peers);
3069                                    let priority_insertions = state.queue_priority_peers(entrants);
3070                                    (priority_insertions, sync_removals)
3071                                };
3072                                if priority_insertions > 0 {
3073                                    debug!(
3074                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3075                                    );
3076                                } else {
3077                                    debug!(
3078                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3079                                    );
3080                                }
3081                                sync_trigger.notify_one();
3082                            }
3083                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3084                                sync_state.write().await.remove_peer(&peer_id);
3085                                repair_proofs.write().await.remove_peer(&peer_id);
3086                                update_bootstrap_after_peer_removed(
3087                                    &peer_id,
3088                                    &handler_context.bootstrap_state,
3089                                    &handler_context.queues,
3090                                    &handler_context.is_bootstrapping,
3091                                    &bootstrap_complete_notify,
3092                                )
3093                                .await;
3094                                // v12: drop the commitment bytes and the
3095                                // recent-prover credit so a churn / sybil
3096                                // attacker cannot leave behind one
3097                                // StorageCommitment per identity in
3098                                // `last_commitment_by_peer`. Also drop the
3099                                // sig-verify rate-limit timestamp.
3100                                last_commitment_by_peer.write().await.remove(&peer_id);
3101                                recent_provers.write().await.forget_peer(&peer_id);
3102                                sig_verify_attempts.write().await.remove(&peer_id);
3103                                // Same for the gossip-audit cooldown (ADR-0002)
3104                                // and the lottery-attempt window.
3105                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3106                                gossip_lottery_attempts.write().await.remove(&peer_id);
3107                                // The sticky `commitment_capable` flag is
3108                                // preserved orthogonally via
3109                                // `ever_capable_peers` — even after this
3110                                // removal, a re-joining peer continues to
3111                                // be treated as v12-capable rather than
3112                                // legacy (§3 shield).
3113                            }
3114                            _ => {}
3115                        }
3116                    }
3117                }
3118            }
3119            debug!("Replication message handler shut down");
3120        });
3121        self.task_handles.push(handle);
3122    }
3123
3124    fn start_neighbor_sync_loop(&mut self) {
3125        let p2p = Arc::clone(&self.p2p_node);
3126        let storage = Arc::clone(&self.storage);
3127        let paid_list = Arc::clone(&self.paid_list);
3128        let queues = Arc::clone(&self.queues);
3129        let config = Arc::clone(&self.config);
3130        let shutdown = self.shutdown.clone();
3131        let sync_state = Arc::clone(&self.sync_state);
3132        let sync_history = Arc::clone(&self.sync_history);
3133        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3134        let repair_proofs = Arc::clone(&self.repair_proofs);
3135        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3136        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3137        let sync_trigger = Arc::clone(&self.sync_trigger);
3138        let commitment_state = Arc::clone(&self.commitment_state);
3139        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3140        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3141        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3142        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3143        let detached_task_tracker = self.detached_task_tracker.clone();
3144        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3145        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3146        // here too so a peer that only ever answers — never initiates sync —
3147        // is still audited; otherwise it could fully evade auditing.
3148        let gossip_audit = GossipAuditTrigger {
3149            p2p_node: Arc::clone(&p2p),
3150            config: Arc::clone(&config),
3151            recent_provers: Arc::clone(&self.recent_provers),
3152            sync_state: Arc::clone(&sync_state),
3153            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3154            detached_task_tracker,
3155            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3156        };
3157
3158        let handle = tokio::spawn(async move {
3159            loop {
3160                // Park for the periodic tick or an explicit trigger ONLY when no
3161                // priority (topology-change) peers are queued. `sync_trigger` is a
3162                // coalescing `Notify`, so a churn burst that queues many entrants
3163                // produces a single wakeup; parking after draining one batch would
3164                // leave the rest waiting up to a full periodic tick. `priority_order`
3165                // is the durable record of pending work, so drain it back-to-back —
3166                // each round removes the peers it selects (`select_next_sync_peer`),
3167                // so the drain terminates once the queue empties.
3168                if !sync_state.read().await.has_priority_peers() {
3169                    let interval = config.random_neighbor_sync_interval();
3170                    tokio::select! {
3171                        () = shutdown.cancelled() => break,
3172                        () = tokio::time::sleep(interval) => {}
3173                        () = sync_trigger.notified() => {
3174                            debug!("Neighbor sync triggered by topology change");
3175                        }
3176                    }
3177                }
3178                // Wrap the sync round in a select so shutdown cancels
3179                // in-progress network operations rather than waiting for
3180                // the full round to complete.
3181                tokio::select! {
3182                    () = shutdown.cancelled() => break,
3183                    () = run_neighbor_sync_round(
3184                        &p2p,
3185                        &storage,
3186                        &paid_list,
3187                        &queues,
3188                        &config,
3189                        &sync_state,
3190                        &sync_history,
3191                        &sync_cycle_epoch,
3192                        &repair_proofs,
3193                        &is_bootstrapping,
3194                        &bootstrap_state,
3195                        &commitment_state,
3196                        &last_commitment_by_peer,
3197                        &ever_capable_peers,
3198                        &sig_verify_attempts,
3199                        &audit_challenge_coordinator,
3200                        &gossip_audit,
3201                    ) => {}
3202                }
3203            }
3204            debug!("Neighbor sync loop shut down");
3205        });
3206        self.task_handles.push(handle);
3207    }
3208
3209    fn start_self_lookup_loop(&mut self) {
3210        let p2p = Arc::clone(&self.p2p_node);
3211        let config = Arc::clone(&self.config);
3212        let shutdown = self.shutdown.clone();
3213
3214        let handle = tokio::spawn(async move {
3215            loop {
3216                let interval = config.random_self_lookup_interval();
3217                tokio::select! {
3218                    () = shutdown.cancelled() => break,
3219                    () = tokio::time::sleep(interval) => {
3220                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3221                            debug!("Self-lookup failed: {e}");
3222                        }
3223                    }
3224                }
3225            }
3226            debug!("Self-lookup loop shut down");
3227        });
3228        self.task_handles.push(handle);
3229    }
3230
3231    /// Periodic responsible-chunk audit loop (audit #2): every
3232    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3233    /// eligible close peer for the chunks it *should* be storing (by
3234    /// responsibility and prior repair hint), independent of the gossip-triggered
3235    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3236    /// immediately and periodically thereafter.
3237    fn start_audit_loop(&mut self) {
3238        let p2p = Arc::clone(&self.p2p_node);
3239        let storage = Arc::clone(&self.storage);
3240        let config = Arc::clone(&self.config);
3241        let shutdown = self.shutdown.clone();
3242        let sync_history = Arc::clone(&self.sync_history);
3243        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3244        let repair_proofs = Arc::clone(&self.repair_proofs);
3245        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3246        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3247        let sync_state = Arc::clone(&self.sync_state);
3248        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3249
3250        let handle = tokio::spawn(async move {
3251            // Invariant 19: wait for bootstrap to drain before starting audits.
3252            loop {
3253                tokio::select! {
3254                    () = shutdown.cancelled() => return,
3255                    () = tokio::time::sleep(
3256                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3257                    ) => {
3258                        if bootstrap_state.read().await.is_drained() {
3259                            break;
3260                        }
3261                    }
3262                }
3263            }
3264
3265            // Run one audit tick immediately after bootstrap drain.
3266            {
3267                let bootstrapping = *is_bootstrapping.read().await;
3268                let result = {
3269                    let history = sync_history.read().await;
3270                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3271                    audit::audit_tick_with_repair_proofs(
3272                        &p2p,
3273                        &storage,
3274                        &config,
3275                        &history,
3276                        &repair_proofs,
3277                        &audit_challenge_coordinator,
3278                        current_sync_epoch,
3279                        bootstrapping,
3280                    )
3281                    .await
3282                };
3283                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3284            }
3285
3286            // Then run periodically.
3287            loop {
3288                let interval = config.random_audit_tick_interval();
3289                tokio::select! {
3290                    () = shutdown.cancelled() => break,
3291                    () = tokio::time::sleep(interval) => {
3292                        let bootstrapping = *is_bootstrapping.read().await;
3293                        let result = {
3294                            let history = sync_history.read().await;
3295                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3296                            audit::audit_tick_with_repair_proofs(
3297                                &p2p,
3298                                &storage,
3299                                &config,
3300                                &history,
3301                                &repair_proofs,
3302                                &audit_challenge_coordinator,
3303                                current_sync_epoch,
3304                                bootstrapping,
3305                            )
3306                            .await
3307                        };
3308                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3309                    }
3310                }
3311            }
3312            debug!("Audit loop shut down");
3313        });
3314        self.task_handles.push(handle);
3315    }
3316
3317    /// Periodically rebuild + sign + rotate the responder's storage
3318    /// commitment.
3319    ///
3320    /// Phase 3 of the v12 storage-bound audit. Once per
3321    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3322    /// current LMDB key set, builds a Merkle tree (for content-addressed
3323    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3324    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3325    /// into `commitment_state`. Old `previous` slot is dropped by the
3326    /// rotate (per `ResponderCommitmentState::rotate`).
3327    ///
3328    /// Skips if the key set is empty (no commitment to make) — the
3329    /// auditor side falls back to the legacy plain-digest path for
3330    /// peers that have never gossiped a commitment.
3331    fn start_commitment_rotation_loop(&mut self) {
3332        let storage = Arc::clone(&self.storage);
3333        let identity = Arc::clone(&self.identity);
3334        let commitment_state = Arc::clone(&self.commitment_state);
3335        let shutdown = self.shutdown.clone();
3336        let p2p = Arc::clone(&self.p2p_node);
3337        let config = Arc::clone(&self.config);
3338        let sync_trigger = Arc::clone(&self.sync_trigger);
3339        let recent_provers = Arc::clone(&self.recent_provers);
3340
3341        let handle = tokio::spawn(async move {
3342            // Build the first commitment immediately on startup so a
3343            // restarted node can answer commitment-bound audits right
3344            // away — otherwise current() stays None for a full rotation
3345            // interval and audits silently fall back to legacy.
3346            //
3347            // After the first build, trigger an immediate neighbor-sync
3348            // round so the new commitment gossips out within seconds.
3349            // Without this, after a restart remote auditors keep pinning
3350            // the pre-restart (rotated-away) hash until their normal
3351            // sync cadence elapses — up to 1 h in the worst case,
3352            // during which time commitment-bound audits hit "unknown
3353            // commitment hash" -> Idle no-ops.
3354            // ML-DSA signatures are randomized so we cannot reproduce
3355            // the pre-restart hash; the only honest path to recovery
3356            // is fast re-gossip.
3357            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3358            // spawned), so this initial rebuild no-ops when the key set is
3359            // unchanged — preserving the reloaded current pin; otherwise the
3360            // reloaded roots stay answerable as retained slots until their gossip
3361            // TTL lapses. Persistence is handled by the retention-persist loop.
3362            if let Err(e) =
3363                rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3364                    .await
3365            {
3366                warn!("Initial commitment build failed: {e}");
3367            } else {
3368                sync_trigger.notify_one();
3369            }
3370            loop {
3371                tokio::select! {
3372                    () = shutdown.cancelled() => break,
3373                    () = tokio::time::sleep(
3374                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3375                    ) => {
3376                        if let Err(e) = rebuild_and_rotate_commitment(
3377                            &storage,
3378                            &identity,
3379                            &commitment_state,
3380                            &p2p,
3381                            &config,
3382                        ).await {
3383                            warn!("Commitment rotation failed: {e}");
3384                        }
3385                        // Piggyback a sweep of expired recent_provers
3386                        // entries on the rotation tick (same cadence,
3387                        // 1 h). is_credited_holder already honours the
3388                        // TTL on read, but the sweep reclaims memory
3389                        // for entries we'll never re-read.
3390                        let dropped = recent_provers.write().await.sweep_expired(
3391                            std::time::Instant::now()
3392                        );
3393                        if dropped > 0 {
3394                            debug!("recent_provers: swept {dropped} expired entries");
3395                        }
3396                    }
3397                }
3398            }
3399            debug!("Commitment rotation loop shut down");
3400        });
3401        self.task_handles.push(handle);
3402    }
3403
3404    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3405    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3406    /// rotations — survives a restart. Flushes once immediately, then every
3407    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3408    fn start_retention_persist_loop(&mut self) {
3409        let commitment_state = Arc::clone(&self.commitment_state);
3410        let retention_path = self.retention_path.clone();
3411        let shutdown = self.shutdown.clone();
3412        let handle = tokio::spawn(async move {
3413            let mut last: Option<Vec<u8>> = None;
3414            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3415            loop {
3416                tokio::select! {
3417                    () = shutdown.cancelled() => {
3418                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3419                            .await;
3420                        break;
3421                    }
3422                    () = tokio::time::sleep(std::time::Duration::from_secs(
3423                        RETENTION_PERSIST_INTERVAL_SECS,
3424                    )) => {
3425                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3426                            .await;
3427                    }
3428                }
3429            }
3430            debug!("Commitment retention persist loop shut down");
3431        });
3432        self.task_handles.push(handle);
3433    }
3434
3435    /// Periodically emit the cumulative replication traffic summaries: the
3436    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3437    /// (V2-684). Both read process-global counter tables maintained by the
3438    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3439    /// state.
3440    fn start_traffic_summary_loop(&mut self) {
3441        let shutdown = self.shutdown.clone();
3442        let handle = tokio::spawn(async move {
3443            loop {
3444                tokio::select! {
3445                    () = shutdown.cancelled() => break,
3446                    () = tokio::time::sleep(std::time::Duration::from_secs(
3447                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3448                    )) => {
3449                        protocol::log_traffic_summary();
3450                        protocol::log_served_peers_summary();
3451                        protocol::log_audit_outcome_summary();
3452                        audit_metrics::log_responder_admission_summary();
3453                    }
3454                }
3455            }
3456            debug!("Replication traffic summary loop shut down");
3457        });
3458        self.task_handles.push(handle);
3459    }
3460
3461    /// Periodically expose the state that gates bootstrap completion and prune
3462    /// admission. The state counts are copied before reading `is_bootstrapping`
3463    /// so this diagnostic path never nests async locks.
3464    #[cfg(feature = "logging")]
3465    fn start_bootstrap_state_snapshot_loop(&mut self) {
3466        let shutdown = self.shutdown.clone();
3467        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3468        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3469        let started_at = Instant::now();
3470        let handle = tokio::spawn(async move {
3471            loop {
3472                tokio::select! {
3473                    () = shutdown.cancelled() => break,
3474                    () = tokio::time::sleep(Duration::from_secs(
3475                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3476                    )) => {
3477                        let (
3478                            drained,
3479                            pending_peer_requests,
3480                            pending_keys,
3481                            capacity_rejected_sources,
3482                        ) = {
3483                            let state = bootstrap_state.read().await;
3484                            (
3485                                state.drained,
3486                                state.pending_peer_requests,
3487                                state.pending_keys.len(),
3488                                state.capacity_rejected_sources.len(),
3489                            )
3490                        };
3491                        let bootstrapping = *is_bootstrapping.read().await;
3492                        let snapshot_state = if drained && !bootstrapping {
3493                            "healthy"
3494                        } else if drained {
3495                            "drained_waiting_for_bootstrap_flag"
3496                        } else {
3497                            "pending"
3498                        };
3499                        info!(
3500                            drained,
3501                            pending_peer_requests,
3502                            pending_keys,
3503                            capacity_rejected_sources,
3504                            is_bootstrapping = bootstrapping,
3505                            snapshot_state,
3506                            uptime_secs = started_at.elapsed().as_secs(),
3507                            "Replication bootstrap state snapshot"
3508                        );
3509                        if drained && !bootstrapping {
3510                            info!(
3511                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3512                            );
3513                            break;
3514                        }
3515                    }
3516                }
3517            }
3518            debug!("Bootstrap state snapshot loop shut down");
3519        });
3520        self.task_handles.push(handle);
3521    }
3522
3523    /// Periodically rank remote peers using the shared audit responder pool and
3524    /// report handler-only versus end-to-end latency. Windowed values make a
3525    /// burst visible even after a long-running node has accumulated traffic.
3526    #[cfg(feature = "logging")]
3527    fn start_audit_responder_summary_loop(&mut self) {
3528        let shutdown = self.shutdown.clone();
3529        let metrics = Arc::clone(&self.audit_responder_metrics);
3530        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3531        let handle = tokio::spawn(async move {
3532            let mut window_started = Instant::now();
3533            loop {
3534                tokio::select! {
3535                    () = shutdown.cancelled() => {
3536                        log_audit_responder_summary(
3537                            &metrics,
3538                            &semaphore,
3539                            window_started.elapsed(),
3540                        );
3541                        break;
3542                    }
3543                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3544                        log_audit_responder_summary(
3545                            &metrics,
3546                            &semaphore,
3547                            window_started.elapsed(),
3548                        );
3549                        window_started = Instant::now();
3550                    }
3551                }
3552            }
3553            debug!("Audit responder summary loop shut down");
3554        });
3555        self.task_handles.push(handle);
3556    }
3557
3558    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3559    fn start_fetch_worker(&mut self) {
3560        let p2p = Arc::clone(&self.p2p_node);
3561        let storage = Arc::clone(&self.storage);
3562        let queues = Arc::clone(&self.queues);
3563        let config = Arc::clone(&self.config);
3564        let shutdown = self.shutdown.clone();
3565        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3566        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3567        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3568        let detached_task_tracker = self.detached_task_tracker.clone();
3569        let concurrency = max_parallel_fetch();
3570
3571        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3572
3573        let handle = tokio::spawn(async move {
3574            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3575            // always recover the key — even if the inner task panics.
3576            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3577
3578            loop {
3579                // Fill up to `concurrency` slots from the queue.
3580                {
3581                    let mut q = queues.write().await;
3582                    while in_flight.len() < concurrency {
3583                        let Some(candidate) = q.dequeue_fetch() else {
3584                            break;
3585                        };
3586                        let fetch_key = candidate.key;
3587                        let Some(&source) = candidate.sources.first() else {
3588                            warn!(
3589                                "Fetch candidate {} has no sources; requeueing for verification",
3590                                hex::encode(fetch_key)
3591                            );
3592                            let _ = q.requeue_candidate_for_verification(
3593                                candidate,
3594                                config.verification_request_timeout,
3595                            );
3596                            continue;
3597                        };
3598                        q.start_dequeued_fetch(candidate, source);
3599
3600                        let p2p = Arc::clone(&p2p);
3601                        let storage = Arc::clone(&storage);
3602                        let config = Arc::clone(&config);
3603                        let token = shutdown.clone();
3604                        let tracker = detached_task_tracker.clone();
3605                        in_flight.push(Box::pin(async move {
3606                            // Tracked so shutdown() still awaits the task if
3607                            // this awaiter is dropped (e.g. the worker is
3608                            // aborted): it holds Arc<LmdbStorage> and must
3609                            // not outlive the engine.
3610                            let handle = tracker.spawn(async move {
3611                                // Cancel-aware: abort when the engine shuts down.
3612                                tokio::select! {
3613                                    () = token.cancelled() => FetchOutcome {
3614                                        key: fetch_key,
3615                                        result: FetchResult::SourceFailed,
3616                                    },
3617                                    outcome = execute_single_fetch(
3618                                        p2p, storage, config, fetch_key, source,
3619                                    ) => outcome,
3620                                }
3621                            });
3622                            match handle.await {
3623                                Ok(outcome) => (outcome.key, Some(outcome)),
3624                                Err(e) => {
3625                                    error!(
3626                                        "Fetch task for {} panicked: {e}",
3627                                        hex::encode(fetch_key)
3628                                    );
3629                                    (fetch_key, None)
3630                                }
3631                            }
3632                        }));
3633                    }
3634                } // release queues write lock
3635
3636                if in_flight.is_empty() {
3637                    // No work — wait for new items or shutdown.
3638                    tokio::select! {
3639                        () = shutdown.cancelled() => break,
3640                        () = tokio::time::sleep(
3641                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3642                        ) => continue,
3643                    }
3644                }
3645
3646                // Wait for the next fetch to complete and process the result.
3647                tokio::select! {
3648                    () = shutdown.cancelled() => break,
3649                    Some((key, maybe_outcome)) = in_flight.next() => {
3650                        let mut q = queues.write().await;
3651                        let terminal = if let Some(outcome) = maybe_outcome {
3652                            match apply_fetch_result(
3653                                &mut q,
3654                                &key,
3655                                &outcome.result,
3656                                config.verification_request_timeout,
3657                            ) {
3658                                FetchFollowUp::Terminal => true,
3659                                FetchFollowUp::RequeuedForVerification => false,
3660                                FetchFollowUp::RetryFrom(next_peer) => {
3661                                    // Spawn a new fetch task for the next source.
3662                                    let p2p = Arc::clone(&p2p);
3663                                    let storage = Arc::clone(&storage);
3664                                    let config = Arc::clone(&config);
3665                                    let token = shutdown.clone();
3666                                    let tracker = detached_task_tracker.clone();
3667                                    let fetch_key = key;
3668                                    in_flight.push(Box::pin(async move {
3669                                        // Tracked for the same reason as the
3670                                        // initial fetch spawn above.
3671                                        let handle = tracker.spawn(async move {
3672                                            tokio::select! {
3673                                                () = token.cancelled() => FetchOutcome {
3674                                                    key: fetch_key,
3675                                                    result: FetchResult::SourceFailed,
3676                                                },
3677                                                outcome = execute_single_fetch(
3678                                                    p2p, storage, config, fetch_key, next_peer,
3679                                                ) => outcome,
3680                                            }
3681                                        });
3682                                        match handle.await {
3683                                            Ok(outcome) => (outcome.key, Some(outcome)),
3684                                            Err(e) => {
3685                                                error!(
3686                                                    "Fetch task for {} panicked: {e}",
3687                                                    hex::encode(fetch_key)
3688                                                );
3689                                                (fetch_key, None)
3690                                            }
3691                                        }
3692                                    }));
3693                                    false
3694                                }
3695                            }
3696                        } else {
3697                            // Task panicked — retry verification when this was
3698                            // a verified repair, otherwise reclaim the slot.
3699                            !q.requeue_fetch_for_verification(
3700                                &key,
3701                                config.verification_request_timeout,
3702                            )
3703                        };
3704
3705                        // Shrink bootstrap pending set on terminal exit.
3706                        if terminal {
3707                            drop(q); // release queues lock before acquiring bootstrap_state
3708                            if !bootstrap_state.read().await.is_drained() {
3709                                bootstrap_state.write().await.remove_key(&key);
3710                                let q = queues.read().await;
3711                                if bootstrap::check_bootstrap_drained(
3712                                    &bootstrap_state,
3713                                    &q,
3714                                )
3715                                .await
3716                                {
3717                                    complete_bootstrap(
3718                                        &is_bootstrapping,
3719                                        &bootstrap_complete_notify,
3720                                    ).await;
3721                                }
3722                            }
3723                        }
3724                    }
3725                }
3726            }
3727
3728            // Cancel and drain remaining in-flight fetches on shutdown.
3729            // The CancellationToken is already cancelled by this point, so
3730            // spawned tasks will see cancellation via their select! branches.
3731            while in_flight.next().await.is_some() {}
3732            debug!("Fetch worker shut down");
3733        });
3734        self.task_handles.push(handle);
3735    }
3736
3737    fn start_verification_worker(&mut self) {
3738        let p2p = Arc::clone(&self.p2p_node);
3739        let storage = Arc::clone(&self.storage);
3740        let queues = Arc::clone(&self.queues);
3741        let paid_list = Arc::clone(&self.paid_list);
3742        let config = Arc::clone(&self.config);
3743        let shutdown = self.shutdown.clone();
3744        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3745        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3746        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3747        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3748        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3749        let recent_provers = Arc::clone(&self.recent_provers);
3750
3751        let handle = tokio::spawn(async move {
3752            loop {
3753                tokio::select! {
3754                    () = shutdown.cancelled() => break,
3755                    () = tokio::time::sleep(
3756                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3757                    ) => {
3758                        let ctx = VerificationCycleContext {
3759                            p2p_node: &p2p,
3760                            paid_list: &paid_list,
3761                            storage: &storage,
3762                            queues: &queues,
3763                            config: &config,
3764                            bootstrap_state: &bootstrap_state,
3765                            is_bootstrapping: &is_bootstrapping,
3766                            bootstrap_complete_notify: &bootstrap_complete_notify,
3767                            last_commitment_by_peer: &last_commitment_by_peer,
3768                            ever_capable_peers: &ever_capable_peers,
3769                            recent_provers: &recent_provers,
3770                        };
3771                        run_verification_cycle(ctx).await;
3772                    }
3773                }
3774            }
3775            debug!("Verification worker shut down");
3776        });
3777        self.task_handles.push(handle);
3778    }
3779
3780    /// Gap 3: Run a one-shot bootstrap sync on startup.
3781    ///
3782    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3783    /// (indicating the routing table is populated) before snapshotting
3784    /// close neighbors. Falls back after a timeout so bootstrap nodes
3785    /// (which have no peers and therefore never receive the event) still
3786    /// proceed.
3787    ///
3788    /// After the gate, finds close neighbors, syncs with each in
3789    /// round-robin batches, admits returned hints into the verification
3790    /// pipeline, and tracks discovered keys for bootstrap drain detection.
3791    #[allow(clippy::too_many_lines)]
3792    fn start_bootstrap_sync(
3793        &mut self,
3794        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3795    ) {
3796        let p2p = Arc::clone(&self.p2p_node);
3797        let storage = Arc::clone(&self.storage);
3798        let paid_list = Arc::clone(&self.paid_list);
3799        let queues = Arc::clone(&self.queues);
3800        let config = Arc::clone(&self.config);
3801        let shutdown = self.shutdown.clone();
3802        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3803        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3804        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3805        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3806        let repair_proofs = Arc::clone(&self.repair_proofs);
3807        let my_commitment_state = Arc::clone(&self.commitment_state);
3808        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3809        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3810        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3811
3812        let handle = tokio::spawn(async move {
3813            // Wait for DHT bootstrap to complete before snapshotting
3814            // neighbors. The routing table is empty until saorsa-core
3815            // finishes its FIND_NODE rounds and bucket refreshes.
3816            let gate = bootstrap::wait_for_bootstrap_complete(
3817                dht_events,
3818                config.bootstrap_complete_timeout_secs,
3819                &shutdown,
3820            )
3821            .await;
3822
3823            if gate == bootstrap::BootstrapGateResult::Shutdown {
3824                return;
3825            }
3826
3827            let self_id = *p2p.peer_id();
3828            let neighbors =
3829                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3830                    .await;
3831
3832            if neighbors.is_empty() {
3833                info!("Bootstrap sync: no close neighbors found, marking drained");
3834                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3835                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3836                return;
3837            }
3838
3839            let neighbor_count = neighbors.len();
3840            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3841
3842            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3843            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3844                if shutdown.is_cancelled() {
3845                    break;
3846                }
3847
3848                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3849                    batch,
3850                    &storage,
3851                    &paid_list,
3852                    &p2p,
3853                    config.close_group_size,
3854                    config.paid_list_close_group_size,
3855                )
3856                .await;
3857
3858                // Keep the batch outstanding until every response has been
3859                // admitted and bootstrap accounting is updated. The verification
3860                // worker uses this counter as a batch barrier, so it cannot race
3861                // the source aggregation below.
3862                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3863                let bootstrapping = *is_bootstrapping.read().await;
3864
3865                let sync_futures = batch.iter().map(|peer| {
3866                    let peer = *peer;
3867                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3868                    // Atomically snapshot + mark-gossiped for each emitted
3869                    // bootstrap request so we remain answerable for it.
3870                    let commitment = my_commitment_state
3871                        .current_for_gossip()
3872                        .map(|binding| binding.commitment().clone());
3873                    let p2p = &p2p;
3874                    let config = &config;
3875                    async move {
3876                        let outcome = neighbor_sync::sync_with_peer_with_hints(
3877                            &peer,
3878                            p2p,
3879                            config,
3880                            bootstrapping,
3881                            hints,
3882                            commitment,
3883                        )
3884                        .await;
3885                        (peer, outcome)
3886                    }
3887                });
3888                let completed = join_all(sync_futures).await;
3889
3890                // Process response metadata before exposing any of this batch's
3891                // hints to verification.
3892                for (peer, outcome) in &completed {
3893                    if let Some(outcome) = outcome {
3894                        // Ingest the peer's piggybacked commitment from the
3895                        // response (same verification as the request path).
3896                        // Bootstrap is the FIRST gossip we receive from most
3897                        // peers, so this populates last_commitment_by_peer.
3898                        //
3899                        // We intentionally do NOT trigger a gossip-audit here:
3900                        // during bootstrap this node may itself still be
3901                        // bootstrapping (audits are gated on that), and the
3902                        // close-group/RT view is not yet stable. The peer is
3903                        // audited on the first STEADY-STATE neighbor-sync round
3904                        // after bootstrap drains (request + response paths both
3905                        // trigger), which is within one sync cycle — so caching
3906                        // the commitment here is sufficient and there is no
3907                        // coverage gap (ADR-0002).
3908                        ingest_peer_commitment(
3909                            peer,
3910                            outcome.response.commitment.as_ref(),
3911                            &p2p,
3912                            &last_commitment_by_peer,
3913                            &ever_capable_peers,
3914                            &sig_verify_attempts,
3915                        )
3916                        .await; // sig_verify_attempts in scope from line ~1080
3917
3918                        if !outcome.response.bootstrapping {
3919                            record_sent_replica_hints(
3920                                peer,
3921                                &outcome.sent_replica_hints,
3922                                &repair_proofs,
3923                                &sync_cycle_epoch,
3924                            )
3925                            .await;
3926                        }
3927                    }
3928                }
3929
3930                let pending_keys: HashSet<XorName> = {
3931                    let q = queues.read().await;
3932                    q.pending_keys().into_iter().collect()
3933                };
3934                let admission_futures = completed.iter().map(|(_, outcome)| async {
3935                    match outcome {
3936                        Some(outcome) if !outcome.response.bootstrapping => Some(
3937                            admission::admit_hints(
3938                                &self_id,
3939                                &outcome.response.replica_hints,
3940                                &outcome.response.paid_hints,
3941                                &p2p,
3942                                &config,
3943                                &storage,
3944                                &paid_list,
3945                                &pending_keys,
3946                            )
3947                            .await,
3948                        ),
3949                        _ => None,
3950                    }
3951                });
3952                let admitted = join_all(admission_futures).await;
3953
3954                // Queue every peer's admitted hints under one write lock. Once
3955                // released, source-count ordering sees the complete batch.
3956                let (batch_outcomes, batch_discovered) = {
3957                    let mut q = queues.write().await;
3958                    let outcomes = completed
3959                        .iter()
3960                        .zip(admitted)
3961                        .filter_map(|((peer, _), admitted)| {
3962                            admitted.map(|admitted| {
3963                                (
3964                                    *peer,
3965                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
3966                                )
3967                            })
3968                        })
3969                        .collect::<Vec<_>>();
3970                    let live_discovered = outcomes
3971                        .iter()
3972                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3973                        .filter(|key| q.contains_key(key))
3974                        .collect::<HashSet<_>>();
3975                    (outcomes, live_discovered)
3976                };
3977
3978                publish_bootstrap_admission_outcomes(
3979                    &bootstrap_state,
3980                    &batch_outcomes,
3981                    &batch_discovered,
3982                )
3983                .await;
3984
3985                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
3986            }
3987
3988            // Check drain condition.
3989            {
3990                let q = queues.read().await;
3991                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
3992                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3993                }
3994            }
3995
3996            info!("Bootstrap sync completed");
3997        });
3998        self.task_handles.push(handle);
3999    }
4000}
4001
4002// ===========================================================================
4003// Free functions for background tasks
4004// ===========================================================================
4005
4006#[cfg(feature = "logging")]
4007fn log_audit_responder_summary(
4008    metrics: &AuditResponderMetrics,
4009    semaphore: &Semaphore,
4010    window: Duration,
4011) {
4012    let snapshot = metrics.take_snapshot();
4013    if snapshot.origins.is_empty() {
4014        return;
4015    }
4016
4017    let total = snapshot.total;
4018    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4019        total.received_by_class;
4020    let global_inflight =
4021        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4022    info!(
4023        target: "ant_node::replication::audit_responder",
4024        window_ms = window.as_millis(),
4025        source_count = snapshot.origins.len(),
4026        received = total.received(),
4027        digest_received,
4028        subtree_received,
4029        byte_received,
4030        commitment_pin_received,
4031        admitted = total.admitted,
4032        global_pool_drops = total.global_pool_drops,
4033        per_peer_cap_drops = total.per_peer_cap_drops,
4034        serial_queue_drops = total.serial_queue_drops,
4035        completed = total.completed,
4036        send_failures = total.send_failures,
4037        processing_avg_ms = total.processing_avg_ms(),
4038        processing_max_ms = total.processing_max_ms,
4039        total_avg_ms = total.total_avg_ms(),
4040        total_max_ms = total.total_max_ms,
4041        global_inflight,
4042        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4043        peak_global_inflight = total.peak_global_inflight,
4044        "Audit responder summary"
4045    );
4046
4047    for (index, origin) in snapshot
4048        .origins
4049        .iter()
4050        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4051        .enumerate()
4052    {
4053        let Some(source) = origin.source else {
4054            continue;
4055        };
4056        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4057            origin.received_by_class;
4058        info!(
4059            target: "ant_node::replication::audit_responder",
4060            rank = index + 1,
4061            source = %source,
4062            received = origin.received(),
4063            digest_received,
4064            subtree_received,
4065            byte_received,
4066            commitment_pin_received,
4067            admitted = origin.admitted,
4068            global_pool_drops = origin.global_pool_drops,
4069            per_peer_cap_drops = origin.per_peer_cap_drops,
4070            serial_queue_drops = origin.serial_queue_drops,
4071            completed = origin.completed,
4072            send_failures = origin.send_failures,
4073            processing_avg_ms = origin.processing_avg_ms(),
4074            processing_max_ms = origin.processing_max_ms,
4075            total_avg_ms = origin.total_avg_ms(),
4076            total_max_ms = origin.total_max_ms,
4077            peak_global_inflight = origin.peak_global_inflight,
4078            peak_peer_inflight = origin.peak_peer_inflight,
4079            "Audit responder top origin"
4080        );
4081    }
4082}
4083
4084/// Which ceiling rejected an audit-responder admission attempt.
4085///
4086/// Stable, machine-readable so a production log-scrape can bucket drops by
4087/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4088/// single opaque "capacity reached" line; this splits the two distinct causes
4089/// so the next such investigation can tell a global-pool exhaustion (the whole
4090/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4091/// without re-instrumenting.
4092///
4093/// This branch runs a SINGLE shared audit-responder pool for all challenge
4094/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4095/// pool to distinguish here — the `kind=` log field already separates the
4096/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4097/// dedicated slow pool is later split out, add its variants here.
4098#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4099enum ResponderRejectReason {
4100    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4101    /// free; the per-peer cap was not the binding constraint.
4102    GlobalPoolFull,
4103    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4104    /// share, so the global permit was never attempted.
4105    PerPeerCapFull,
4106}
4107
4108impl ResponderRejectReason {
4109    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4110    /// frozen — production log tooling greps for them.
4111    fn as_str(self) -> &'static str {
4112        match self {
4113            Self::GlobalPoolFull => "global_pool_full",
4114            Self::PerPeerCapFull => "per_peer_cap_full",
4115        }
4116    }
4117}
4118
4119impl From<ResponderRejectReason> for AuditResponderDropReason {
4120    fn from(reason: ResponderRejectReason) -> Self {
4121        match reason {
4122            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4123            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4124        }
4125    }
4126}
4127
4128impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4129    fn from(reason: ResponderRejectReason) -> Self {
4130        match reason {
4131            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4132            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4133        }
4134    }
4135}
4136
4137/// Cumulative fresh-offer admission refusals in this process.
4138///
4139/// **Expected value in healthy operation is zero.** A node that refuses a
4140/// legitimate fresh offer does not merely shed load: the sender transmits
4141/// offers one-way and never reads the refusal, so the chunk's absence
4142/// resurfaces at the sender's delayed possession check and is charged to the
4143/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4144/// means the node is either under-provisioned for its offered load or its
4145/// admission share is mis-sized — and is accruing unearned trust damage either
4146/// way. Operators should alarm on any sustained non-zero rate.
4147///
4148/// Process-global rather than per-engine, which is exactly right in production
4149/// (one node per process) and adequate in multi-node test harnesses, where the
4150/// useful assertion is that *no* node in the fleet refused.
4151#[must_use]
4152pub fn fresh_offer_admission_refusals() -> u64 {
4153    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4154}
4155
4156/// Cumulative paid-list notification admission refusals in this process.
4157///
4158/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4159/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4160/// paid-list evidence outright rather than pushing work back onto a requester.
4161#[must_use]
4162pub fn paid_notify_admission_refusals() -> u64 {
4163    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4164}
4165
4166/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4167///
4168/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4169/// different things: this one says the node was saturated across all sources
4170/// and is genuinely under-provisioned for its offered load.
4171#[must_use]
4172pub fn fresh_offer_refusals_global_pool() -> u64 {
4173    audit_metrics::responder_admission_drops_by_ceiling(
4174        ReplicationResponderClass::FreshOffer,
4175        ResponderAdmissionCeiling::GlobalPool,
4176    )
4177}
4178
4179/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4180///
4181/// For fresh offers this usually indicts the *share's size* rather than the
4182/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4183/// node handling a client's PUT and fanning it out — so a share sized for
4184/// request/response traffic will refuse ordinary uploads.
4185#[must_use]
4186pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4187    audit_metrics::responder_admission_drops_by_ceiling(
4188        ReplicationResponderClass::FreshOffer,
4189        ResponderAdmissionCeiling::PerPeerShare,
4190    )
4191}
4192
4193/// Why an audit-responder admission attempt failed, with the decision-time
4194/// capacity counters that let a drop be logged with full context.
4195///
4196/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4197/// decision was made (the two ceilings are read under different locks, so they
4198/// are not a single atomic view), but they are exact enough to tell a saturated
4199/// node from a single self-throttling flooder.
4200#[derive(Debug, Clone, Copy)]
4201struct ResponderAdmissionFailure {
4202    reason: ResponderRejectReason,
4203    /// Global permits in use across the whole engine at decision time.
4204    global_inflight: usize,
4205    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4206    global_limit: usize,
4207    /// In-flight audit responders already held for `source` at decision time.
4208    peer_inflight: u32,
4209    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4210    peer_limit: u32,
4211}
4212
4213impl fmt::Display for ResponderAdmissionFailure {
4214    /// Renders the stable `reason=... global_inflight=... global_limit=...
4215    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4217        write!(
4218            f,
4219            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4220            self.reason.as_str(),
4221            self.global_inflight,
4222            self.global_limit,
4223            self.peer_inflight,
4224            self.peer_limit,
4225        )
4226    }
4227}
4228
4229/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4230/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4231/// spawned task ties both bounds to the task's exact lifetime — no manual
4232/// decrement to forget on an early return or panic.
4233struct ResponderGuard {
4234    _permit: tokio::sync::OwnedSemaphorePermit,
4235    _peer_slot: PeerResponderSlot,
4236    global_inflight: usize,
4237    peer_inflight: u32,
4238}
4239
4240type AuditResponderGuard = ResponderGuard;
4241type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4242
4243/// Provisional or admitted per-peer responder slot.
4244///
4245/// The slot is claimed before the global permit is attempted. Keeping that
4246/// claim under RAII means cancellation while rolling a failed admission back
4247/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4248/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4249struct PeerResponderSlot {
4250    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4251    peer: PeerId,
4252}
4253
4254#[derive(Clone)]
4255struct ReplicationMessageHandlerContext {
4256    p2p_node: Arc<P2PNode>,
4257    storage: Arc<LmdbStorage>,
4258    paid_list: Arc<PaidList>,
4259    payment_verifier: Arc<PaymentVerifier>,
4260    queues: Arc<RwLock<ReplicationQueues>>,
4261    config: Arc<ReplicationConfig>,
4262    is_bootstrapping: Arc<RwLock<bool>>,
4263    bootstrap_state: Arc<RwLock<BootstrapState>>,
4264    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4265    sync_cycle_epoch: Arc<RwLock<u64>>,
4266    repair_proofs: Arc<RwLock<RepairProofs>>,
4267    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4268    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4269    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4270    my_commitment_state: Arc<ResponderCommitmentState>,
4271    gossip_audit: GossipAuditTrigger,
4272    audit_responder_semaphore: Arc<Semaphore>,
4273    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4274    audit_responder_metrics: Arc<AuditResponderMetrics>,
4275    subtree_round1: SubtreeRound1Limiter,
4276    fetch_responder_worker_semaphore: Arc<Semaphore>,
4277    fetch_responder_admission_semaphore: Arc<Semaphore>,
4278    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4279    verification_responder_worker_semaphore: Arc<Semaphore>,
4280    verification_responder_admission_semaphore: Arc<Semaphore>,
4281    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4282    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4283    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4284    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4285    fresh_offer_worker_semaphore: Arc<Semaphore>,
4286    fresh_offer_admission_semaphore: Arc<Semaphore>,
4287    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4288    fresh_offer_in_flight: FreshOfferInFlight,
4289    paid_notify_worker_semaphore: Arc<Semaphore>,
4290    paid_notify_admission_semaphore: Arc<Semaphore>,
4291    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4292    /// The engine's shutdown token, for detached responder work.
4293    ///
4294    /// Workers on [`Self::detached_task_tracker`] race this around their
4295    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4296    /// where dropping the awaiter would detach a live transaction. This is
4297    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4298    /// terminate: the wait stays safe because it is now guaranteed finite.
4299    shutdown: CancellationToken,
4300    /// Shared tracker for detached work so `shutdown()` can await release of
4301    /// storage and P2P resources after all producer tasks have stopped.
4302    detached_task_tracker: TaskTracker,
4303}
4304
4305struct InboundReplicationMessage {
4306    source: PeerId,
4307    msg: ReplicationMessage,
4308    rr_message_id: Option<String>,
4309    received_at: Instant,
4310}
4311
4312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4313enum SerialQueueDropReason {
4314    Full,
4315    Closed,
4316}
4317
4318#[cfg(feature = "logging")]
4319impl SerialQueueDropReason {
4320    const fn as_str(self) -> &'static str {
4321        match self {
4322            Self::Full => "full",
4323            Self::Closed => "closed",
4324        }
4325    }
4326}
4327
4328#[derive(Debug, Clone, Copy)]
4329#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4330struct SerialQueueDrop {
4331    source: PeerId,
4332    message_class: &'static str,
4333    audit_responder_class: Option<AuditResponderClass>,
4334    queue_depth: usize,
4335    reason: SerialQueueDropReason,
4336}
4337
4338fn try_enqueue_serial_message(
4339    sender: &mpsc::Sender<InboundReplicationMessage>,
4340    inbound: InboundReplicationMessage,
4341) -> std::result::Result<(), SerialQueueDrop> {
4342    let source = inbound.source;
4343    let message_class = replication_message_class(&inbound.msg.body);
4344    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4345    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4346    sender.try_send(inbound).map_err(|error| {
4347        let (reason, dropped) = match error {
4348            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4349            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4350        };
4351        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4352        SerialQueueDrop {
4353            source,
4354            message_class,
4355            audit_responder_class,
4356            queue_depth,
4357            reason,
4358        }
4359    })
4360}
4361
4362const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4363    match body {
4364        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4365        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4366        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4367        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4368        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4369        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4370        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4371        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4372        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4373        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4374        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4375        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4376        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4377        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4378        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4379        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4380        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4381    }
4382}
4383
4384const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4385    match body {
4386        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4387        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4388        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4389        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4390        _ => None,
4391    }
4392}
4393
4394impl AuditResponderClass {
4395    const fn per_peer_limit(self) -> u32 {
4396        match self {
4397            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4398            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4399        }
4400    }
4401}
4402
4403fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4404    match error {
4405        RecvError::Lagged(missed) => {
4406            audit_metrics::record_replication_event_lagged(*missed);
4407            warn!(
4408                "Missed {missed} P2P events on replication branch (broadcast lag); \
4409                 replication messages may have been dropped before dispatch"
4410            );
4411            ControlFlow::Continue(())
4412        }
4413        RecvError::Closed => {
4414            // A closed broadcast channel never yields again, so the branch
4415            // would otherwise be immediately ready on every select! iteration.
4416            warn!("P2P event stream closed on replication branch; stopping message handler");
4417            ControlFlow::Break(())
4418        }
4419    }
4420}
4421
4422fn replication_payload_from_event(
4423    event: P2PEvent,
4424) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4425    let P2PEvent::Message {
4426        topic,
4427        source: Some(source),
4428        data,
4429        ..
4430    } = event
4431    else {
4432        return None;
4433    };
4434
4435    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4436    if !is_rr {
4437        return Some((source, data, matched_id, None));
4438    }
4439    if is_rr {
4440        return P2PNode::parse_request_envelope(&data)
4441            .filter(|(_, is_resp, _)| !is_resp)
4442            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4443    }
4444    None
4445}
4446
4447impl Drop for PeerResponderSlot {
4448    fn drop(&mut self) {
4449        // Decrement (and prune to keep the map bounded) without blocking the
4450        // async runtime: a short lock on a tiny map.
4451        //
4452        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4453        // with no spawn. Otherwise defer to a task — but only if a runtime is
4454        // actually current, so `Drop` during shutdown (no runtime) can never
4455        // panic. A missed decrement at shutdown is harmless: the whole map is
4456        // being dropped with the engine.
4457        let peer = self.peer;
4458        if let Ok(mut map) = self.inflight.try_write() {
4459            if let Some(n) = map.get_mut(&peer) {
4460                *n = n.saturating_sub(1);
4461                if *n == 0 {
4462                    map.remove(&peer);
4463                }
4464            }
4465            return;
4466        }
4467        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4468            let inflight = Arc::clone(&self.inflight);
4469            handle.spawn(async move {
4470                let mut map = inflight.write().await;
4471                if let Some(n) = map.get_mut(&peer) {
4472                    *n = n.saturating_sub(1);
4473                    if *n == 0 {
4474                        map.remove(&peer);
4475                    }
4476                }
4477            });
4478        }
4479    }
4480}
4481
4482/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4483/// and then a global permit. The limits are parameters so independent responder
4484/// classes can reuse the same flood-fair admission and cancellation semantics.
4485async fn admit_bounded_responder(
4486    semaphore: &Arc<Semaphore>,
4487    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4488    source: &PeerId,
4489    global_limit: usize,
4490    peer_limit: u32,
4491) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4492    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4493
4494    let admitted_peer_inflight = {
4495        let mut map = inflight.write().await;
4496        let entry = map.entry(*source).or_insert(0);
4497        if *entry >= peer_limit {
4498            let peer_inflight = *entry;
4499            drop(map);
4500            return Err(ResponderAdmissionFailure {
4501                reason: ResponderRejectReason::PerPeerCapFull,
4502                global_inflight: global_inflight(semaphore),
4503                global_limit,
4504                peer_inflight,
4505                peer_limit,
4506            });
4507        }
4508        *entry += 1;
4509        *entry
4510    };
4511
4512    let peer_slot = PeerResponderSlot {
4513        inflight: Arc::clone(inflight),
4514        peer: *source,
4515    };
4516    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4517        return Err(ResponderAdmissionFailure {
4518            reason: ResponderRejectReason::GlobalPoolFull,
4519            global_inflight: global_inflight(semaphore),
4520            global_limit,
4521            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4522            peer_limit,
4523        });
4524    };
4525
4526    Ok(ResponderGuard {
4527        _permit: permit,
4528        _peer_slot: peer_slot,
4529        global_inflight: global_inflight(semaphore),
4530        peer_inflight: admitted_peer_inflight,
4531    })
4532}
4533
4534/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4535struct SubtreeSession {
4536    commitment_hash: [u8; 32],
4537    nonce: [u8; 32],
4538    inserted: Instant,
4539}
4540
4541/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4542/// read and hash, refilled continuously at
4543/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4544/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4545///
4546/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4547/// identity may ask, so it is refilled by acquiring more identities; this is
4548/// charged for work done regardless of who asked, so it is not.
4549///
4550/// Charged after the fact, with the bytes the proof actually covered: the cost
4551/// of a request is not known until the pinned commitment has been resolved and
4552/// its subtree selected, both of which happen inside the handler. Admission
4553/// therefore asks only whether the balance is positive, and a proof that costs
4554/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4555/// Carrying the debt is what makes the bound real: without it a maximal proof
4556/// would cost the same as a trivial one, since either way the next request only
4557/// has to wait for the balance to climb back above zero. With it, sustained
4558/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4559/// admitted proportionally less often.
4560struct Round1WorkBudget {
4561    /// Signed, so an over-large proof leaves debt to work off.
4562    balance: i64,
4563    last_refill: Instant,
4564}
4565
4566impl Round1WorkBudget {
4567    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4568    /// for longer than the burst takes to refill.
4569    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4570    /// Nanoseconds per second, for the sub-second part of a refill.
4571    const NANOS_PER_SEC: i64 = 1_000_000_000;
4572
4573    fn new() -> Self {
4574        Self {
4575            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4576            last_refill: Instant::now(),
4577        }
4578    }
4579
4580    /// Add the tokens accrued since the last touch, capped at the burst size.
4581    fn refill(&mut self, now: Instant) {
4582        let elapsed = now.saturating_duration_since(self.last_refill);
4583        self.last_refill = now;
4584        let whole_secs = i64::try_from(elapsed.as_secs())
4585            .unwrap_or(i64::MAX)
4586            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4587        let sub_sec = i64::from(elapsed.subsec_nanos())
4588            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4589            / Self::NANOS_PER_SEC;
4590        self.balance = self
4591            .balance
4592            .saturating_add(whole_secs.saturating_add(sub_sec))
4593            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4594    }
4595
4596    /// Whether budget remains for a new round-1 proof.
4597    fn has_budget(&mut self, now: Instant) -> bool {
4598        self.refill(now);
4599        self.balance > 0
4600    }
4601
4602    /// Charge `bytes` of completed proof work, carrying debt down to
4603    /// [`Self::MAX_DEBT`].
4604    fn charge(&mut self, bytes: i64, now: Instant) {
4605        self.refill(now);
4606        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4607    }
4608}
4609
4610/// Resource controls for the HEAVY subtree-audit round 1: a tight
4611/// admission pool separate from the light responsible/slice audits, a per-peer
4612/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4613/// challenge is only served after a matching round 1.
4614///
4615/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4616/// bounds not keyed by peer identity, and so the only one that bounds sustained
4617/// work rather than concurrency or per-identity frequency.
4618#[derive(Clone)]
4619struct SubtreeRound1Limiter {
4620    semaphore: Arc<Semaphore>,
4621    /// Global ceiling on concurrent round-1 proofs (config-driven;
4622    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4623    /// semaphore because the per-peer admission helper needs the same number.
4624    max_concurrent: usize,
4625    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4626    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4627    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4628    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4629    cooldown_interval: Duration,
4630    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4631    /// Identity-independent ceiling on sustained round-1 work.
4632    work: Arc<RwLock<Round1WorkBudget>>,
4633}
4634
4635impl SubtreeRound1Limiter {
4636    /// `max_concurrent` of 0 would wedge the responder into refusing every
4637    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4638    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4639    /// rather than to off.
4640    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4641        let max_concurrent = max_concurrent.max(1);
4642        Self {
4643            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4644            max_concurrent,
4645            inflight: Arc::new(RwLock::new(HashMap::new())),
4646            cooldown: Arc::new(RwLock::new(HashMap::new())),
4647            cooldown_interval,
4648            sessions: Arc::new(RwLock::new(HashMap::new())),
4649            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4650        }
4651    }
4652
4653    /// Charge completed round-1 proof work against the responder-wide budget.
4654    async fn charge_work(&self, content_bytes: i64) {
4655        self.work
4656            .write()
4657            .await
4658            .charge(content_bytes, Instant::now());
4659    }
4660
4661    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4662    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4663    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4664    /// drops the challenge (the remote auditor applies its own graced-timeout
4665    /// policy).
4666    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4667        let guard = admit_bounded_responder(
4668            &self.semaphore,
4669            &self.inflight,
4670            source,
4671            self.max_concurrent,
4672            MAX_SUBTREE_ROUND1_PER_PEER,
4673        )
4674        .await
4675        .ok()?;
4676        // Checked before the per-peer cooldown is stamped, so a peer refused for
4677        // want of budget is not also charged its next allowance.
4678        if !self.work.write().await.has_budget(Instant::now()) {
4679            return None; // guard drops here, releasing the permit + slot
4680        }
4681        let now = Instant::now();
4682        let mut cooldown = self.cooldown.write().await;
4683        if let Some(&last) = cooldown.get(source) {
4684            if now.duration_since(last) < self.cooldown_interval {
4685                return None; // guard drops here, releasing the permit + slot
4686            }
4687        }
4688        // Evict lapsed entries (their cooldown has expired, so they no longer
4689        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4690        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4691        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4692            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4693                cooldown.remove(&oldest);
4694            }
4695        }
4696        cooldown.insert(*source, now);
4697        Some(guard)
4698    }
4699
4700    /// Record a single-use session once a round-1 proof is built and about to be
4701    /// sent, so the matching round 2 is admitted exactly once.
4702    async fn open_session(
4703        &self,
4704        source: PeerId,
4705        challenge_id: u64,
4706        commitment_hash: [u8; 32],
4707        nonce: [u8; 32],
4708    ) {
4709        let now = Instant::now();
4710        let mut sessions = self.sessions.write().await;
4711        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4712        if sessions.len() >= MAX_SUBTREE_SESSIONS {
4713            if let Some(oldest) = sessions
4714                .iter()
4715                .min_by_key(|(_, e)| e.inserted)
4716                .map(|(k, _)| *k)
4717            {
4718                sessions.remove(&oldest);
4719            }
4720        }
4721        sessions.insert(
4722            (source, challenge_id),
4723            SubtreeSession {
4724                commitment_hash,
4725                nonce,
4726                inserted: now,
4727            },
4728        );
4729    }
4730
4731    /// Atomically consume the round-2 session for this exchange. `true` iff a
4732    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4733    /// existed (and is now removed); a miss silently drops round 2 to the graced
4734    /// timeout lane (sessions are ephemeral and can be lost across a restart).
4735    async fn consume_session(
4736        &self,
4737        source: &PeerId,
4738        challenge_id: u64,
4739        commitment_hash: &[u8; 32],
4740        nonce: &[u8; 32],
4741    ) -> bool {
4742        let mut sessions = self.sessions.write().await;
4743        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4744            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4745                && &e.commitment_hash == commitment_hash
4746                && &e.nonce == nonce
4747        });
4748        if matches {
4749            sessions.remove(&(*source, challenge_id));
4750        }
4751        matches
4752    }
4753}
4754
4755/// Outcome of admitting a round-2 slice challenge.
4756enum SliceAdmission {
4757    /// Admitted: the guard holds the global permit and the per-peer slot, and
4758    /// the single-use round-1 session has been consumed.
4759    Admitted(AuditResponderGuard),
4760    /// Refused at a responder ceiling. The round-1 session is left INTACT.
4761    Capacity(AuditResponderAdmissionFailure),
4762    /// No live round-1 session matched this challenge.
4763    NoSession,
4764}
4765
4766/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4767/// the single-use round-1 session.
4768///
4769/// The order is the point: a single-use token must not be spent on work that is
4770/// then refused. Consuming first and testing admission second leaves the session
4771/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4772/// even in principle.
4773///
4774/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4775/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4776/// auditor does not currently re-send round 2 within an audit. The preserved
4777/// session is therefore not yet *recovering* an audit — it keeps a refusal
4778/// truthful (temporary means temporary) and keeps the invariant available for a
4779/// retry, rather than baking "capacity drop is permanent" into the state
4780/// machine. If an application-level retry is ruled out for good, this ordering
4781/// still costs nothing over the alternative.
4782///
4783/// Cost of the ordering: the permit and per-peer slot are held across the
4784/// session probe, which is one in-memory map lookup and no chunk work. The
4785/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4786/// share it could already occupy with well-formed ones, so the admission
4787/// surface is unchanged.
4788async fn admit_slice_challenge(
4789    semaphore: &Arc<Semaphore>,
4790    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4791    round1: &SubtreeRound1Limiter,
4792    source: &PeerId,
4793    challenge: &protocol::SubtreeSliceChallenge,
4794) -> SliceAdmission {
4795    let guard =
4796        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4797            Ok(guard) => guard,
4798            Err(failure) => return SliceAdmission::Capacity(failure),
4799        };
4800    if !round1
4801        .consume_session(
4802            source,
4803            challenge.challenge_id,
4804            &challenge.expected_commitment_hash,
4805            &challenge.nonce,
4806        )
4807        .await
4808    {
4809        // Release the permit and per-peer slot before the caller replies: no
4810        // chunk work follows, so holding them would shrink the pool for nothing.
4811        drop(guard);
4812        return SliceAdmission::NoSession;
4813    }
4814    SliceAdmission::Admitted(guard)
4815}
4816
4817/// Try to admit one audit-responder task for `source`: take a global permit AND
4818/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4819/// its decision-time counters (caller drops the challenge, leaving the remote
4820/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4821/// so one flooder can neither exhaust the global pool's effect on others nor
4822/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4823/// log exactly WHY the drop happened rather than a single opaque "capacity
4824/// reached".
4825async fn admit_audit_responder(
4826    semaphore: &Arc<Semaphore>,
4827    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4828    source: &PeerId,
4829    class: AuditResponderClass,
4830) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4831    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4832    let peer_limit = class.per_peer_limit();
4833    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4834}
4835
4836/// Handle an incoming replication protocol message.
4837///
4838/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4839/// request-response path and the response must be sent via `send_response`
4840/// so saorsa-core can route it back to the waiting `send_request` caller.
4841#[allow(clippy::too_many_lines)]
4842async fn handle_replication_message(
4843    source: &PeerId,
4844    msg: ReplicationMessage,
4845    ctx: &ReplicationMessageHandlerContext,
4846    received_at: Instant,
4847    rr_message_id: Option<&str>,
4848) -> Result<()> {
4849    match msg.body {
4850        ReplicationMessageBody::FreshReplicationOffer(offer) => {
4851            dispatch_fresh_offer(
4852                *source,
4853                offer,
4854                ctx,
4855                msg.request_id,
4856                received_at,
4857                rr_message_id,
4858            )
4859            .await
4860        }
4861        ReplicationMessageBody::PaidNotify(notify) => {
4862            dispatch_paid_notify(*source, notify, ctx, received_at).await
4863        }
4864        ReplicationMessageBody::NeighborSyncRequest(request) => {
4865            let bootstrapping = *ctx.is_bootstrapping.read().await;
4866            // Phase-3 storage-bound audit: store the sender's
4867            // commitment for use as `expected_commitment_hash` in
4868            // future audits. Verify signature before storing so a peer
4869            // cannot inject a forged commitment for someone else.
4870            if let Some(target) = ingest_peer_commitment(
4871                source,
4872                request.commitment.as_ref(),
4873                &ctx.p2p_node,
4874                &ctx.last_commitment_by_peer,
4875                &ctx.ever_capable_peers,
4876                &ctx.sig_verify_attempts,
4877            )
4878            .await
4879            {
4880                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4881            }
4882            dispatch_neighbor_sync_request(
4883                *source,
4884                request,
4885                ctx,
4886                bootstrapping,
4887                // Atomically snapshot + mark-gossiped: emitted in the sync
4888                // response, so we must stay answerable for it (ADR-0002).
4889                ctx.my_commitment_state
4890                    .current_for_gossip()
4891                    .map(|b| b.commitment().clone()),
4892                msg.request_id,
4893                received_at,
4894                rr_message_id,
4895            )
4896            .await
4897        }
4898        ReplicationMessageBody::VerificationRequest(request) => {
4899            dispatch_verification_request(
4900                *source,
4901                request,
4902                ctx,
4903                msg.request_id,
4904                received_at,
4905                rr_message_id,
4906            )
4907            .await
4908        }
4909        ReplicationMessageBody::FetchRequest(request) => {
4910            dispatch_fetch_request(
4911                *source,
4912                request,
4913                ctx,
4914                msg.request_id,
4915                received_at,
4916                rr_message_id,
4917            )
4918            .await
4919        }
4920        ReplicationMessageBody::AuditChallenge(challenge) => {
4921            // Responsible-chunk audit (audit #2) responder: answer with per-key
4922            // possession digests. This same handler also answers the
4923            // prune-confirmation audit, which sends the same `AuditChallenge`
4924            // wire message.
4925            //
4926            // Answering digests the stored bytes of every challenged key, so —
4927            // like the subtree/byte audits below — run it on a detached task off
4928            // this serial message loop. Handling it inline lets one challenge
4929            // block all other replication traffic until its digests complete
4930            // (head-of-line blocking). The same flood-fair admission applies: a
4931            // global ceiling AND a per-peer cap, dropping the challenge if either
4932            // is hit. A dropped challenge reads as a penalised timeout to the
4933            // auditor, so the caps must remain high enough for honest audit load;
4934            // the per-peer share still prevents one flooder from starving others.
4935            let class = AuditResponderClass::Digest;
4936            let guard = match admit_audit_responder(
4937                &ctx.audit_responder_semaphore,
4938                &ctx.audit_responder_inflight,
4939                source,
4940                class,
4941            )
4942            .await
4943            {
4944                Ok(guard) => guard,
4945                Err(failure) => {
4946                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4947                    audit_metrics::record_admission_drop(class);
4948                    ctx.audit_responder_metrics
4949                        .record_drop(*source, failure.reason.into());
4950                    warn!(
4951                        target: "ant_node::replication::audit_responder",
4952                        event = "admission_dropped",
4953                        kind = "responsible",
4954                        responder_class = class.as_str(),
4955                        source = %source,
4956                        challenge_id = challenge.challenge_id,
4957                        key_count = challenge.keys.len(),
4958                        request_response = rr_message_id.is_some(),
4959                        dispatch_ms = received_at.elapsed().as_millis(),
4960                        reason = failure.reason.as_str(),
4961                        global_inflight = failure.global_inflight,
4962                        global_limit = failure.global_limit,
4963                        peer_inflight = failure.peer_inflight,
4964                        peer_limit = failure.peer_limit,
4965                        "Audit responder admission dropped"
4966                    );
4967                    return Ok(());
4968                }
4969            };
4970            let admission_global_inflight = guard.global_inflight;
4971            let admission_peer_inflight = guard.peer_inflight;
4972            ctx.audit_responder_metrics.record_admitted(
4973                *source,
4974                admission_global_inflight,
4975                admission_peer_inflight,
4976            );
4977            info!(
4978                target: "ant_node::replication::audit_responder",
4979                event = "admitted",
4980                kind = "responsible",
4981                responder_class = class.as_str(),
4982                source = %source,
4983                challenge_id = challenge.challenge_id,
4984                key_count = challenge.keys.len(),
4985                request_response = rr_message_id.is_some(),
4986                dispatch_ms = received_at.elapsed().as_millis(),
4987                global_inflight = admission_global_inflight,
4988                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4989                peer_inflight = admission_peer_inflight,
4990                peer_limit = class.per_peer_limit(),
4991                "Audit responder request admitted"
4992            );
4993            let bootstrapping = *ctx.is_bootstrapping.read().await;
4994            let dispatch_latency = received_at.elapsed();
4995            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
4996            debug!(
4997                audit_type = "digest_responder",
4998                dispatch_latency_ms = dispatch_latency.as_millis(),
4999                source = %source,
5000                "Audit challenge dispatch latency measured"
5001            );
5002            let storage = Arc::clone(&ctx.storage);
5003            let p2p_node = Arc::clone(&ctx.p2p_node);
5004            let source = *source;
5005            let request_id = msg.request_id;
5006            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5007            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5008            ctx.detached_task_tracker.spawn(async move {
5009                let _guard = guard; // global permit + per-peer slot, held until done
5010                let worker_started = Instant::now();
5011                match handle_audit_challenge_msg(
5012                    &source,
5013                    &challenge,
5014                    &storage,
5015                    &p2p_node,
5016                    bootstrapping,
5017                    ReplyRoute {
5018                        request_id,
5019                        rr_message_id: rr_message_id.as_deref(),
5020                        protocol: REPLICATION_PROTOCOL_ID,
5021                    },
5022                )
5023                .await
5024                {
5025                    Ok(completion) => log_audit_responder_completion(
5026                        &responder_metrics,
5027                        source,
5028                        class,
5029                        "responsible",
5030                        challenge.challenge_id,
5031                        challenge.keys.len(),
5032                        completion.response_kind,
5033                        completion.sent,
5034                        received_at,
5035                        worker_started,
5036                        completion.processing,
5037                        completion.response_send,
5038                    ),
5039                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5040                }
5041            });
5042            Ok(())
5043        }
5044        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5045            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5046            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5047            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5048            // detached task so this serial message loop is never blocked on disk
5049            // I/O — otherwise one audit stalls all replication traffic (§5).
5050            //
5051            // A bounded, flood-fair admission restores backpressure (codex#1 +
5052            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5053            // we drop this challenge. Subtree auditors grace timeout
5054            // non-responses, so capacity drops throttle flooders without turning
5055            // into trust penalties (and one source cannot starve other peers,
5056            // since its share is capped per-peer).
5057            let class = AuditResponderClass::Subtree;
5058            info!(
5059                "Audit challenge received: kind=subtree source={source} request_response={}",
5060                rr_message_id.is_some(),
5061            );
5062            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5063            // so it uses its own tight admission pool + per-peer rate cooldown,
5064            // separate from the light responsible/slice audits, and a miss silently
5065            // drops (subtree auditors grace timeouts).
5066            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5067                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5068                warn!(
5069                    target: "ant_node::replication::audit_responder",
5070                    event = "admission_dropped",
5071                    kind = "subtree",
5072                    responder_class = class.as_str(),
5073                    source = %source,
5074                    challenge_id = challenge.challenge_id,
5075                    request_response = rr_message_id.is_some(),
5076                    dispatch_ms = received_at.elapsed().as_millis(),
5077                    reason = "heavy_pool_cooldown_or_work_budget",
5078                    "Audit responder admission dropped"
5079                );
5080                return Ok(());
5081            };
5082            let admission_global_inflight = guard.global_inflight;
5083            let admission_peer_inflight = guard.peer_inflight;
5084            ctx.audit_responder_metrics.record_admitted(
5085                *source,
5086                admission_global_inflight,
5087                admission_peer_inflight,
5088            );
5089            info!(
5090                target: "ant_node::replication::audit_responder",
5091                event = "admitted",
5092                kind = "subtree",
5093                responder_class = class.as_str(),
5094                source = %source,
5095                challenge_id = challenge.challenge_id,
5096                request_response = rr_message_id.is_some(),
5097                dispatch_ms = received_at.elapsed().as_millis(),
5098                global_inflight = admission_global_inflight,
5099                global_limit = ctx.subtree_round1.max_concurrent,
5100                peer_inflight = admission_peer_inflight,
5101                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5102                "Audit responder request admitted"
5103            );
5104            let bootstrapping = *ctx.is_bootstrapping.read().await;
5105            let storage = Arc::clone(&ctx.storage);
5106            let p2p_node = Arc::clone(&ctx.p2p_node);
5107            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5108            let source = *source;
5109            let request_id = msg.request_id;
5110            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5111            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5112            let subtree_round1 = ctx.subtree_round1.clone();
5113            ctx.detached_task_tracker.spawn(async move {
5114                let _guard = guard; // global permit + per-peer slot, held until done
5115                let worker_started = Instant::now();
5116                let processing_started = Instant::now();
5117                let storage_commitment_audit::Round1Work {
5118                    response,
5119                    content_bytes,
5120                } = storage_commitment_audit::handle_subtree_challenge_measured(
5121                    &challenge,
5122                    &storage,
5123                    p2p_node.peer_id(),
5124                    bootstrapping,
5125                    Some(&my_commitment_state),
5126                )
5127                .await;
5128                let processing = processing_started.elapsed();
5129                // Charge the work actually done, on EVERY outcome.
5130                //
5131                // This used to charge only the `Proof` arm, reasoning that the
5132                // rejecting paths either read nothing or reflected this node's
5133                // own broken storage. The second half of that was wrong: a
5134                // retained commitment containing one unreadable key still costs
5135                // a full run of reads and keyed-BLAKE3 passes over every leaf
5136                // before it, and then rejects. An attacker who finds such a
5137                // commitment could replay subtrees over it indefinitely for
5138                // free. The per-peer cooldown does not catch that either, since
5139                // it is escapable by rotating identity — the responder-wide
5140                // budget is the only bound that applies, so it has to see the
5141                // work. A zero charge is a no-op, so the untouched paths are
5142                // unaffected.
5143                subtree_round1.charge_work(content_bytes).await;
5144                // A round-1 proof authorizes exactly one matching round 2: open a
5145                // single-use session so a slice challenge cannot be served without
5146                // a live round-1 exchange.
5147                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5148                {
5149                    subtree_round1
5150                        .open_session(
5151                            source,
5152                            challenge.challenge_id,
5153                            challenge.expected_commitment_hash,
5154                            challenge.nonce,
5155                        )
5156                        .await;
5157                }
5158                let response_kind = subtree_audit_response_kind(&response);
5159                let work_items = subtree_audit_response_work_items(&response);
5160                let response_send_started = Instant::now();
5161                let sent = send_replication_response_checked(
5162                    &source,
5163                    &p2p_node,
5164                    request_id,
5165                    ReplicationMessageBody::SubtreeAuditResponse(response),
5166                    rr_message_id.as_deref(),
5167                    None,
5168                )
5169                .await;
5170                let response_send = response_send_started.elapsed();
5171                log_audit_responder_completion(
5172                    &responder_metrics,
5173                    source,
5174                    class,
5175                    "subtree",
5176                    challenge.challenge_id,
5177                    work_items,
5178                    response_kind,
5179                    sent,
5180                    received_at,
5181                    worker_started,
5182                    processing,
5183                    response_send,
5184                );
5185            });
5186            Ok(())
5187        }
5188        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5189            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5190            // block of each auditor-selected spot-check key with a Bao verified
5191            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5192            // build the proofs, so it runs off the serial loop under the light
5193            // audit pool's global and per-peer ceilings.
5194            let class = AuditResponderClass::Byte;
5195            info!(
5196                "Audit challenge received: kind=slice source={source} request_response={}",
5197                rr_message_id.is_some(),
5198            );
5199            let guard = match admit_slice_challenge(
5200                &ctx.audit_responder_semaphore,
5201                &ctx.audit_responder_inflight,
5202                &ctx.subtree_round1,
5203                source,
5204                &challenge,
5205            )
5206            .await
5207            {
5208                SliceAdmission::Admitted(guard) => guard,
5209                SliceAdmission::Capacity(failure) => {
5210                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5211                    audit_metrics::record_admission_drop(class);
5212                    ctx.audit_responder_metrics
5213                        .record_drop(*source, failure.reason.into());
5214                    warn!(
5215                        target: "ant_node::replication::audit_responder",
5216                        event = "admission_dropped",
5217                        kind = "byte",
5218                        responder_class = class.as_str(),
5219                        source = %source,
5220                        challenge_id = challenge.challenge_id,
5221                        key_count = challenge.openings.len(),
5222                        request_response = rr_message_id.is_some(),
5223                        dispatch_ms = received_at.elapsed().as_millis(),
5224                        reason = failure.reason.as_str(),
5225                        global_inflight = failure.global_inflight,
5226                        global_limit = failure.global_limit,
5227                        peer_inflight = failure.peer_inflight,
5228                        peer_limit = failure.peer_limit,
5229                        "Audit responder admission dropped"
5230                    );
5231                    return Ok(());
5232                }
5233                // No live round-1 session: reply with a cheap `Transient` rejection
5234                // rather than dropping silently. Sessions are ephemeral (an honest
5235                // responder that restarts between rounds loses its session), and an
5236                // unanswered `send_request` would make saorsa-core record a
5237                // transport trust failure against that honest responder — an
5238                // ongoing effect, not just a rollout-window one. A `Transient`
5239                // reply routes the auditor to the graced timeout lane (no trust
5240                // penalty; the responder re-earns pinned credit on the next audit)
5241                // and does no chunk work, so it is not a DoS lever.
5242                SliceAdmission::NoSession => {
5243                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5244                    debug!(
5245                        "Slice challenge without a live round-1 session source={source} \
5246                         challenge_id={} → Transient reject",
5247                        challenge.challenge_id
5248                    );
5249                    send_replication_response_checked(
5250                        source,
5251                        &ctx.p2p_node,
5252                        msg.request_id,
5253                        ReplicationMessageBody::SubtreeSliceResponse(
5254                            protocol::SubtreeSliceResponse::Rejected {
5255                                challenge_id: challenge.challenge_id,
5256                                kind: protocol::RejectKind::Transient,
5257                                reason: "no live round-1 session".to_string(),
5258                            },
5259                        ),
5260                        rr_message_id,
5261                        None,
5262                    )
5263                    .await;
5264                    return Ok(());
5265                }
5266            };
5267            let admission_global_inflight = guard.global_inflight;
5268            let admission_peer_inflight = guard.peer_inflight;
5269            ctx.audit_responder_metrics.record_admitted(
5270                *source,
5271                admission_global_inflight,
5272                admission_peer_inflight,
5273            );
5274            info!(
5275                target: "ant_node::replication::audit_responder",
5276                event = "admitted",
5277                kind = "byte",
5278                responder_class = class.as_str(),
5279                source = %source,
5280                challenge_id = challenge.challenge_id,
5281                key_count = challenge.openings.len(),
5282                request_response = rr_message_id.is_some(),
5283                dispatch_ms = received_at.elapsed().as_millis(),
5284                global_inflight = admission_global_inflight,
5285                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5286                peer_inflight = admission_peer_inflight,
5287                peer_limit = class.per_peer_limit(),
5288                "Audit responder request admitted"
5289            );
5290            let bootstrapping = *ctx.is_bootstrapping.read().await;
5291            let storage = Arc::clone(&ctx.storage);
5292            let p2p_node = Arc::clone(&ctx.p2p_node);
5293            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5294            let source = *source;
5295            let request_id = msg.request_id;
5296            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5297            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5298            ctx.detached_task_tracker.spawn(async move {
5299                let _guard = guard; // global permit + per-peer slot, held until done
5300                let worker_started = Instant::now();
5301                let processing_started = Instant::now();
5302                let response = storage_commitment_audit::handle_subtree_slice_challenge(
5303                    &challenge,
5304                    &storage,
5305                    p2p_node.peer_id(),
5306                    bootstrapping,
5307                    Some(&my_commitment_state),
5308                )
5309                .await;
5310                let processing = processing_started.elapsed();
5311                let response_kind = subtree_slice_response_kind(&response);
5312                let response_send_started = Instant::now();
5313                let sent = send_replication_response_checked(
5314                    &source,
5315                    &p2p_node,
5316                    request_id,
5317                    ReplicationMessageBody::SubtreeSliceResponse(response),
5318                    rr_message_id.as_deref(),
5319                    None,
5320                )
5321                .await;
5322                let response_send = response_send_started.elapsed();
5323                log_audit_responder_completion(
5324                    &responder_metrics,
5325                    source,
5326                    class,
5327                    "byte",
5328                    challenge.challenge_id,
5329                    challenge.openings.len(),
5330                    response_kind,
5331                    sent,
5332                    received_at,
5333                    worker_started,
5334                    processing,
5335                    response_send,
5336                );
5337            });
5338            Ok(())
5339        }
5340        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5341            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5342            // only. `lookup_by_hash` is an allocation-light read over the
5343            // bounded slot set; it returns the live current commitment or any
5344            // still-answerable recently-gossiped/quoted one. A miss is reported
5345            // as `NotRetained` (graced, never confirmed) rather than an error,
5346            // so an aged-out pin can never brand an honest node.
5347            //
5348            // Reuse the audit-responder admission guard (global ceiling + per-peer
5349            // cap) so a flood of fetches cannot drive unbounded commitment
5350            // clone/encode/send work; over-limit is dropped, which the fetching
5351            // peer graces exactly like a missed audit response.
5352            let class = AuditResponderClass::CommitmentPin;
5353            let guard = match admit_audit_responder(
5354                &ctx.audit_responder_semaphore,
5355                &ctx.audit_responder_inflight,
5356                source,
5357                class,
5358            )
5359            .await
5360            {
5361                Ok(guard) => guard,
5362                Err(failure) => {
5363                    audit_metrics::record_admission_drop(class);
5364                    ctx.audit_responder_metrics
5365                        .record_drop(*source, failure.reason.into());
5366                    warn!(
5367                        target: "ant_node::replication::audit_responder",
5368                        event = "admission_dropped",
5369                        kind = "commitment_pin",
5370                        responder_class = class.as_str(),
5371                        source = %source,
5372                        challenge_id = msg.request_id,
5373                        request_response = rr_message_id.is_some(),
5374                        dispatch_ms = received_at.elapsed().as_millis(),
5375                        reason = failure.reason.as_str(),
5376                        global_inflight = failure.global_inflight,
5377                        global_limit = failure.global_limit,
5378                        peer_inflight = failure.peer_inflight,
5379                        peer_limit = failure.peer_limit,
5380                        "Audit responder admission dropped"
5381                    );
5382                    return Ok(());
5383                }
5384            };
5385            ctx.audit_responder_metrics.record_admitted(
5386                *source,
5387                guard.global_inflight,
5388                guard.peer_inflight,
5389            );
5390            info!(
5391                target: "ant_node::replication::audit_responder",
5392                event = "admitted",
5393                kind = "commitment_pin",
5394                responder_class = class.as_str(),
5395                source = %source,
5396                challenge_id = msg.request_id,
5397                request_response = rr_message_id.is_some(),
5398                dispatch_ms = received_at.elapsed().as_millis(),
5399                global_inflight = guard.global_inflight,
5400                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5401                peer_inflight = guard.peer_inflight,
5402                peer_limit = class.per_peer_limit(),
5403                "Audit responder request admitted"
5404            );
5405            let worker_started = Instant::now();
5406            let processing_started = Instant::now();
5407            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5408                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5409                |built| protocol::GetCommitmentByPinResponse::Found {
5410                    commitment: built.commitment().clone(),
5411                },
5412            );
5413            let processing = processing_started.elapsed();
5414            let response_kind = commitment_pin_response_kind(&response);
5415            let response_send_started = Instant::now();
5416            let sent = send_replication_response_checked(
5417                source,
5418                &ctx.p2p_node,
5419                msg.request_id,
5420                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5421                rr_message_id,
5422                None,
5423            )
5424            .await;
5425            let response_send = response_send_started.elapsed();
5426            log_audit_responder_completion(
5427                &ctx.audit_responder_metrics,
5428                *source,
5429                class,
5430                "commitment_pin",
5431                msg.request_id,
5432                1,
5433                response_kind,
5434                sent,
5435                received_at,
5436                worker_started,
5437                processing,
5438                response_send,
5439            );
5440            drop(guard);
5441            Ok(())
5442        }
5443        // Response messages are handled by their respective request initiators.
5444        ReplicationMessageBody::FreshReplicationResponse(_)
5445        | ReplicationMessageBody::NeighborSyncResponse(_)
5446        | ReplicationMessageBody::VerificationResponse(_)
5447        | ReplicationMessageBody::FetchResponse(_)
5448        | ReplicationMessageBody::AuditResponse(_)
5449        | ReplicationMessageBody::SubtreeAuditResponse(_)
5450        | ReplicationMessageBody::SubtreeSliceResponse(_)
5451        | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5452    }
5453}
5454
5455// ---------------------------------------------------------------------------
5456// Per-message-type handlers
5457// ---------------------------------------------------------------------------
5458
5459/// Verify a payment proof, yielding early if the engine is shutting down.
5460///
5461/// Returns `None` when shutdown won the race, meaning no verdict was reached
5462/// and the caller must abandon the message without storing or penalising.
5463///
5464/// Payment verification is pure network I/O — an EVM round trip and, on the
5465/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5466/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5467/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5468/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5469/// is guaranteed to end.
5470///
5471/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5472/// dropping its awaiter would detach a live LMDB transaction and break the
5473/// very contract the unbounded wait exists to uphold.
5474async fn verify_payment_until_shutdown(
5475    payment_verifier: &Arc<PaymentVerifier>,
5476    key: &XorName,
5477    proof_of_payment: &[u8],
5478    context: VerificationContext,
5479    shutdown: &CancellationToken,
5480) -> Option<Result<crate::payment::PaymentStatus>> {
5481    tokio::select! {
5482        () = shutdown.cancelled() => None,
5483        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5484            Some(result)
5485        }
5486    }
5487}
5488
5489/// A fresh offer rejected on payload shape alone.
5490struct FreshOfferRejection {
5491    /// Wire-visible reason returned to the sender.
5492    reason: String,
5493    /// Whether the sender is charged for it. Reserved for offers no honest
5494    /// node would construct, so an ordinary capacity refusal stays free.
5495    penalise: bool,
5496}
5497
5498/// Reject a fresh offer on payload shape, or return `None` to admit it.
5499///
5500/// Pure and non-blocking by construction: these are the checks answerable from
5501/// the payload alone, run on the serial message loop *before* the in-flight
5502/// claim and the admission permit, so a malformed offer can neither lock an
5503/// honest offer out of its key nor occupy one of the scarce
5504/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5505/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5506/// verification — stays on the worker.
5507///
5508/// The content-address hash is deliberately included despite costing real CPU
5509/// on the loop: it is what makes the entry below *earned* rather than merely
5510/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5511/// arrive at link speed, so a flooder can never make this loop hash faster than
5512/// it can deliver the bytes, and delivering them already cost it more than the
5513/// hash costs us. The receive path has in any case already deserialised the
5514/// same buffer.
5515///
5516/// Every rejection here is penalised. These are the conditions no honest sender
5517/// can produce — an absent, undersized, oversized, or non-matching payload — as
5518/// distinct from a capacity refusal, which is this node's own state and stays
5519/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5520/// proof that fails to verify may simply have been read against a lagging chain
5521/// view, and penalising that would charge honest senders in correlated bursts.
5522fn fresh_offer_structural_rejection(
5523    key: &XorName,
5524    data: &[u8],
5525    proof_of_payment: &[u8],
5526) -> Option<FreshOfferRejection> {
5527    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5528    // and an absent proof is the cheapest possible slot-filler, so this is the
5529    // first thing checked.
5530    if proof_of_payment.is_empty() {
5531        return Some(FreshOfferRejection {
5532            reason: "Missing proof of payment".to_string(),
5533            penalise: true,
5534        });
5535    }
5536
5537    // Bound the proof before it can be queued. The verifier applies the same
5538    // limits, but only once the offer reaches a worker — too late here, because
5539    // an entry retains a proof per queued sender, and a proof is capped on the
5540    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5541    // a byte of data and a 10 MiB "proof" would be admitted, and
5542    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5543    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5544    // admission bound exists to enforce.
5545    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5546        return Some(FreshOfferRejection {
5547            reason: format!(
5548                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5549                proof_of_payment.len(),
5550            ),
5551            penalise: true,
5552        });
5553    }
5554    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5555        return Some(FreshOfferRejection {
5556            reason: format!(
5557                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5558                proof_of_payment.len(),
5559            ),
5560            penalise: true,
5561        });
5562    }
5563
5564    // Enforce chunk size invariant: the normal PUT path rejects data larger
5565    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5566    // prevent peers from pushing oversized records through replication.
5567    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5568        return Some(FreshOfferRejection {
5569            reason: format!(
5570                "Data size {} exceeds maximum chunk size {}",
5571                data.len(),
5572                crate::ant_protocol::MAX_CHUNK_SIZE,
5573            ),
5574            penalise: true,
5575        });
5576    }
5577
5578    // Mirror the normal PUT path: the advertised key must be the content
5579    // address of the supplied bytes. Ordered last so an oversized payload is
5580    // refused without being hashed.
5581    //
5582    // This is the check that makes the entry safe to open, and safe for later
5583    // offers to be folded into. Until it passes, the sender has only *asserted*
5584    // an association between the key and the bytes. Opening an entry on an
5585    // assertion would let any peer that knows a key — every recipient of its
5586    // `PaidNotify`, not just the close group — seize it with junk; folding a
5587    // later offer into an entry on an assertion would be worse still, since the
5588    // handler tries each queued proof against the *opener's* bytes and would be
5589    // storing bytes nobody offered for that proof.
5590    let computed_key = crate::client::compute_address(data);
5591    if computed_key != *key {
5592        return Some(FreshOfferRejection {
5593            reason: format!(
5594                "Content address mismatch: expected {}, computed {}",
5595                hex::encode(key),
5596                hex::encode(computed_key),
5597            ),
5598            penalise: true,
5599        });
5600    }
5601
5602    None
5603}
5604
5605/// Tell `source` its offer for `key` was not taken.
5606///
5607/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5608/// one-way `send_message`, so the refusal is observed only as a later absence by
5609/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5610async fn refuse_fresh_offer(
5611    source: &PeerId,
5612    key: XorName,
5613    reason: String,
5614    ctx: &ReplicationMessageHandlerContext,
5615    request_id: u64,
5616    rr_message_id: Option<&str>,
5617) {
5618    send_replication_response(
5619        source,
5620        &ctx.p2p_node,
5621        request_id,
5622        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5623            key,
5624            reason,
5625        }),
5626        rr_message_id,
5627    )
5628    .await;
5629}
5630
5631/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5632/// the sender when the defect is one no honest node could produce.
5633///
5634/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5635/// two say opposite things: this is the sender's fault, that one is ours.
5636async fn refuse_malformed_fresh_offer(
5637    source: &PeerId,
5638    key: XorName,
5639    rejection: FreshOfferRejection,
5640    ctx: &ReplicationMessageHandlerContext,
5641    request_id: u64,
5642    rr_message_id: Option<&str>,
5643) {
5644    if rejection.penalise {
5645        warn!(
5646            "Rejecting fresh offer for key {} from {source}: {}",
5647            hex::encode(key),
5648            rejection.reason
5649        );
5650        ctx.p2p_node
5651            .report_trust_event(
5652                source,
5653                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5654            )
5655            .await;
5656    } else {
5657        debug!(
5658            "Fresh offer for {} from {source} refused before admission: {}",
5659            hex::encode(key),
5660            rejection.reason
5661        );
5662    }
5663    refuse_fresh_offer(
5664        source,
5665        key,
5666        rejection.reason,
5667        ctx,
5668        request_id,
5669        rr_message_id,
5670    )
5671    .await;
5672}
5673
5674/// Tell senders whose proofs joined an entry that was torn down before a handler
5675/// ever ran for it.
5676///
5677/// Only reachable in the window between opening an entry and failing to take an
5678/// admission permit. Their proofs are answered rather than dropped with the
5679/// entry, so the refusal count reflects what actually happened.
5680async fn refuse_stranded_fresh_offers(
5681    key: XorName,
5682    stranded: Vec<FreshOfferAttempt>,
5683    ctx: &ReplicationMessageHandlerContext,
5684) {
5685    for attempt in stranded {
5686        refuse_fresh_offer(
5687            &attempt.source,
5688            key,
5689            "Receiver at fresh-offer capacity".to_string(),
5690            ctx,
5691            attempt.request_id,
5692            attempt.rr_message_id.as_deref(),
5693        )
5694        .await;
5695    }
5696}
5697
5698/// Admit a fresh offer for handling on a worker, or refuse it.
5699///
5700/// This runs on the serial non-audit message loop, so it must stay cheap: every
5701/// path here is a set insert, a permit try, or a small response send. The offer
5702/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5703/// runs on a tracked worker task, never inline, because stalling this loop backs
5704/// up the inbound queue and ultimately drops replication messages wholesale.
5705///
5706/// Admission is bounded **per source** as well as globally
5707/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5708/// hold every slot, and since a refusal is later read as absence by the
5709/// sender's delayed possession check, the resulting refusals land as
5710/// audit-severity penalties on this node rather than on the flooder.
5711///
5712/// The structurally-invalid checks run **before** the entry is opened and before
5713/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5714/// the duration of a payment verification.
5715///
5716/// Only the offer that *opens* an entry costs a permit and a worker. Later
5717/// offers for the same key contribute their proof and are answered by whatever
5718/// the opener's handler concludes, which is what keeps the routine
5719/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5720/// one verification per key.
5721async fn dispatch_fresh_offer(
5722    source: PeerId,
5723    offer: protocol::FreshReplicationOffer,
5724    ctx: &ReplicationMessageHandlerContext,
5725    request_id: u64,
5726    received_at: Instant,
5727    rr_message_id: Option<&str>,
5728) -> Result<()> {
5729    if let Some(rejection) =
5730        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5731    {
5732        refuse_malformed_fresh_offer(
5733            &source,
5734            offer.key,
5735            rejection,
5736            ctx,
5737            request_id,
5738            rr_message_id,
5739        )
5740        .await;
5741        return Ok(());
5742    }
5743
5744    // Join the work already in flight for this key before taking an admission
5745    // permit, so the duplicates a single client PUT produces cost one permit
5746    // between them rather than one each.
5747    //
5748    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5749    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5750    // already held for the key. That is what lets its payload be dropped here
5751    // and only its proof retained: the handler will try that proof against the
5752    // bytes it already has.
5753    let key = offer.key;
5754    let admission_outcome = FreshOfferEntryGuard::admit(
5755        &ctx.fresh_offer_in_flight,
5756        offer,
5757        source,
5758        request_id,
5759        rr_message_id.map(ToOwned::to_owned),
5760        received_at,
5761    );
5762    let mut entry = match admission_outcome {
5763        FreshOfferAdmission::Opened(entry) => entry,
5764        FreshOfferAdmission::Joined => {
5765            // No response yet: this proof has not been judged. The handler that
5766            // owns the key answers every queued sender once it settles.
5767            debug!(
5768                "Fresh offer for {} from {source} queued behind the handler already \
5769                 holding the key",
5770                hex::encode(key)
5771            );
5772            return Ok(());
5773        }
5774        // Surplus, not suspect: the proofs already queued are enough to place
5775        // the record, so neither case is charged as misbehaviour.
5776        surplus => {
5777            debug!(
5778                "Fresh offer for {} from {source} refused: {}",
5779                hex::encode(key),
5780                surplus.surplus_reason()
5781            );
5782            refuse_fresh_offer(
5783                &source,
5784                key,
5785                "Duplicate offer already in flight".to_string(),
5786                ctx,
5787                request_id,
5788                rr_message_id,
5789            )
5790            .await;
5791            return Ok(());
5792        }
5793    };
5794
5795    let admission = match admit_bounded_responder(
5796        &ctx.fresh_offer_admission_semaphore,
5797        &ctx.fresh_offer_responder_inflight,
5798        &source,
5799        FRESH_OFFER_MAX_OUTSTANDING,
5800        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5801    )
5802    .await
5803    {
5804        Ok(guard) => guard,
5805        Err(failure) => {
5806            audit_metrics::record_responder_admission_drop(
5807                ReplicationResponderClass::FreshOffer,
5808                failure.reason.into(),
5809            );
5810            // WARN, not DEBUG: a healthy node should never refuse a legitimate
5811            // fresh offer. The sender does not read this refusal, so it
5812            // resurfaces as a missing key at the delayed possession check and
5813            // is charged to US at audit severity. Log the binding ceiling
5814            // locally; the wire reason stays generic so a probing peer cannot
5815            // map out this node's live occupancy.
5816            warn!(
5817                responder_class = "fresh_offer",
5818                source = %source,
5819                key = %hex::encode(key),
5820                "Fresh offer refused at admission — this node will be penalised                  for the resulting absence: {failure}"
5821            );
5822            // Release the key explicitly rather than on drop, so the next offer
5823            // opens a fresh entry rather than queueing behind a handler that was
5824            // never spawned — and so any proof that joined in the window between
5825            // opening the entry and failing here is answered rather than
5826            // discarded with it.
5827            let stranded = entry.release();
5828            refuse_fresh_offer(
5829                &source,
5830                key,
5831                "Receiver at fresh-offer capacity".to_string(),
5832                ctx,
5833                request_id,
5834                rr_message_id,
5835            )
5836            .await;
5837            refuse_stranded_fresh_offers(key, stranded, ctx).await;
5838            return Ok(());
5839        }
5840    };
5841
5842    let ctx = ctx.clone();
5843    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5844    // an `Arc<LmdbStorage>` while writing, and the shutdown contract requires
5845    // those references be released before the caller reopens the environment.
5846    ctx.detached_task_tracker
5847        .clone()
5848        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5849    Ok(())
5850}
5851
5852/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5853///
5854/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5855/// A started handler is never cancelled: `storage.put()` awaits
5856/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5857/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5858/// and from `handle_fresh_offer` racing the token around payment verification.
5859///
5860/// Works down the key's queued proofs rather than judging the key on the first
5861/// one. A proof that fails to establish payment disqualifies its *sender*, not
5862/// the record: the bytes are content-addressed and identical across every offer,
5863/// so the next sender's proof is tried against the copy already in hand — no
5864/// second payload, no second permit, no refetch. Only when a failure is about
5865/// the key itself (not responsible, no capacity, shutting down) does rotating
5866/// become pointless, because every remaining proof would meet the same wall.
5867async fn run_fresh_offer_worker(
5868    key: XorName,
5869    mut entry: Box<FreshOfferEntryGuard>,
5870    ctx: ReplicationMessageHandlerContext,
5871    admission: ResponderGuard,
5872) {
5873    // The admission permit is released on completion, freeing the payload's
5874    // memory budget and the opening source's per-peer share. The entry releases
5875    // the key itself, either as the queue empties or on drop.
5876    let _admission = admission;
5877    let received_at = entry.received_at();
5878    // Wait for a worker slot here rather than in the caller. The worker bound
5879    // caps concurrent EVM and storage pressure; making the message loop wait on
5880    // it is what put that pressure back on the loop.
5881    //
5882    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5883    // path for offers still queued behind a worker when the engine stops — not
5884    // dead code.
5885    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5886        .acquire_owned()
5887        .await
5888    else {
5889        debug!(
5890            "Fresh offer for {} dropped: worker pool shut down",
5891            hex::encode(key)
5892        );
5893        return;
5894    };
5895    // Fresh offers are fire-and-forget (`send_message`), so there is no
5896    // requester deadline to honour and a late store is still genuinely useful.
5897    // The threshold is the point past which the offer has already cost us what
5898    // it was going to cost: the possession check (ADR-0003) has run by then and
5899    // charged the absence to this node, and it does not re-offer the key —
5900    // repair comes later from neighbor sync. Shedding here trades a copy that
5901    // would have arrived after the penalty for the multi-MiB payload it is
5902    // holding, and keeps a backlog from outliving its own admission bound.
5903    //
5904    // Note this is a memory-pressure decision, not a redundancy one: the copy
5905    // is late, not useless, so on a node with headroom finishing it would still
5906    // beat waiting for neighbor sync.
5907    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5908        debug!(
5909            responder_class = "fresh_offer",
5910            key = %hex::encode(key),
5911            request_age_ms = received_at.elapsed().as_millis(),
5912            "Superseded fresh offer shed at dequeue"
5913        );
5914        return;
5915    }
5916
5917    let mut verdict = FreshOfferOutcome::Abandoned;
5918    while let Some(attempt) = entry.next_attempt() {
5919        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5920            Ok(outcome) => {
5921                verdict = outcome;
5922                match outcome {
5923                    // Settled: the record is down and every remaining sender
5924                    // wanted exactly that. Abandoned: the key cannot be placed
5925                    // by anyone right now, so the proofs behind this one would
5926                    // fail identically. Either way there is nothing left to try.
5927                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5928                    // This sender's claim to have paid did not hold up. Say so
5929                    // to that sender alone and try the next proof.
5930                    FreshOfferOutcome::ProofRejected => {}
5931                }
5932            }
5933            Err(e) => {
5934                debug!(
5935                    "Fresh replication offer for {} from {} error: {e}",
5936                    hex::encode(key),
5937                    attempt.source
5938                );
5939                verdict = FreshOfferOutcome::Abandoned;
5940                break;
5941            }
5942        }
5943    }
5944
5945    // Answer the senders whose proofs were never reached. A stored record is
5946    // what they were asking for, so it is an acceptance even though their own
5947    // proof went untested.
5948    let unreached = entry.release();
5949    if unreached.is_empty() {
5950        return;
5951    }
5952    let response = match verdict {
5953        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5954        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5955            FreshReplicationResponse::Rejected {
5956                key,
5957                reason: "Record could not be stored from any offered proof".to_string(),
5958            }
5959        }
5960    };
5961    for attempt in unreached {
5962        send_replication_response(
5963            &attempt.source,
5964            &ctx.p2p_node,
5965            attempt.request_id,
5966            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5967            attempt.rr_message_id.as_deref(),
5968        )
5969        .await;
5970    }
5971}
5972
5973/// What one proof concluded, and whether another proof for the same key is worth
5974/// trying.
5975///
5976/// The distinction the worker acts on is *what the failure was about*. A
5977/// rejected proof is a statement about its sender; anything else is a statement
5978/// about the key or this node, which no other sender's proof can change.
5979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5980enum FreshOfferOutcome {
5981    /// The record is stored. The key is done.
5982    Settled,
5983    /// This proof did not establish payment. A different sender's proof for the
5984    /// same bytes may still succeed.
5985    ProofRejected,
5986    /// Nothing about this key can succeed right now — not responsible, no disk,
5987    /// shutting down, or a write that failed. Rotating repeats the failure.
5988    Abandoned,
5989}
5990
5991// A linear sequence of protocol steps — structural recheck, responsibility,
5992// capacity, payment, write — each with its own refusal response. Splitting it
5993// would scatter one decision across several functions.
5994#[allow(clippy::too_many_lines)]
5995async fn handle_fresh_offer(
5996    key: &XorName,
5997    data: &[u8],
5998    attempt: &FreshOfferAttempt,
5999    ctx: &ReplicationMessageHandlerContext,
6000) -> Result<FreshOfferOutcome> {
6001    let source = &attempt.source;
6002    let request_id = attempt.request_id;
6003    let rr_message_id = attempt.rr_message_id.as_deref();
6004    let p2p_node = &ctx.p2p_node;
6005    let config = &ctx.config;
6006    let self_id = *p2p_node.peer_id();
6007
6008    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6009    // proof, bad proof size, oversized payload, content-address mismatch —
6010    // before opening the entry or taking an admission permit, so nothing
6011    // reaching a worker should trip them. Kept so the handler is correct in
6012    // isolation. Note this re-checks the *pairing* actually being used: these
6013    // bytes against this attempt's proof.
6014    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6015    {
6016        if rejection.penalise {
6017            warn!(
6018                "Rejecting fresh offer for key {}: {}",
6019                hex::encode(key),
6020                rejection.reason
6021            );
6022            p2p_node
6023                .report_trust_event(
6024                    source,
6025                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6026                )
6027                .await;
6028        }
6029        send_replication_response(
6030            source,
6031            p2p_node,
6032            request_id,
6033            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6034                key: *key,
6035                reason: rejection.reason,
6036            }),
6037            rr_message_id,
6038        )
6039        .await;
6040        // Structurally invalid is a fact about this attempt, not the key.
6041        return Ok(FreshOfferOutcome::ProofRejected);
6042    }
6043
6044    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6045    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6046    // the same width client PUTs use), not just the close group plus a small
6047    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6048    // table may still list closer full nodes it hasn't evicted yet, ranking it
6049    // outside the narrow window in its own view; the wider accept window absorbs
6050    // that transient skew so the chunk still lands. Retention (pruning) stays at
6051    // `storage_admission_width`, so steady-state replication is unchanged.
6052    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6053    {
6054        send_replication_response(
6055            source,
6056            p2p_node,
6057            request_id,
6058            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6059                key: *key,
6060                reason: "Not in storage-admission range for this key".to_string(),
6061            }),
6062            rr_message_id,
6063        )
6064        .await;
6065        // About the key and this node's place in the routing table, not about
6066        // the sender: every queued proof would be refused identically.
6067        return Ok(FreshOfferOutcome::Abandoned);
6068    }
6069
6070    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6071    // never store this record, so reject it before the expensive payment
6072    // verification (EVM on-chain query / merkle pool work) rather than verifying
6073    // and only then failing at `storage.put` below. Reuses the cached capacity
6074    // check (passing results only, so freed space is detected promptly), and the
6075    // store path keeps its own check as defence-in-depth.
6076    if let Err(e) = ctx.storage.check_capacity() {
6077        info!(
6078            target: "ant_node::storage::disk_precheck",
6079            key = %hex::encode(key),
6080            "Rejecting fresh replication offer before payment verification: {e}"
6081        );
6082        send_replication_response(
6083            source,
6084            p2p_node,
6085            request_id,
6086            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6087                key: *key,
6088                reason: e.to_string(),
6089            }),
6090            rr_message_id,
6091        )
6092        .await;
6093        // A full disk is this node's condition, not the sender's.
6094        return Ok(FreshOfferOutcome::Abandoned);
6095    }
6096
6097    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6098    // part of the immediate write fan-out: this receiver is about to store the
6099    // record as if the client had PUT it here directly. Storage admission
6100    // was checked above before proof work. FreshReplication verification is
6101    // identical to ClientPut — store-strength cache semantics, paid-quote
6102    // issuer K-closeness checks for single-node proofs, merkle candidate
6103    // closeness for merkle proofs, and the same price-floor policy — the
6104    // distinct context only labels price-floor telemetry.
6105    let Some(verification) = verify_payment_until_shutdown(
6106        &ctx.payment_verifier,
6107        key,
6108        &attempt.proof_of_payment,
6109        fresh_offer_payment_context(),
6110        &ctx.shutdown,
6111    )
6112    .await
6113    else {
6114        debug!(
6115            "Fresh offer for {} from {source} abandoned: engine shutting down \
6116             during payment verification",
6117            hex::encode(key)
6118        );
6119        return Ok(FreshOfferOutcome::Abandoned);
6120    };
6121    match verification {
6122        Ok(status) if status.can_store() => {
6123            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6124        }
6125        // The chain has no record of this payment. That is a statement about
6126        // *this sender's* proof, so the key rotates to the next one rather than
6127        // being written off — the whole point of queueing them.
6128        //
6129        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6130        // not "definitively unpaid", so a lagging or reorganising chain view
6131        // renders honest senders indistinguishable from forgers, and penalising
6132        // would land on the entire close group at once. The structural checks in
6133        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6134        // because those cannot be produced by an honest sender at all.
6135        Ok(_) => {
6136            debug!(
6137                "Fresh offer for {} from {source}: no payment found for this proof",
6138                hex::encode(key)
6139            );
6140            send_replication_response(
6141                source,
6142                p2p_node,
6143                request_id,
6144                ReplicationMessageBody::FreshReplicationResponse(
6145                    FreshReplicationResponse::Rejected {
6146                        key: *key,
6147                        reason: "Payment verification failed: payment required".to_string(),
6148                    },
6149                ),
6150                rr_message_id,
6151            )
6152            .await;
6153            return Ok(FreshOfferOutcome::ProofRejected);
6154        }
6155        // A verification *error* is usually ours — an unreachable or failing EVM
6156        // endpoint — so it is neither penalised nor treated as this sender's
6157        // fault. Another proof still gets its turn, since the next call may well
6158        // succeed against a recovered endpoint.
6159        Err(e) => {
6160            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6161            send_replication_response(
6162                source,
6163                p2p_node,
6164                request_id,
6165                ReplicationMessageBody::FreshReplicationResponse(
6166                    FreshReplicationResponse::Rejected {
6167                        key: *key,
6168                        reason: format!("Payment verification error: {e}"),
6169                    },
6170                ),
6171                rr_message_id,
6172            )
6173            .await;
6174            return Ok(FreshOfferOutcome::ProofRejected);
6175        }
6176    }
6177
6178    // Rule 6: add to PaidForList.
6179    if let Err(e) = ctx.paid_list.insert(key).await {
6180        warn!("Failed to add key to PaidForList: {e}");
6181    }
6182
6183    // Store the record.
6184    match ctx.storage.put(key, data).await {
6185        Ok(_) => {
6186            send_replication_response(
6187                source,
6188                p2p_node,
6189                request_id,
6190                ReplicationMessageBody::FreshReplicationResponse(
6191                    FreshReplicationResponse::Accepted { key: *key },
6192                ),
6193                rr_message_id,
6194            )
6195            .await;
6196            Ok(FreshOfferOutcome::Settled)
6197        }
6198        Err(e) => {
6199            send_replication_response(
6200                source,
6201                p2p_node,
6202                request_id,
6203                ReplicationMessageBody::FreshReplicationResponse(
6204                    FreshReplicationResponse::Rejected {
6205                        key: *key,
6206                        reason: e.to_string(),
6207                    },
6208                ),
6209                rr_message_id,
6210            )
6211            .await;
6212            // The payment was good and the write still failed, so this is local
6213            // storage trouble that another proof cannot get around.
6214            Ok(FreshOfferOutcome::Abandoned)
6215        }
6216    }
6217}
6218
6219/// Admit a paid-list notification for handling on a worker, or drop it.
6220///
6221/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6222/// meant one message could park every other non-audit message behind a full
6223/// payment verification. That verification is not a bounded local computation:
6224/// on the merkle path it performs an iterative Kademlia lookup capped only by
6225/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6226/// the loop for minutes while the bounded inbound queue behind it overflowed
6227/// and dropped unrelated replication traffic wholesale.
6228///
6229/// It now follows the same detached-responder pattern as neighbor sync and
6230/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6231/// when stale, and run on a tracked worker.
6232///
6233/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6234/// refused notify is simply dropped. The sender's own paid-list convergence
6235/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6236/// the recovery path, exactly as for a notify lost in transit.
6237async fn dispatch_paid_notify(
6238    source: PeerId,
6239    notify: protocol::PaidNotify,
6240    ctx: &ReplicationMessageHandlerContext,
6241    received_at: Instant,
6242) -> Result<()> {
6243    let admission = match admit_bounded_responder(
6244        &ctx.paid_notify_admission_semaphore,
6245        &ctx.paid_notify_responder_inflight,
6246        &source,
6247        PAID_NOTIFY_MAX_OUTSTANDING,
6248        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6249    )
6250    .await
6251    {
6252        Ok(guard) => guard,
6253        Err(failure) => {
6254            audit_metrics::record_responder_admission_drop(
6255                ReplicationResponderClass::PaidNotify,
6256                failure.reason.into(),
6257            );
6258            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6259            // so a refusal discards durable paid-list evidence outright rather
6260            // than pushing work back onto a requester.
6261            warn!(
6262                responder_class = "paid_notify",
6263                source = %source,
6264                key = %hex::encode(notify.key),
6265                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6266            );
6267            return Ok(());
6268        }
6269    };
6270
6271    let ctx = ctx.clone();
6272    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6273    // Deliberately NOT the verification request deadline used by the
6274    // request/response responders. Nobody is waiting on a notify, and shedding
6275    // one discards durable paid-list evidence rather than a reply a requester
6276    // has already given up on. The threshold is instead the point at which the
6277    // pull path would have learned the same fact anyway: one slow-cadence
6278    // neighbor-sync interval, after which the verification cycle's paid-list
6279    // quorum makes this notify genuinely redundant.
6280    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6281    ctx.detached_task_tracker.clone().spawn(async move {
6282        let _admission = admission;
6283        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6284        // still queued behind a worker when the engine stops.
6285        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6286            debug!("Paid notify from {source} dropped: worker pool shut down");
6287            return;
6288        };
6289        if request_is_stale(received_at, queue_max_age) {
6290            debug!(
6291                responder_class = "paid_notify",
6292                source = %source,
6293                request_age_ms = received_at.elapsed().as_millis(),
6294                "Redundant paid notify shed at dequeue"
6295            );
6296            return;
6297        }
6298        if let Err(e) = handle_paid_notify(
6299            &source,
6300            &notify,
6301            &ctx.paid_list,
6302            &ctx.payment_verifier,
6303            &ctx.p2p_node,
6304            &ctx.config,
6305            &ctx.shutdown,
6306        )
6307        .await
6308        {
6309            debug!("Paid notify from {source} error: {e}");
6310        }
6311    });
6312
6313    Ok(())
6314}
6315
6316async fn handle_paid_notify(
6317    _source: &PeerId,
6318    notify: &protocol::PaidNotify,
6319    paid_list: &Arc<PaidList>,
6320    payment_verifier: &Arc<PaymentVerifier>,
6321    p2p_node: &Arc<P2PNode>,
6322    config: &ReplicationConfig,
6323    shutdown: &CancellationToken,
6324) -> Result<()> {
6325    let self_id = *p2p_node.peer_id();
6326
6327    // Rule 3: validate PoP presence before adding.
6328    if notify.proof_of_payment.is_empty() {
6329        return Ok(());
6330    }
6331
6332    // Check if we're in PaidCloseGroup for this key.
6333    if !admission::is_in_paid_close_group(
6334        &self_id,
6335        &notify.key,
6336        p2p_node,
6337        config.paid_list_close_group_size,
6338    )
6339    .await
6340    {
6341        return Ok(());
6342    }
6343
6344    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6345    // paid-list metadata, so local paid-list close-group membership was checked
6346    // above before proof work. The verifier then runs the same payment proof
6347    // checks as ClientPut while writing a paid-list-strength cache entry.
6348    let Some(verification) = verify_payment_until_shutdown(
6349        payment_verifier,
6350        &notify.key,
6351        &notify.proof_of_payment,
6352        paid_notify_payment_context(),
6353        shutdown,
6354    )
6355    .await
6356    else {
6357        debug!(
6358            "Paid notify for {} abandoned: engine shutting down during payment \
6359             verification",
6360            hex::encode(notify.key)
6361        );
6362        return Ok(());
6363    };
6364    match verification {
6365        Ok(status) if status.can_store() => {
6366            debug!(
6367                "PoP validated for paid notify key {}",
6368                hex::encode(notify.key)
6369            );
6370        }
6371        Ok(_) => {
6372            warn!(
6373                "Paid notify rejected: payment required for key {}",
6374                hex::encode(notify.key)
6375            );
6376            return Ok(());
6377        }
6378        Err(e) => {
6379            warn!(
6380                "PoP verification error for paid notify key {}: {e}",
6381                hex::encode(notify.key)
6382            );
6383            return Ok(());
6384        }
6385    }
6386
6387    if let Err(e) = paid_list.insert(&notify.key).await {
6388        warn!("Failed to add paid notify key to PaidForList: {e}");
6389    }
6390
6391    Ok(())
6392}
6393
6394#[allow(clippy::too_many_arguments)]
6395async fn dispatch_neighbor_sync_request(
6396    source: PeerId,
6397    request: protocol::NeighborSyncRequest,
6398    ctx: &ReplicationMessageHandlerContext,
6399    is_bootstrapping: bool,
6400    my_commitment: Option<StorageCommitment>,
6401    request_id: u64,
6402    received_at: Instant,
6403    rr_message_id: Option<&str>,
6404) -> Result<()> {
6405    let guard = match admit_bounded_responder(
6406        &ctx.neighbor_sync_responder_admission_semaphore,
6407        &ctx.neighbor_sync_responder_inflight,
6408        &source,
6409        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6410        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6411    )
6412    .await
6413    {
6414        Ok(guard) => guard,
6415        Err(failure) => {
6416            audit_metrics::record_responder_admission_drop(
6417                ReplicationResponderClass::NeighborSync,
6418                failure.reason.into(),
6419            );
6420            warn!(
6421                responder_class = "neighbor_sync",
6422                source = %source,
6423                "Neighbor-sync response dropped at admission: {failure}"
6424            );
6425            return Ok(());
6426        }
6427    };
6428
6429    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6430    let p2p_node = Arc::clone(&ctx.p2p_node);
6431    let storage = Arc::clone(&ctx.storage);
6432    let paid_list = Arc::clone(&ctx.paid_list);
6433    let queues = Arc::clone(&ctx.queues);
6434    let config = Arc::clone(&ctx.config);
6435    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6436    let sync_history = Arc::clone(&ctx.sync_history);
6437    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6438    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6439    let request_timeout = ctx.config.verification_request_timeout;
6440    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6441    ctx.detached_task_tracker.spawn(async move {
6442        let _guard = guard;
6443        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6444            debug!(
6445                responder_class = "neighbor_sync",
6446                source = %source,
6447                "Neighbor-sync responder worker pool closed before dequeue"
6448            );
6449            return;
6450        };
6451        if request_is_stale(received_at, request_timeout) {
6452            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6453            debug!(
6454                responder_class = "neighbor_sync",
6455                source = %source,
6456                request_age_ms = received_at.elapsed().as_millis(),
6457                "Stale neighbor-sync request shed at dequeue"
6458            );
6459            return;
6460        }
6461        if let Err(e) = handle_neighbor_sync_request(
6462            &source,
6463            &request,
6464            &p2p_node,
6465            &storage,
6466            &paid_list,
6467            &queues,
6468            &config,
6469            is_bootstrapping,
6470            &bootstrap_state,
6471            &sync_history,
6472            &sync_cycle_epoch,
6473            &repair_proofs,
6474            my_commitment,
6475            request_id,
6476            rr_message_id.as_deref(),
6477        )
6478        .await
6479        {
6480            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6481        }
6482    });
6483
6484    Ok(())
6485}
6486
6487#[allow(clippy::too_many_arguments)]
6488async fn handle_neighbor_sync_request(
6489    source: &PeerId,
6490    request: &protocol::NeighborSyncRequest,
6491    p2p_node: &Arc<P2PNode>,
6492    storage: &Arc<LmdbStorage>,
6493    paid_list: &Arc<PaidList>,
6494    queues: &Arc<RwLock<ReplicationQueues>>,
6495    config: &ReplicationConfig,
6496    is_bootstrapping: bool,
6497    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6498    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6499    sync_cycle_epoch: &Arc<RwLock<u64>>,
6500    repair_proofs: &Arc<RwLock<RepairProofs>>,
6501    my_commitment: Option<StorageCommitment>,
6502    request_id: u64,
6503    rr_message_id: Option<&str>,
6504) -> Result<()> {
6505    let self_id = *p2p_node.peer_id();
6506
6507    // No per-request hint count limit: the wire message size limit
6508    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6509    // challenges, sync hints don't drive expensive computation — they just
6510    // enter the verification queue. A per-request limit here would break
6511    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6512
6513    // Build response (outbound hints).
6514    let (response, sent_replica_hints, sender_in_rt) =
6515        neighbor_sync::handle_sync_request_with_proofs(
6516            source,
6517            request,
6518            p2p_node,
6519            storage,
6520            paid_list,
6521            config,
6522            is_bootstrapping,
6523            my_commitment.clone(),
6524        )
6525        .await;
6526
6527    // Send response.
6528    let response_sent = send_replication_response_checked(
6529        source,
6530        p2p_node,
6531        request_id,
6532        ReplicationMessageBody::NeighborSyncResponse(response),
6533        rr_message_id,
6534        None,
6535    )
6536    .await;
6537
6538    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6539    if !sender_in_rt {
6540        return Ok(());
6541    }
6542
6543    // Update sync history for this peer before recording repair proofs so a
6544    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6545    {
6546        let mut history = sync_history.write().await;
6547        let record = history.entry(*source).or_insert(PeerSyncRecord {
6548            last_sync: None,
6549            cycles_since_sync: 0,
6550        });
6551        record.last_sync = Some(Instant::now());
6552        record.cycles_since_sync = 0;
6553    }
6554
6555    if response_sent && !request.bootstrapping {
6556        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6557            .await;
6558    }
6559
6560    // Admit inbound hints and queue for verification.
6561    let outcome = admit_and_queue_hints(
6562        &self_id,
6563        source,
6564        &request.replica_hints,
6565        &request.paid_hints,
6566        p2p_node,
6567        config,
6568        storage,
6569        paid_list,
6570        queues,
6571    )
6572    .await;
6573
6574    // Track discovered keys for bootstrap drain detection so that hints
6575    // admitted via inbound sync requests are not missed. Capacity-rejected
6576    // hints keep this source on the "not yet drained" list until its next
6577    // sync re-admits them; a clean cycle clears the source.
6578    if is_bootstrapping {
6579        let live_discovered = outcome.discovered.clone();
6580        let outcomes = [(*source, outcome)];
6581        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6582    }
6583
6584    Ok(())
6585}
6586
6587/// Test-only record of who *sent* a verification request covering a watched key.
6588///
6589/// The capacity gate's entire effect is a request that is never sent, and a
6590/// request that was not sent leaves no production counter anywhere — not on the
6591/// sender, whose traffic counters are process-global and so cannot separate one
6592/// node of a single-process testnet from another, and not on the responder,
6593/// which simply never hears from it. Recording who asked is what lets a test
6594/// tell "held the key back" apart from "probed the close group, was refused at
6595/// the dial, and then held the key back", which are otherwise identical from the
6596/// queue's point of view.
6597///
6598/// Arming replaces the previous watch, so the outer map holds exactly the keys
6599/// the current test named, and each inner map holds at most one entry per node
6600/// in the process. Nothing is recorded until a test arms it, and the armed path
6601/// costs one read lock on the sending side.
6602///
6603/// Counting is per key because a node that cannot write legitimately keeps
6604/// sending verification requests for keys it has not yet authorized — that is
6605/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
6606/// would assert something untrue.
6607///
6608/// It counts *send attempts*, deliberately, recorded immediately before the wire
6609/// call. A responder sheds requests at admission and as stale, so a
6610/// receiver-side count would report zero for probes that were really sent, and
6611/// an assertion that this node asked nobody would pass on the strength of the
6612/// receiver dropping the question. It is not proof of delivery: a send that
6613/// fails immediately, with no route or during shutdown, is still counted.
6614///
6615/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
6616/// MSRV.
6617#[cfg(any(test, feature = "test-utils"))]
6618type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
6619
6620#[cfg(any(test, feature = "test-utils"))]
6621static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
6622    std::sync::OnceLock::new();
6623
6624#[cfg(any(test, feature = "test-utils"))]
6625fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
6626    VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
6627}
6628
6629/// Test-only: start counting verification requests for `keys`, from zero.
6630///
6631/// Replaces any previous watch rather than adding to it, so the map is bounded
6632/// by the keys of the test that armed it last and nothing accumulates across a
6633/// process running many tests.
6634#[cfg(any(test, feature = "test-utils"))]
6635pub fn watch_verification_requests_for_test(keys: &[XorName]) {
6636    if let Ok(mut watch) = verification_watch().write() {
6637        watch.clear();
6638        for key in keys {
6639            watch.insert(*key, HashMap::new());
6640        }
6641    }
6642}
6643
6644/// Record that `requester` sent a verification request covering `keys`, for
6645/// whichever of them are watched. A poisoned lock is ignored rather than
6646/// propagated: this is observation for tests and must never change behaviour.
6647#[cfg(any(test, feature = "test-utils"))]
6648pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
6649    // Fast path under a read lock: with nothing watched — every production
6650    // build, and every test that did not ask — this is all the sender pays.
6651    match verification_watch().read() {
6652        Ok(watch) if watch.is_empty() => return,
6653        Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
6654        Ok(_) => {}
6655        Err(_) => return,
6656    }
6657    if let Ok(mut watch) = verification_watch().write() {
6658        for key in keys {
6659            if let Some(by_peer) = watch.get_mut(key) {
6660                *by_peer.entry(*requester).or_insert(0) += 1;
6661            }
6662        }
6663    }
6664}
6665
6666/// Test-only: how many times `requester` has asked this process about `key`.
6667/// Zero unless the key was registered with `watch_verification_requests_for_test`.
6668#[cfg(any(test, feature = "test-utils"))]
6669#[must_use]
6670pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
6671    verification_watch().read().map_or(0, |watch| {
6672        watch
6673            .get(key)
6674            .and_then(|by_peer| by_peer.get(requester))
6675            .copied()
6676            .unwrap_or(0)
6677    })
6678}
6679
6680async fn handle_verification_request(
6681    source: &PeerId,
6682    request: &protocol::VerificationRequest,
6683    storage: &Arc<LmdbStorage>,
6684    paid_list: &Arc<PaidList>,
6685    p2p_node: &Arc<P2PNode>,
6686    request_id: u64,
6687    rr_message_id: Option<&str>,
6688) -> Result<()> {
6689    #[derive(Clone, Copy)]
6690    enum CachedPaidLookup {
6691        NotChecked,
6692        Checked(Option<bool>),
6693    }
6694
6695    #[derive(Clone, Copy)]
6696    struct CachedVerificationLookup {
6697        present: Option<bool>,
6698        paid: CachedPaidLookup,
6699    }
6700
6701    if verification_request_exceeds_limit(request.keys.len()) {
6702        warn!(
6703            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6704            request.keys.len(),
6705        );
6706        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6707        return Ok(());
6708    }
6709
6710    let requested_keys = request.keys.as_slice();
6711
6712    if request.paid_list_check_indices.len() > request.keys.len() {
6713        warn!(
6714            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6715            request.paid_list_check_indices.len(),
6716            request.keys.len(),
6717        );
6718        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6719        return Ok(());
6720    }
6721
6722    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6723    let paid_check_set: HashSet<u32> = request
6724        .paid_list_check_indices
6725        .iter()
6726        .copied()
6727        .filter(|&idx| {
6728            if idx >= keys_len {
6729                warn!(
6730                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6731                    requested_keys.len(),
6732                );
6733                false
6734            } else {
6735                true
6736            }
6737        })
6738        .collect();
6739
6740    let mut results = Vec::with_capacity(requested_keys.len());
6741    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6742    for (i, key) in requested_keys.iter().enumerate() {
6743        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6744        let cached = lookup_cache.entry(*key).or_insert_with(|| {
6745            let present = match storage.exists(key) {
6746                Ok(present) => Some(present),
6747                Err(e) => {
6748                    warn!(
6749                        "Verification request from {source}: failed to check storage for {}: {e}",
6750                        hex::encode(key)
6751                    );
6752                    None
6753                }
6754            };
6755            CachedVerificationLookup {
6756                present,
6757                paid: CachedPaidLookup::NotChecked,
6758            }
6759        });
6760
6761        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6762            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6763                Ok(paid) => Some(paid),
6764                Err(e) => {
6765                    warn!(
6766                        "Verification request from {source}: failed to check paid-list for {}: {e}",
6767                        hex::encode(key)
6768                    );
6769                    None
6770                }
6771            });
6772        }
6773
6774        let paid = if needs_paid {
6775            match cached.paid {
6776                CachedPaidLookup::Checked(paid) => paid,
6777                CachedPaidLookup::NotChecked => None,
6778            }
6779        } else {
6780            None
6781        };
6782
6783        if cached.present.is_none() && paid.is_none() {
6784            continue;
6785        }
6786
6787        results.push(protocol::KeyVerificationResult {
6788            key: *key,
6789            present: cached.present.unwrap_or(false),
6790            paid,
6791        });
6792    }
6793
6794    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6795
6796    Ok(())
6797}
6798
6799async fn dispatch_verification_request(
6800    source: PeerId,
6801    request: protocol::VerificationRequest,
6802    ctx: &ReplicationMessageHandlerContext,
6803    request_id: u64,
6804    received_at: Instant,
6805    rr_message_id: Option<&str>,
6806) -> Result<()> {
6807    let guard = match admit_bounded_responder(
6808        &ctx.verification_responder_admission_semaphore,
6809        &ctx.verification_responder_inflight,
6810        &source,
6811        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6812        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6813    )
6814    .await
6815    {
6816        Ok(guard) => guard,
6817        Err(failure) => {
6818            audit_metrics::record_responder_admission_drop(
6819                ReplicationResponderClass::Verification,
6820                failure.reason.into(),
6821            );
6822            warn!(
6823                responder_class = "verification",
6824                source = %source,
6825                "Verification response dropped at admission: {failure}"
6826            );
6827            return Ok(());
6828        }
6829    };
6830
6831    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6832    let storage = Arc::clone(&ctx.storage);
6833    let paid_list = Arc::clone(&ctx.paid_list);
6834    let p2p_node = Arc::clone(&ctx.p2p_node);
6835    let request_timeout = ctx.config.verification_request_timeout;
6836    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6837    ctx.detached_task_tracker.spawn(async move {
6838        let _guard = guard;
6839        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6840            debug!(
6841                responder_class = "verification",
6842                source = %source,
6843                "Verification responder worker pool closed before dequeue"
6844            );
6845            return;
6846        };
6847        if request_is_stale(received_at, request_timeout) {
6848            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6849            debug!(
6850                responder_class = "verification",
6851                source = %source,
6852                request_age_ms = received_at.elapsed().as_millis(),
6853                "Stale verification request shed at dequeue"
6854            );
6855            return;
6856        }
6857        if let Err(e) = handle_verification_request(
6858            &source,
6859            &request,
6860            &storage,
6861            &paid_list,
6862            &p2p_node,
6863            request_id,
6864            rr_message_id.as_deref(),
6865        )
6866        .await
6867        {
6868            debug!(source = %source, "Verification request handling failed: {e}");
6869        }
6870    });
6871
6872    Ok(())
6873}
6874
6875const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6876    key_count > MAX_INCOMING_VERIFICATION_KEYS
6877}
6878
6879async fn send_verification_results(
6880    source: &PeerId,
6881    p2p_node: &Arc<P2PNode>,
6882    request_id: u64,
6883    results: Vec<protocol::KeyVerificationResult>,
6884    rr_message_id: Option<&str>,
6885) {
6886    send_replication_response(
6887        source,
6888        p2p_node,
6889        request_id,
6890        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6891        rr_message_id,
6892    )
6893    .await;
6894}
6895
6896async fn dispatch_fetch_request(
6897    source: PeerId,
6898    request: protocol::FetchRequest,
6899    ctx: &ReplicationMessageHandlerContext,
6900    request_id: u64,
6901    received_at: Instant,
6902    rr_message_id: Option<&str>,
6903) -> Result<()> {
6904    let guard = match admit_bounded_responder(
6905        &ctx.fetch_responder_admission_semaphore,
6906        &ctx.fetch_responder_inflight,
6907        &source,
6908        FETCH_RESPONDER_MAX_OUTSTANDING,
6909        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6910    )
6911    .await
6912    {
6913        Ok(guard) => guard,
6914        Err(failure) => {
6915            audit_metrics::record_responder_admission_drop(
6916                ReplicationResponderClass::Fetch,
6917                failure.reason.into(),
6918            );
6919            warn!(
6920                responder_class = "fetch",
6921                source = %source,
6922                "Fetch response dropped at admission: {failure}"
6923            );
6924            return Ok(());
6925        }
6926    };
6927
6928    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6929    let storage = Arc::clone(&ctx.storage);
6930    let p2p_node = Arc::clone(&ctx.p2p_node);
6931    let request_timeout = ctx.config.fetch_request_timeout;
6932    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6933    ctx.detached_task_tracker.spawn(async move {
6934        let _guard = guard;
6935        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6936            debug!(
6937                responder_class = "fetch",
6938                source = %source,
6939                "Fetch responder worker pool closed before dequeue"
6940            );
6941            return;
6942        };
6943        if request_is_stale(received_at, request_timeout) {
6944            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6945            debug!(
6946                responder_class = "fetch",
6947                source = %source,
6948                request_age_ms = received_at.elapsed().as_millis(),
6949                "Stale fetch request shed at dequeue"
6950            );
6951            return;
6952        }
6953        if let Err(e) = handle_fetch_request(
6954            &source,
6955            &request,
6956            &storage,
6957            &p2p_node,
6958            request_id,
6959            rr_message_id.as_deref(),
6960        )
6961        .await
6962        {
6963            debug!(source = %source, "Fetch request handling failed: {e}");
6964        }
6965    });
6966
6967    Ok(())
6968}
6969
6970fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6971    received_at.elapsed() >= timeout
6972}
6973
6974async fn handle_fetch_request(
6975    source: &PeerId,
6976    request: &protocol::FetchRequest,
6977    storage: &Arc<LmdbStorage>,
6978    p2p_node: &Arc<P2PNode>,
6979    request_id: u64,
6980    rr_message_id: Option<&str>,
6981) -> Result<()> {
6982    let response = match storage.get(&request.key).await {
6983        Ok(Some(data)) => protocol::FetchResponse::Success {
6984            key: request.key,
6985            data,
6986        },
6987        Ok(None) => protocol::FetchResponse::NotFound { key: request.key },
6988        Err(e) => protocol::FetchResponse::Error {
6989            key: request.key,
6990            reason: format!("{e}"),
6991        },
6992    };
6993
6994    send_replication_response(
6995        source,
6996        p2p_node,
6997        request_id,
6998        ReplicationMessageBody::FetchResponse(response),
6999        rr_message_id,
7000    )
7001    .await;
7002
7003    Ok(())
7004}
7005
7006/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7007/// the prune-confirmation audit, which reuses the same wire message): reply with
7008/// per-key possession digests.
7009struct AuditResponderCompletion {
7010    response_kind: &'static str,
7011    sent: bool,
7012    processing: Duration,
7013    response_send: Duration,
7014}
7015
7016async fn handle_audit_challenge_msg(
7017    source: &PeerId,
7018    challenge: &protocol::AuditChallenge,
7019    storage: &Arc<LmdbStorage>,
7020    p2p_node: &Arc<P2PNode>,
7021    is_bootstrapping: bool,
7022    reply: ReplyRoute<'_>,
7023) -> Result<AuditResponderCompletion> {
7024    #[allow(clippy::cast_possible_truncation)]
7025    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7026    info!(
7027        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7028        challenge.keys.len(),
7029        is_bootstrapping,
7030        reply.rr_message_id.is_some(),
7031    );
7032
7033    let processing_started = Instant::now();
7034    let response = audit::handle_audit_challenge(
7035        challenge,
7036        storage,
7037        p2p_node.peer_id(),
7038        is_bootstrapping,
7039        stored_chunks,
7040    )
7041    .await;
7042    let processing = processing_started.elapsed();
7043    let response_kind = audit_response_kind(&response);
7044
7045    let response_send_started = Instant::now();
7046    let sent = send_replication_response_checked(
7047        source,
7048        p2p_node,
7049        reply.request_id,
7050        ReplicationMessageBody::AuditResponse(response),
7051        reply.rr_message_id,
7052        Some(reply.protocol),
7053    )
7054    .await;
7055    let response_send = response_send_started.elapsed();
7056
7057    Ok(AuditResponderCompletion {
7058        response_kind,
7059        sent,
7060        processing,
7061        response_send,
7062    })
7063}
7064
7065#[allow(clippy::too_many_arguments)]
7066fn log_audit_responder_completion(
7067    metrics: &AuditResponderMetrics,
7068    source: PeerId,
7069    class: AuditResponderClass,
7070    kind: &'static str,
7071    challenge_id: u64,
7072    work_items: usize,
7073    response_kind: &'static str,
7074    sent: bool,
7075    received_at: Instant,
7076    worker_started: Instant,
7077    processing: Duration,
7078    response_send: Duration,
7079) {
7080    let dispatch = worker_started.saturating_duration_since(received_at);
7081    let total = received_at.elapsed();
7082    metrics.record_completed(source, processing, total, sent);
7083    if sent {
7084        info!(
7085            target: "ant_node::replication::audit_responder",
7086            event = "completed",
7087            kind,
7088            responder_class = class.as_str(),
7089            source = %source,
7090            challenge_id,
7091            work_items,
7092            response = response_kind,
7093            sent,
7094            dispatch_ms = dispatch.as_millis(),
7095            processing_ms = processing.as_millis(),
7096            response_send_ms = response_send.as_millis(),
7097            total_ms = total.as_millis(),
7098            "Audit responder request completed"
7099        );
7100    } else {
7101        warn!(
7102            target: "ant_node::replication::audit_responder",
7103            event = "completed",
7104            kind,
7105            responder_class = class.as_str(),
7106            source = %source,
7107            challenge_id,
7108            work_items,
7109            response = response_kind,
7110            sent,
7111            dispatch_ms = dispatch.as_millis(),
7112            processing_ms = processing.as_millis(),
7113            response_send_ms = response_send.as_millis(),
7114            total_ms = total.as_millis(),
7115            "Audit responder request completed without sending a reply"
7116        );
7117    }
7118}
7119
7120/// Where a reply goes and how it is addressed.
7121///
7122/// Grouped because the audit responder needs all three together and one of them
7123/// is not derivable from the body: during the rollout window a possession reply
7124/// may have to go out on the core id rather than its family's own (see
7125/// [`is_legacy_possession_challenge`]).
7126struct ReplyRoute<'a> {
7127    /// Correlates the reply with the challenge, at the replication layer.
7128    request_id: u64,
7129    /// Present when the challenge arrived over request-response, in which case
7130    /// the reply rides the same exchange back.
7131    rr_message_id: Option<&'a str>,
7132    /// The protocol id to answer on.
7133    protocol: &'static str,
7134}
7135
7136fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7137    match response {
7138        protocol::AuditResponse::Digests { .. } => "digests",
7139        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7140        protocol::AuditResponse::Rejected { .. } => "rejected",
7141    }
7142}
7143
7144fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7145    match response {
7146        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7147        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7148        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7149    }
7150}
7151
7152fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7153    match response {
7154        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7155        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7156        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7157    }
7158}
7159
7160fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7161    match response {
7162        protocol::SubtreeSliceResponse::Items { .. } => "items",
7163        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7164        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7165    }
7166}
7167
7168fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7169    match response {
7170        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7171        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7172    }
7173}
7174
7175// ---------------------------------------------------------------------------
7176// Message sending helper
7177// ---------------------------------------------------------------------------
7178
7179/// Send a replication response message as a best-effort reply.
7180///
7181/// Encode and send failures are logged by the checked helper. Most response
7182/// paths do not need to branch on send success, so this wrapper keeps those
7183/// call sites explicit about their best-effort behavior.
7184async fn send_replication_response(
7185    peer: &PeerId,
7186    p2p_node: &Arc<P2PNode>,
7187    request_id: u64,
7188    body: ReplicationMessageBody,
7189    rr_message_id: Option<&str>,
7190) {
7191    let _ =
7192        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7193            .await;
7194}
7195
7196/// Send a replication response message and report whether it was accepted.
7197///
7198/// Returns `true` after the message is encoded and accepted by the P2P send
7199/// path. Returns `false` after logging an encode or send failure. Repair-proof
7200/// recording uses this to avoid trusting hints that were not actually sent.
7201///
7202/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7203/// request-response path so saorsa-core can route it back to the caller's
7204/// `send_request` future. Otherwise it is sent as a plain message.
7205///
7206/// `protocol` overrides the id the body would route on by family. Exactly one
7207/// caller needs it: a possession challenge from a peer that predates the family
7208/// split has to be answered where it was asked (see
7209/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7210/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7211async fn send_replication_response_checked(
7212    peer: &PeerId,
7213    p2p_node: &Arc<P2PNode>,
7214    request_id: u64,
7215    body: ReplicationMessageBody,
7216    rr_message_id: Option<&str>,
7217    protocol: Option<&'static str>,
7218) -> bool {
7219    let msg = ReplicationMessage { request_id, body };
7220    let encoded = match msg.encode() {
7221        Ok(data) => data,
7222        Err(e) => {
7223            warn!("Failed to encode replication response: {e}");
7224            return false;
7225        }
7226    };
7227    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7228    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7229    // included for completeness. Other response variants (verification/audit/
7230    // commitment) are intentionally excluded — the round-2 audit reply is now a
7231    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7232    if matches!(
7233        msg.body,
7234        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7235    ) {
7236        protocol::record_served(peer, encoded.len());
7237    }
7238    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7239    let result = if let Some(msg_id) = rr_message_id {
7240        p2p_node
7241            .send_response(peer, protocol, msg_id, encoded)
7242            .await
7243    } else {
7244        p2p_node.send_message(peer, protocol, encoded, &[]).await
7245    };
7246    if let Err(e) = result {
7247        debug!("Failed to send replication response to {peer}: {e}");
7248        return false;
7249    }
7250    true
7251}
7252
7253async fn record_sent_replica_hints(
7254    peer: &PeerId,
7255    hints: &[neighbor_sync::SentReplicaHint],
7256    repair_proofs: &Arc<RwLock<RepairProofs>>,
7257    sync_cycle_epoch: &Arc<RwLock<u64>>,
7258) {
7259    if hints.is_empty() {
7260        return;
7261    }
7262
7263    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7264    let mut proofs = repair_proofs.write().await;
7265    for hint in hints {
7266        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7267            debug!(
7268                "Recorded repair hint proof for peer {peer} and key {}",
7269                hex::encode(hint.key)
7270            );
7271        }
7272    }
7273}
7274
7275// ---------------------------------------------------------------------------
7276// Neighbor sync round
7277// ---------------------------------------------------------------------------
7278
7279/// Run one neighbor sync round.
7280#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7281async fn run_neighbor_sync_round(
7282    p2p_node: &Arc<P2PNode>,
7283    storage: &Arc<LmdbStorage>,
7284    paid_list: &Arc<PaidList>,
7285    queues: &Arc<RwLock<ReplicationQueues>>,
7286    config: &ReplicationConfig,
7287    sync_state: &Arc<RwLock<NeighborSyncState>>,
7288    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7289    sync_cycle_epoch: &Arc<RwLock<u64>>,
7290    repair_proofs: &Arc<RwLock<RepairProofs>>,
7291    is_bootstrapping: &Arc<RwLock<bool>>,
7292    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7293    commitment_state: &Arc<ResponderCommitmentState>,
7294    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7295    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7296    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7297    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7298    gossip_audit: &GossipAuditTrigger,
7299) {
7300    let self_id = *p2p_node.peer_id();
7301    let bootstrapping = *is_bootstrapping.read().await;
7302
7303    // Check if cycle is complete; start new one if needed.
7304    // We check under a read lock, then release it before the expensive
7305    // prune pass and DHT snapshot so other tasks are not starved.
7306    let cycle_complete = sync_state.read().await.is_cycle_complete();
7307    if cycle_complete {
7308        // A completed local neighbor-sync cycle advances the epoch component
7309        // of repair-proof maturity. The per-key wall-clock minimum age is
7310        // checked when audits are selected.
7311        {
7312            let mut history = sync_history.write().await;
7313            for record in history.values_mut() {
7314                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7315            }
7316        }
7317        {
7318            let mut epoch = sync_cycle_epoch.write().await;
7319            *epoch = epoch.saturating_add(1);
7320        }
7321
7322        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7323        // Prune candidacy is unconditional once the hysteresis elapses;
7324        // bootstrap state only defers the remote prune-confirmation audits
7325        // until bootstrap has drained.
7326        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7327        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7328            self_id: &self_id,
7329            storage,
7330            paid_list,
7331            p2p_node,
7332            config,
7333            sync_state,
7334            repair_proofs,
7335            allow_remote_prune_audits,
7336            commitment_state: Some(commitment_state),
7337            audit_challenge_coordinator,
7338        })
7339        .await;
7340
7341        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7342        let neighbors =
7343            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7344                .await;
7345
7346        // Now re-acquire write lock and re-check before swapping cycle.
7347        let mut state = sync_state.write().await;
7348        if state.is_cycle_complete() {
7349            // Preserve cooldown and bootstrap-claim tracking across cycles.
7350            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7351            // would reset the abuse detection timer every cycle.
7352            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7353            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7354            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7355            let old_prune_cursor = state.prune_cursor;
7356            *state = NeighborSyncState::new_cycle(neighbors);
7357            state.last_sync_times = old_sync_times;
7358            state.bootstrap_claims = old_bootstrap_claims;
7359            state.bootstrap_claim_history = old_bootstrap_claim_history;
7360            state.prune_cursor = old_prune_cursor;
7361        }
7362    }
7363
7364    // Select batch of peers.
7365    let batch = {
7366        let mut state = sync_state.write().await;
7367        neighbor_sync::select_sync_batch(
7368            &mut state,
7369            config.neighbor_sync_peer_count,
7370            config.neighbor_sync_cooldown,
7371        )
7372    };
7373
7374    if batch.is_empty() {
7375        return;
7376    }
7377
7378    debug!("Neighbor sync: syncing with {} peers", batch.len());
7379
7380    // Snapshot our current commitment once per round so all peers in
7381    // this batch see the same thing (gossip is the responder's attestation;
7382    // same value across the batch is fine and reduces RwLock churn). Atomically
7383    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7384    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7385    let my_commitment = commitment_state
7386        .current_for_gossip()
7387        .map(|b| b.commitment().clone());
7388
7389    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7390        &batch,
7391        storage,
7392        paid_list,
7393        p2p_node,
7394        config.close_group_size,
7395        config.paid_list_close_group_size,
7396    )
7397    .await;
7398
7399    // Sync with each peer in the batch.
7400    for peer in &batch {
7401        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7402        let outcome = neighbor_sync::sync_with_peer_with_hints(
7403            peer,
7404            p2p_node,
7405            config,
7406            bootstrapping,
7407            hints,
7408            my_commitment.clone(),
7409        )
7410        .await;
7411
7412        if let Some(outcome) = outcome {
7413            handle_sync_response(
7414                &self_id,
7415                peer,
7416                &outcome.response,
7417                &outcome.sent_replica_hints,
7418                p2p_node,
7419                config,
7420                bootstrapping,
7421                bootstrap_state,
7422                storage,
7423                paid_list,
7424                queues,
7425                sync_state,
7426                sync_history,
7427                sync_cycle_epoch,
7428                repair_proofs,
7429                last_commitment_by_peer,
7430                ever_capable_peers,
7431                sig_verify_attempts,
7432                gossip_audit,
7433            )
7434            .await;
7435        } else {
7436            // Sync failed -- remove peer and try to fill slot.
7437            let replacement = {
7438                let mut state = sync_state.write().await;
7439                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7440            };
7441
7442            // Attempt sync with the replacement peer (if one was found).
7443            if let Some(replacement_peer) = replacement {
7444                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7445                    std::slice::from_ref(&replacement_peer),
7446                    storage,
7447                    paid_list,
7448                    p2p_node,
7449                    config.close_group_size,
7450                    config.paid_list_close_group_size,
7451                )
7452                .await;
7453                let hints = replacement_hints
7454                    .remove(&replacement_peer)
7455                    .unwrap_or_default();
7456                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7457                    &replacement_peer,
7458                    p2p_node,
7459                    config,
7460                    bootstrapping,
7461                    hints,
7462                    my_commitment.clone(),
7463                )
7464                .await;
7465
7466                if let Some(outcome) = replacement_outcome {
7467                    handle_sync_response(
7468                        &self_id,
7469                        &replacement_peer,
7470                        &outcome.response,
7471                        &outcome.sent_replica_hints,
7472                        p2p_node,
7473                        config,
7474                        bootstrapping,
7475                        bootstrap_state,
7476                        storage,
7477                        paid_list,
7478                        queues,
7479                        sync_state,
7480                        sync_history,
7481                        sync_cycle_epoch,
7482                        repair_proofs,
7483                        last_commitment_by_peer,
7484                        ever_capable_peers,
7485                        sig_verify_attempts,
7486                        gossip_audit,
7487                    )
7488                    .await;
7489                }
7490            }
7491        }
7492    }
7493}
7494
7495/// Process a successful neighbor sync response: record the sync, check for
7496/// bootstrap claim abuse, and admit inbound hints.
7497#[allow(clippy::too_many_arguments)]
7498async fn handle_sync_response(
7499    self_id: &PeerId,
7500    peer: &PeerId,
7501    resp: &NeighborSyncResponse,
7502    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7503    p2p_node: &Arc<P2PNode>,
7504    config: &ReplicationConfig,
7505    bootstrapping: bool,
7506    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7507    storage: &Arc<LmdbStorage>,
7508    paid_list: &Arc<PaidList>,
7509    queues: &Arc<RwLock<ReplicationQueues>>,
7510    sync_state: &Arc<RwLock<NeighborSyncState>>,
7511    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7512    sync_cycle_epoch: &Arc<RwLock<u64>>,
7513    repair_proofs: &Arc<RwLock<RepairProofs>>,
7514    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7515    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7516    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7517    gossip_audit: &GossipAuditTrigger,
7518) {
7519    // Ingest the peer's commitment if they piggybacked one on the response.
7520    // Same verification as the request path (peer-id binding + signature);
7521    // forged commitments are dropped at the edge. A *changed* commitment here
7522    // is a gossip-audit trigger just like on the request path — so a peer that
7523    // only ever answers sync (never initiates) is still audited (ADR-0002).
7524    if let Some(target) = ingest_peer_commitment(
7525        peer,
7526        resp.commitment.as_ref(),
7527        p2p_node,
7528        last_commitment_by_peer,
7529        ever_capable_peers,
7530        sig_verify_attempts,
7531    )
7532    .await
7533    {
7534        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7535    }
7536
7537    // Record successful sync.
7538    {
7539        let mut state = sync_state.write().await;
7540        neighbor_sync::record_successful_sync(&mut state, peer);
7541    }
7542    {
7543        let mut history = sync_history.write().await;
7544        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7545            last_sync: None,
7546            cycles_since_sync: 0,
7547        });
7548        record.last_sync = Some(Instant::now());
7549        record.cycles_since_sync = 0;
7550    }
7551
7552    // Process inbound hints from response (skip if peer is bootstrapping).
7553    if resp.bootstrapping {
7554        // Gap 6: BootstrapClaimAbuse grace period enforcement.
7555        // Separate state mutation from network I/O to avoid holding the
7556        // write lock across report_trust_event.
7557        let should_report = {
7558            let now = Instant::now();
7559            let mut state = sync_state.write().await;
7560            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7561                BootstrapClaimObservation::WithinGrace { .. } => false,
7562                BootstrapClaimObservation::PastGrace { first_seen } => {
7563                    warn!(
7564                        "Peer {peer} has been claiming bootstrap for {:?}, \
7565                         exceeding grace period of {:?} — reporting abuse",
7566                        now.duration_since(first_seen),
7567                        config.bootstrap_claim_grace_period,
7568                    );
7569                    true
7570                }
7571                BootstrapClaimObservation::Repeated { first_seen } => {
7572                    warn!(
7573                        "Peer {peer} repeated bootstrap claim after previously stopping; \
7574                         first claim was {:?} ago — reporting abuse",
7575                        now.duration_since(first_seen),
7576                    );
7577                    true
7578                }
7579            }
7580        };
7581        if should_report {
7582            p2p_node
7583                .report_trust_event(
7584                    peer,
7585                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7586                )
7587                .await;
7588        }
7589    } else {
7590        // Peer is not claiming bootstrap; clear active claim while retaining
7591        // history so the peer cannot start a second grace window later.
7592        {
7593            let mut state = sync_state.write().await;
7594            state.clear_active_bootstrap_claim(peer);
7595        }
7596        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7597        let outcome = admit_and_queue_hints(
7598            self_id,
7599            peer,
7600            &resp.replica_hints,
7601            &resp.paid_hints,
7602            p2p_node,
7603            config,
7604            storage,
7605            paid_list,
7606            queues,
7607        )
7608        .await;
7609
7610        // Track discovered keys for bootstrap drain detection so that hints
7611        // admitted via regular neighbor sync are not missed. Capacity-
7612        // rejected hints keep this source on the "not yet drained" list
7613        // until its next sync replays them; a clean cycle clears it.
7614        if bootstrapping {
7615            let live_discovered = outcome.discovered.clone();
7616            let outcomes = [(*peer, outcome)];
7617            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7618                .await;
7619        }
7620    }
7621}
7622
7623/// Admit hints and queue them for verification, returning newly-discovered keys.
7624///
7625/// Shared by neighbor-sync request handling, response handling, and bootstrap
7626/// sync so that admission + queueing logic lives in one place.
7627#[allow(clippy::too_many_arguments)]
7628/// Outcome of [`admit_and_queue_hints`].
7629///
7630/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7631/// available; that source is kept outstanding until it re-hints. `displaced`
7632/// tracks older borrowed hints reclaimed for another sender; only the key is
7633/// dropped from bootstrap tracking — the former owner's standing is untouched
7634/// (see [`publish_bootstrap_admission_outcomes`]).
7635struct AdmissionOutcome {
7636    discovered: HashSet<XorName>,
7637    capacity_rejected_count: usize,
7638    displaced: Vec<CapacityDisplacement>,
7639}
7640
7641/// Publish one atomic admission unit into bootstrap drain accounting.
7642///
7643/// Only sources that were themselves capacity-rejected are kept outstanding.
7644/// A fairness displacement forfeits the displaced *key* but never stamps its
7645/// former owner: reclaiming a borrowed slot is this node's own fairness
7646/// decision, so charging it to the victim would let a sustained flooder wedge
7647/// our bootstrap drain open through an unrelated honest peer. Clean sources
7648/// are cleared only after every outcome in the unit is known, so peer
7649/// iteration order cannot falsely clear a rejection recorded later in the same
7650/// bootstrap batch.
7651async fn publish_bootstrap_admission_outcomes(
7652    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7653    outcomes: &[(PeerId, AdmissionOutcome)],
7654    live_discovered: &HashSet<XorName>,
7655) {
7656    let mut rejected_sources = HashSet::new();
7657    let mut clean_sources = HashSet::new();
7658    let mut displaced_keys = HashSet::new();
7659
7660    for (source, outcome) in outcomes {
7661        if outcome.capacity_rejected_count > 0 {
7662            rejected_sources.insert(*source);
7663        } else {
7664            clean_sources.insert(*source);
7665        }
7666        // Only the *key* of a fairness displacement is forfeited here, never
7667        // its owner's standing. Reclaiming a borrowed slot is our own fairness
7668        // decision, not a failure by the peer that held it: stamping the victim
7669        // would let a sustained flooder block our bootstrap drain through an
7670        // unrelated honest peer that never overflowed us. The displaced key
7671        // falls to the same post-bootstrap neighbor-sync and audit/repair
7672        // recovery path that TTL expiry already relies on.
7673        for displacement in &outcome.displaced {
7674            displaced_keys.insert(displacement.key);
7675        }
7676    }
7677    clean_sources.retain(|source| !rejected_sources.contains(source));
7678
7679    let now = Instant::now();
7680    let mut state = bootstrap_state.write().await;
7681    for key in displaced_keys {
7682        state.remove_key(&key);
7683    }
7684    state.pending_keys.extend(live_discovered);
7685    for source in clean_sources {
7686        state.capacity_rejected_sources.remove(&source);
7687    }
7688    for source in rejected_sources {
7689        // First-seen: a source that keeps overflowing us must not keep its own
7690        // record fresh, or bootstrap never drains and auditing stays off.
7691        state.note_capacity_rejected(source, now);
7692    }
7693}
7694
7695#[allow(clippy::too_many_arguments)]
7696async fn admit_and_queue_hints(
7697    self_id: &PeerId,
7698    source_peer: &PeerId,
7699    replica_hints: &[XorName],
7700    paid_hints: &[XorName],
7701    p2p_node: &Arc<P2PNode>,
7702    config: &ReplicationConfig,
7703    storage: &Arc<LmdbStorage>,
7704    paid_list: &Arc<PaidList>,
7705    queues: &Arc<RwLock<ReplicationQueues>>,
7706) -> AdmissionOutcome {
7707    let pending_keys: HashSet<XorName> = {
7708        let q = queues.read().await;
7709        q.pending_keys().into_iter().collect()
7710    };
7711
7712    let admitted = admission::admit_hints(
7713        self_id,
7714        replica_hints,
7715        paid_hints,
7716        p2p_node,
7717        config,
7718        storage,
7719        paid_list,
7720        &pending_keys,
7721    )
7722    .await;
7723
7724    let mut q = queues.write().await;
7725    queue_admitted_hints(source_peer, admitted, storage, &mut q)
7726}
7727
7728fn queue_admitted_hints(
7729    source_peer: &PeerId,
7730    admitted: admission::AdmissionResult,
7731    storage: &LmdbStorage,
7732    q: &mut ReplicationQueues,
7733) -> AdmissionOutcome {
7734    let mut discovered = HashSet::new();
7735    let mut capacity_rejected_count: usize = 0;
7736    let mut displaced = Vec::new();
7737    let now = Instant::now();
7738
7739    for key in admitted.replica_keys {
7740        if !storage.exists(&key).unwrap_or(false) {
7741            let result = q.add_pending_verify(
7742                key,
7743                VerificationEntry {
7744                    state: VerificationState::PendingVerify,
7745                    verified_sources: Vec::new(),
7746                    tried_sources: HashSet::new(),
7747                    created_at: now,
7748                    next_verify_at: now,
7749                    hint_sources: HashSet::from([*source_peer]),
7750                    // Non-empty: this peer claimed possession, so it is a
7751                    // fetch-source candidate. Derives HintPipeline::Replica.
7752                    replica_hint_sources: HashSet::from([*source_peer]),
7753                    unresolved_retries: 0,
7754                    no_holder_reported: false,
7755                },
7756            );
7757            match result {
7758                crate::replication::scheduling::AdmissionResult::Admitted => {
7759                    discovered.insert(key);
7760                }
7761                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7762                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7763                    capacity_rejected_count += 1;
7764                }
7765            }
7766        }
7767    }
7768
7769    for key in admitted.paid_only_keys {
7770        let result = q.add_pending_verify(
7771            key,
7772            VerificationEntry {
7773                state: VerificationState::PendingVerify,
7774                verified_sources: Vec::new(),
7775                tried_sources: HashSet::new(),
7776                created_at: now,
7777                next_verify_at: now,
7778                hint_sources: HashSet::from([*source_peer]),
7779                // Empty: a paid hint makes no possession claim, so this peer is
7780                // not a fetch source. Derives HintPipeline::PaidOnly.
7781                replica_hint_sources: HashSet::new(),
7782                unresolved_retries: 0,
7783                no_holder_reported: false,
7784            },
7785        );
7786        match result {
7787            crate::replication::scheduling::AdmissionResult::Admitted => {
7788                discovered.insert(key);
7789            }
7790            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7791            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7792                capacity_rejected_count += 1;
7793            }
7794        }
7795    }
7796
7797    if capacity_rejected_count > 0 {
7798        debug!(
7799            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7800             rejected at queue capacity; source will need to re-hint after pending_verify drains"
7801        );
7802    }
7803
7804    displaced.extend(q.take_capacity_displacements());
7805
7806    AdmissionOutcome {
7807        discovered,
7808        capacity_rejected_count,
7809        displaced,
7810    }
7811}
7812
7813// ---------------------------------------------------------------------------
7814// Verification cycle
7815// ---------------------------------------------------------------------------
7816
7817/// Run one verification cycle: process pending keys through quorum checks.
7818#[allow(clippy::too_many_lines)]
7819async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7820    let cycle_started = Instant::now();
7821    let VerificationCycleContext {
7822        p2p_node,
7823        paid_list,
7824        storage,
7825        queues,
7826        config,
7827        bootstrap_state,
7828        is_bootstrapping,
7829        bootstrap_complete_notify,
7830        last_commitment_by_peer,
7831        ever_capable_peers,
7832        recent_provers,
7833    } = ctx;
7834
7835    // Self-heal the bootstrap drain before any early-return below: abandoned
7836    // capacity-rejection records must expire, and a drain condition that
7837    // became true without a triggering event must still be observed. Pending
7838    // peer requests legitimately block the drain check itself, but not this.
7839    expire_and_recheck_bootstrap_drain(
7840        bootstrap_state,
7841        queues,
7842        is_bootstrapping,
7843        bootstrap_complete_notify,
7844        config.capacity_rejected_max_age(),
7845    )
7846    .await;
7847
7848    // Bootstrap admits one concurrent neighbor batch as an atomic source
7849    // aggregation unit. Do not select newly queued keys until that batch's
7850    // hints and drain accounting have both been published.
7851    if bootstrap_state.read().await.pending_peer_requests > 0 {
7852        return;
7853    }
7854
7855    // Evict stale entries that have been pending too long (e.g. unreachable
7856    // verification targets during a network partition).
7857    let stale_pending_keys = {
7858        let mut q = queues.write().await;
7859        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7860    };
7861    if !stale_pending_keys.is_empty() {
7862        update_bootstrap_after_verification(
7863            &stale_pending_keys,
7864            bootstrap_state,
7865            queues,
7866            is_bootstrapping,
7867            bootstrap_complete_notify,
7868        )
7869        .await;
7870    }
7871
7872    let pending_keys = {
7873        let mut q = queues.write().await;
7874        // Re-check while holding the queue write lock used by fair selection.
7875        // This closes the race
7876        // where a bootstrap batch starts after the early check: the batch
7877        // cannot publish its hints under the queue write lock until this
7878        // selection either returns or declines to run.
7879        if bootstrap_state.read().await.pending_peer_requests > 0 {
7880            return;
7881        }
7882        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7883    };
7884
7885    if pending_keys.is_empty() {
7886        return;
7887    }
7888    let initial_pending_count = pending_keys.len();
7889
7890    // Capacity verdict for this cycle — the same pre-check the PUT handler and
7891    // the fresh-offer path already run (V2-411), read once and reused below.
7892    //
7893    // It gates only the two steps that exist to enable a fetch: the presence
7894    // probe that discovers holders, and the promotion that queues the download.
7895    // Everything a cycle does that does not need a local write still runs on a
7896    // full node — the local paid-list fast path, `PaidForList` convergence
7897    // through the quorum round, and the terminal checks that retire a key this
7898    // node already holds or is no longer admitted for. Gating earlier than this
7899    // would stop a full node learning which of its keys were paid for, and
7900    // would strand keys that should have retired, which keeps bootstrap drain
7901    // pending and audits disabled until stale eviction.
7902    // Only a *full* disk is a standing condition worth minutes of backoff. A
7903    // failed `statvfs` says nothing about available space and may have cleared
7904    // by the next cycle, so it is treated as writable here and left to the
7905    // pre-check at the dial, which queries again and may well permit the write.
7906    let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
7907    // Counted per gate rather than combined. `local_paid_probe` below counts
7908    // probes actually sent, so it reads zero once the first gate fires; keeping
7909    // the two deferral counts apart is what lets an operator see which branch a
7910    // full node's keys are taking without adding a code path to find out.
7911    let mut capacity_deferred_probe = 0usize;
7912    let mut capacity_deferred_promote = 0usize;
7913
7914    let self_id = *p2p_node.peer_id();
7915
7916    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
7917    // step 4). Paid-list membership settles *validity* — the key is known-paid,
7918    // so no quorum round is needed. It says nothing about whether we must hold
7919    // the bytes; that is decided below.
7920    let mut local_paid_keys = Vec::new();
7921    let mut keys_needing_network = Vec::new();
7922    let mut terminal_keys: Vec<XorName> = Vec::new();
7923    {
7924        let mut q = queues.write().await;
7925        for key in &pending_keys {
7926            if paid_list.contains(key).unwrap_or(false) {
7927                if q.set_pending_state(key, VerificationState::PaidListVerified) {
7928                    local_paid_keys.push(*key);
7929                }
7930            } else {
7931                keys_needing_network.push(*key);
7932            }
7933        }
7934    }
7935
7936    // Storage responsibility is a live routing question, decided identically
7937    // for every known-paid key regardless of how the advertising peer labelled
7938    // its hint — a replica hint is a possession *claim* by the sender, never
7939    // permission for us to store. Held outside the queue lock: `is_responsible`
7940    // awaits into the DHT manager.
7941    let mut local_paid_presence_probe_keys = Vec::new();
7942    if !local_paid_keys.is_empty() {
7943        let mut terminal_paid = Vec::new();
7944        for key in local_paid_keys {
7945            if storage.exists(&key).unwrap_or(false) {
7946                terminal_paid.push(key);
7947            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
7948                // We carry storage responsibility and lack the bytes. The
7949                // presence probe below discovers holders to fetch from; it is
7950                // source discovery, not re-verification.
7951                local_paid_presence_probe_keys.push(key);
7952            } else {
7953                terminal_paid.push(key);
7954            }
7955        }
7956
7957        if !terminal_paid.is_empty() {
7958            let mut q = queues.write().await;
7959            for key in terminal_paid {
7960                q.remove_pending(&key);
7961                terminal_keys.push(key);
7962            }
7963        }
7964
7965        // Capacity gate, first of two. Everything above this point has already
7966        // run: authorization succeeded via the local `PaidForList` hit, and the
7967        // keys that should retire (already held, or no longer storage-admitted)
7968        // have retired. What is left is a probe whose only purpose is finding a
7969        // holder to download from, and this node cannot write what it would
7970        // download.
7971        if write_blocked && !local_paid_presence_probe_keys.is_empty() {
7972            let mut q = queues.write().await;
7973            for key in std::mem::take(&mut local_paid_presence_probe_keys) {
7974                if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
7975                    capacity_deferred_probe += 1;
7976                }
7977            }
7978        }
7979    }
7980
7981    let local_paid_probe_count = local_paid_presence_probe_keys.len();
7982    let keys_needing_network_count = keys_needing_network.len();
7983    // Keys this cycle put back because no peer claimed possession. Reported in
7984    // aggregate below; the per-key line is warned once per entry, not per retry.
7985    let mut no_holder_deferrals = 0usize;
7986
7987    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
7988    // step 4, authorization succeeds immediately; run a presence-only probe
7989    // to find any holder we can fetch from.
7990    if !local_paid_presence_probe_keys.is_empty() {
7991        let targets = quorum::compute_presence_targets(
7992            &local_paid_presence_probe_keys,
7993            p2p_node,
7994            config,
7995            &self_id,
7996        )
7997        .await;
7998        let evidence = quorum::run_verification_round(
7999            &local_paid_presence_probe_keys,
8000            &targets,
8001            p2p_node,
8002            config,
8003        )
8004        .await;
8005
8006        let mut q = queues.write().await;
8007        for key in local_paid_presence_probe_keys {
8008            if storage.exists(&key).unwrap_or(false) {
8009                q.remove_pending(&key);
8010                terminal_keys.push(key);
8011                continue;
8012            }
8013            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8014                quorum::present_sources_for_key(&key, ev, &targets)
8015            });
8016            if let Some(entry) = q.get_pending(&key) {
8017                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8018            }
8019            if sources.is_empty() {
8020                no_holder_deferrals += 1;
8021                let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8022                let first_report = q.claim_no_holder_report(&key);
8023                report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8024            } else {
8025                // A holder answered, so whatever came before is not a run of
8026                // consecutive failures any more. Clear before promoting: if the
8027                // fetch queue is full the entry stays pending, and it must not
8028                // carry the old backoff.
8029                q.clear_unresolved(&key);
8030                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8031                // Atomic remove+enqueue: if fetch_queue is at capacity, the
8032                // pending entry is preserved and retried next cycle (no
8033                // silent drop of verified replica-repair work).
8034                let _ = q.promote_pending_to_fetch(key, distance, sources);
8035            }
8036        }
8037    }
8038
8039    // Steps 2-5: Network verification (skipped if all keys resolved locally).
8040    if !keys_needing_network.is_empty() {
8041        // Step 2: Compute targets and run network verification round.
8042        let targets =
8043            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8044                .await;
8045
8046        let evidence =
8047            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8048
8049        // Step 3: Evaluate results — collect outcomes without holding the write
8050        // lock across paid-list I/O.
8051        //
8052        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8053        // table and recent_provers cache up front so the synchronous
8054        // evaluate_key_evidence_with_holder_check predicate can consult
8055        // them without awaiting. The predicate downgrades a Present
8056        // claim to Unresolved unless the peer is credited for that key.
8057        // Snapshot per-peer commitment data. We need two views:
8058        //   - `commitment_by_peer_snapshot`: peers that currently have
8059        //     a verified commitment record on file (used to look up
8060        //     their current hash).
8061        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
8062        //     set. Sourced from a separate set rather than the
8063        //     commitment map so eviction (PeerRemoved cleanup, sybil
8064        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8065        //     a previously-v12 peer to "legacy" credit-unconditionally.
8066        //     Legacy / pre-v12 peers that have never sent a commitment
8067        //     remain absent from the set and are credited via the
8068        //     legacy path so mixed-version networks stay live.
8069        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8070            let map = last_commitment_by_peer.read().await;
8071            map.iter()
8072                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8073                // of every peer's ~5 KiB commitment.
8074                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8075                .collect()
8076        };
8077        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8078        // Take a full snapshot of recent_provers under the read lock,
8079        // then release. The cache is bounded (16/key × keys), so the
8080        // clone is cheap.
8081        let provers_snapshot = recent_provers.read().await.clone();
8082        // For the replica-fetch path, we need to know whether THIS
8083        // node already holds the key being verified. The v12 §6
8084        // holder-credit gate is meant to prevent uncredited Present
8085        // claims from contributing to paid-list / reward quorum for
8086        // keys we DO hold (and could audit ourselves). For keys we
8087        // are trying to FETCH (i.e. not in local storage), there is
8088        // no possible local audit credit, and gating the presence
8089        // quorum on credit would deadlock replica-repair in a
8090        // fully v12-capable close group.
8091        let mut locally_held: HashSet<XorName> = HashSet::new();
8092        for key in &keys_needing_network {
8093            if storage.exists(key).unwrap_or(false) {
8094                locally_held.insert(*key);
8095            }
8096        }
8097        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8098            if !locally_held.contains(key) {
8099                // Replica-fetch path: we don't hold this key, so we
8100                // cannot have collected audit credit for it. Trust
8101                // Present claims to drive fetch-source promotion;
8102                // chunk-PUT payment_verifier is the security backstop
8103                // when the bytes actually arrive.
8104                return true;
8105            }
8106            if !capable_peer_snapshot.contains(peer) {
8107                // Pre-v12 / legacy peer that has never gossiped a
8108                // commitment. The v12 §6 holder-eligibility check
8109                // doesn't apply: their Present evidence comes through
8110                // the legacy path and we credit it unconditionally
8111                // so a mixed-version network stays live during
8112                // transition.
8113                return true;
8114            }
8115            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8116                // Peer is commitment_capable (sticky) but currently
8117                // has no live commitment record on file (e.g. their
8118                // last gossip was evicted from the LRU cache, or it
8119                // failed verification). Withhold credit until they
8120                // re-prove storage under a fresh commitment.
8121                return false;
8122            };
8123            provers_snapshot.is_credited_holder(key, peer, hash)
8124        };
8125
8126        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8127        {
8128            let q = queues.read().await;
8129            for key in &keys_needing_network {
8130                let Some(ev) = evidence.get(key) else {
8131                    continue;
8132                };
8133                if q.get_pending(key).is_none() {
8134                    continue;
8135                }
8136                let outcome = quorum::evaluate_key_evidence_with_holder_check(
8137                    key,
8138                    ev,
8139                    &targets,
8140                    config,
8141                    holder_credit,
8142                );
8143                evaluated.push((*key, outcome));
8144            }
8145        } // read lock released
8146
8147        // Step 4: Insert verified keys into PaidForList (no lock held).
8148        let mut paid_insert_keys: Vec<XorName> = Vec::new();
8149        for (key, outcome) in &evaluated {
8150            if matches!(
8151                outcome,
8152                KeyVerificationOutcome::QuorumVerified { .. }
8153                    | KeyVerificationOutcome::PaidListVerified { .. }
8154            ) {
8155                paid_insert_keys.push(*key);
8156            }
8157        }
8158        for key in &paid_insert_keys {
8159            if let Err(e) = paid_list.insert(key).await {
8160                warn!("Failed to add verified key to PaidForList: {e}");
8161            }
8162        }
8163
8164        // Verification established validity; the paid-list insert above records
8165        // it. Downloading the bytes is a separate duty, owed only by the
8166        // storage-admission group, asked on the same terms for every verified
8167        // key — the advertising peer's replica/paid labelling is a claim about
8168        // itself and carries no authority over what we store. This check is a
8169        // cheap pre-filter that keeps never-responsible keys out of the fetch
8170        // queue entirely; the authoritative gate is the per-attempt recheck in
8171        // `execute_single_fetch`, because a key can wait in the nearest-first
8172        // fetch queue long enough for this promotion-time answer to go stale.
8173        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8174        for (key, outcome) in &evaluated {
8175            if matches!(
8176                outcome,
8177                KeyVerificationOutcome::QuorumVerified { .. }
8178                    | KeyVerificationOutcome::PaidListVerified { .. }
8179            ) && !storage.exists(key).unwrap_or(false)
8180                && is_storage_admitted(&self_id, key, p2p_node, config).await
8181            {
8182                fetch_allowed_keys.insert(*key);
8183            }
8184        }
8185
8186        // Step 5: Update queues with the evaluated outcomes.
8187        let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
8188        let mut q = queues.write().await;
8189        for (key, outcome) in evaluated {
8190            let replica_hint_sources = q
8191                .get_pending(&key)
8192                .map(|entry| entry.replica_hint_sources.clone())
8193                .unwrap_or_default();
8194            if let Some(ev) = evidence.get(&key) {
8195                if let Some(source) =
8196                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8197                {
8198                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8199                }
8200            }
8201            match outcome {
8202                KeyVerificationOutcome::QuorumVerified { sources }
8203                | KeyVerificationOutcome::PaidListVerified { sources } => {
8204                    let mut fetch_sources = sources;
8205                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8206                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8207                    if fetch_eligible && write_blocked {
8208                        // Capacity gate, second of two, and deliberately after
8209                        // Step 4: the key is now recorded in `PaidForList` and
8210                        // its verification stands. Only the download is held,
8211                        // because `execute_single_fetch` would refuse it and
8212                        // hand the key straight back here.
8213                        if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8214                            capacity_deferred_promote += 1;
8215                        }
8216                    } else if fetch_eligible && !fetch_sources.is_empty() {
8217                        // A holder answered; see the matching clear on the
8218                        // local-paid path.
8219                        q.clear_unresolved(&key);
8220                        let distance =
8221                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8222                        // Atomic remove+enqueue: on fetch_queue capacity miss
8223                        // the pending entry is preserved so this verified key
8224                        // is retried on the next cycle (no silent drop).
8225                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8226                        // Not terminal — either moved to fetch queue, or
8227                        // retained as pending until queue drains.
8228                    } else if fetch_eligible && fetch_sources.is_empty() {
8229                        no_holder_deferrals += 1;
8230                        let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8231                        let first_report = q.claim_no_holder_report(&key);
8232                        report_unresolved_deferral(
8233                            "Verified storage-admitted key",
8234                            &key,
8235                            outcome,
8236                            first_report,
8237                        );
8238                    } else {
8239                        q.remove_pending(&key);
8240                        terminal_keys.push(key);
8241                    }
8242                }
8243                KeyVerificationOutcome::QuorumFailed => {
8244                    q.remove_pending(&key);
8245                    terminal_keys.push(key);
8246                }
8247                KeyVerificationOutcome::QuorumInconclusive => {
8248                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8249                    // Backed off like any other unresolved round, but it does
8250                    // NOT claim the no-holder report: nothing yet says this key
8251                    // has no holder, so the first round that does say so must
8252                    // still be the one that warns.
8253                    let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8254                }
8255            }
8256        }
8257        drop(q);
8258
8259        for (peer, bad_hint_count) in bad_singleton_hints {
8260            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8261            warn!(
8262                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8263                 sole-source replica hints; \
8264                 reporting {reports} bounded trust failure(s)"
8265            );
8266            for _ in 0..reports {
8267                p2p_node
8268                    .report_trust_event(
8269                        &peer,
8270                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8271                    )
8272                    .await;
8273            }
8274        }
8275    }
8276
8277    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8278    // the drain condition.
8279    update_bootstrap_after_verification(
8280        &terminal_keys,
8281        bootstrap_state,
8282        queues,
8283        is_bootstrapping,
8284        bootstrap_complete_notify,
8285    )
8286    .await;
8287
8288    let (pending_after, fetch_after, in_flight_after) = {
8289        let q = queues.read().await;
8290        (
8291            q.pending_count(),
8292            q.fetch_queue_count(),
8293            q.in_flight_count(),
8294        )
8295    };
8296    let terminal_key_count = terminal_keys.len();
8297    let elapsed_ms = cycle_started.elapsed().as_millis();
8298
8299    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8300        info!(
8301            target: "ant_node::replication::verification",
8302            "Slow replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8303        );
8304    } else {
8305        debug!(
8306            target: "ant_node::replication::verification",
8307            "Replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8308        );
8309    }
8310}
8311
8312/// Report a verification round that left a key without a usable holder.
8313///
8314/// Warns once per entry — the first failure is news, and by the hundredth the
8315/// node is re-asking peers it has already exhausted. Later failures stay at
8316/// `debug`, and the per-cycle count is carried in the cycle summary so the
8317/// scale of a backlog is still visible without a line per key per retry.
8318///
8319/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8320/// number: a round may advance the count without producing a no-holder result,
8321/// and such a round must not consume the warning.
8322///
8323/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8324/// a holder clears it, so a later relapse warns again: "once per episode", not
8325/// "once ever".
8326fn report_unresolved_deferral(
8327    what: &str,
8328    key: &XorName,
8329    outcome: Option<DeferralOutcome>,
8330    first_report: bool,
8331) {
8332    let Some(outcome) = outcome else {
8333        // The entry left `pending_verify` under the same lock; nothing deferred.
8334        return;
8335    };
8336    if first_report {
8337        warn!(
8338            "{what} {} has no responding holders yet; deferring retry",
8339            hex::encode(key)
8340        );
8341    } else {
8342        debug!(
8343            "{what} {} still has no responding holders after {} attempts; \
8344             retrying in {}s",
8345            hex::encode(key),
8346            outcome.attempt,
8347            outcome.retry_after.as_secs()
8348        );
8349    }
8350}
8351
8352/// Add peers that claimed possession as fallback fetch sources.
8353///
8354/// Paid-only advertisers make no possession claim and are absent from
8355/// `replica_hint_sources` by construction, so they are never added.
8356fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8357    for source in replica_hint_sources {
8358        if !sources.contains(source) {
8359            sources.push(*source);
8360        }
8361    }
8362}
8363
8364/// Return the sole replica advertiser when either the close group definitively
8365/// rejects the key or the advertiser explicitly denies possessing it.
8366/// Paid-only advertisements, corroborated replica hints, and inconclusive
8367/// rounds without that direct contradiction are deliberately non-penalizing.
8368fn punishable_singleton_replica_hint_source(
8369    replica_hint_sources: &HashSet<PeerId>,
8370    outcome: &KeyVerificationOutcome,
8371    evidence: &crate::replication::types::KeyVerificationEvidence,
8372) -> Option<PeerId> {
8373    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8374    // reserved for peers that actually claimed possession.
8375    if replica_hint_sources.len() != 1 {
8376        return None;
8377    }
8378    let source = *replica_hint_sources.iter().next()?;
8379    let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8380    let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8381
8382    (rejected_by_close_group || denied_possession).then_some(source)
8383}
8384
8385/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8386/// bootstrap pending set and transition out of bootstrapping when drained.
8387async fn update_bootstrap_after_verification(
8388    terminal_keys: &[XorName],
8389    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8390    queues: &Arc<RwLock<ReplicationQueues>>,
8391    is_bootstrapping: &Arc<RwLock<bool>>,
8392    bootstrap_complete_notify: &Arc<Notify>,
8393) {
8394    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8395        return;
8396    }
8397    {
8398        let mut bs = bootstrap_state.write().await;
8399        for key in terminal_keys {
8400            bs.remove_key(key);
8401        }
8402    }
8403    let q = queues.read().await;
8404    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8405        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8406    }
8407}
8408
8409/// Retire bootstrap work owed by a peer that permanently left the routing
8410/// table, then immediately re-check drain so this removal can complete
8411/// bootstrap without waiting for an unrelated pipeline event.
8412async fn update_bootstrap_after_peer_removed(
8413    peer: &PeerId,
8414    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8415    queues: &Arc<RwLock<ReplicationQueues>>,
8416    is_bootstrapping: &Arc<RwLock<bool>>,
8417    bootstrap_complete_notify: &Arc<Notify>,
8418) {
8419    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8420    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8421
8422    if !orphaned_keys.is_empty() {
8423        let mut state = bootstrap_state.write().await;
8424        for key in &orphaned_keys {
8425            state.remove_key(key);
8426        }
8427    }
8428
8429    if orphaned_keys.is_empty() && !cleared_rejection {
8430        return;
8431    }
8432    let q = queues.read().await;
8433    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8434        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8435    }
8436}
8437
8438/// Periodic bootstrap-drain self-healing, run on every verification worker
8439/// tick until bootstrap drains.
8440///
8441/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8442/// recording of a capacity rejection leaves an entry no future event can
8443/// clear — `max_age` expiry is its only exit. And a clean-cycle
8444/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8445/// quiet node the drain condition can become true with nothing left to
8446/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8447/// drain itself, so this is invoked before `run_verification_cycle`'s
8448/// early-returns.
8449async fn expire_and_recheck_bootstrap_drain(
8450    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8451    queues: &Arc<RwLock<ReplicationQueues>>,
8452    is_bootstrapping: &Arc<RwLock<bool>>,
8453    bootstrap_complete_notify: &Arc<Notify>,
8454    max_age: Duration,
8455) {
8456    if bootstrap_state.read().await.is_drained() {
8457        return;
8458    }
8459    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8460    let q = queues.read().await;
8461    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8462        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8463    }
8464}
8465
8466/// Set `is_bootstrapping` to `false` and wake all waiters.
8467async fn complete_bootstrap(
8468    is_bootstrapping: &Arc<RwLock<bool>>,
8469    bootstrap_complete_notify: &Arc<Notify>,
8470) {
8471    *is_bootstrapping.write().await = false;
8472    bootstrap_complete_notify.notify_waiters();
8473    info!("Replication bootstrap complete");
8474}
8475
8476// ---------------------------------------------------------------------------
8477// Fetch types and single-fetch executor
8478// ---------------------------------------------------------------------------
8479
8480/// Result classification for a single fetch attempt.
8481enum FetchResult {
8482    /// Data fetched, integrity-checked, and stored successfully.
8483    Stored,
8484    /// Content-address integrity check failed — do not retry.
8485    IntegrityFailed,
8486    /// Source failed (network error or non-success response) — retryable.
8487    SourceFailed,
8488    /// This node could not write the chunk locally: the capacity pre-check
8489    /// refused before the dial, or `put` failed after the bytes arrived.
8490    ///
8491    /// Distinct from [`Self::SourceFailed`] because nothing about the source
8492    /// is implicated, and because the remedy is the opposite one. A source
8493    /// failure should move on to the next holder; a local write failure must
8494    /// not — every remaining source would send the same chunk into the same
8495    /// full disk. The key returns to verification instead, so a later cycle
8496    /// retries it once local capacity allows. That is a retry path, not a
8497    /// liveness guarantee: `evict_stale` still expires the entry at
8498    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8499    /// which re-acquisition depends on a fresh hint.
8500    LocalWriteFailed,
8501    /// This node already holds the key, so there is nothing to fetch —
8502    /// terminal, exactly like [`Self::Stored`], because the duty is already
8503    /// discharged.
8504    ///
8505    /// Responsibility is rechecked at download time; possession has to be too.
8506    /// The earlier gates already drop held keys out of the fetch pipeline —
8507    /// `queue_admitted_hints` skips them, and the promotion-time
8508    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8509    /// them. (`is_relevant` is not one of them: possession there makes a key
8510    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8511    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8512    /// client PUT, or another source landing first. The nearest-first fetch
8513    /// queue is deep enough for that window to be real.
8514    ///
8515    /// This check must also precede the capacity pre-check below, because
8516    /// `LmdbStorage::put` tests `exists` *before* it tests disk space: without
8517    /// it, a full node would decline a key it already holds, which `put` would
8518    /// have accepted as a duplicate.
8519    AlreadyHeld,
8520    /// Live routing state no longer places this node in the storage-admission
8521    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8522    /// the fetch was serving has lapsed, so no alternate source is tried and
8523    /// no trust event is reported: the source did nothing wrong.
8524    NoLongerResponsible,
8525}
8526
8527/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8528/// worker loop to update queue state.
8529struct FetchOutcome {
8530    key: XorName,
8531    result: FetchResult,
8532}
8533
8534/// What the fetch worker must do next for a key whose fetch attempt resolved.
8535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8536enum FetchFollowUp {
8537    /// The key terminally left the fetch pipeline (its in-flight entry is
8538    /// removed and any verification retry-slot reservation released); the
8539    /// caller must run bootstrap accounting for it.
8540    Terminal,
8541    /// The key returned to `pending_verify` for a later verification round.
8542    RequeuedForVerification,
8543    /// Retry immediately from this next untried verified source.
8544    RetryFrom(PeerId),
8545}
8546
8547/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8548///
8549/// Split out of the fetch-worker loop so the per-variant queue transitions
8550/// are unit-testable without a live network. The caller holds the queues
8551/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8552/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8553/// retry-slot reservation, and the caller's terminal handling shrinks the
8554/// bootstrap pending set — dropping the key without that accounting would
8555/// stall bootstrap drain forever.
8556///
8557/// The nursery `option_if_let_else` rewrite is impossible here: both
8558/// `map_or_else` closures would need `&mut *q` simultaneously.
8559#[allow(clippy::option_if_let_else)]
8560fn apply_fetch_result(
8561    q: &mut ReplicationQueues,
8562    key: &XorName,
8563    result: &FetchResult,
8564    verification_retry_after: Duration,
8565) -> FetchFollowUp {
8566    match result {
8567        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8568            q.complete_fetch(key);
8569            FetchFollowUp::Terminal
8570        }
8571        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8572            if let Some(next_peer) = q.retry_fetch(key) {
8573                FetchFollowUp::RetryFrom(next_peer)
8574            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8575                FetchFollowUp::RequeuedForVerification
8576            } else {
8577                FetchFollowUp::Terminal
8578            }
8579        }
8580        // No `retry_fetch`: the local write is what failed, so every other
8581        // source would be asked to send the same chunk into the same full
8582        // disk. Requeueing for verification is what keeps the key from being
8583        // stranded — it comes back once capacity allows — and the fallthrough
8584        // to `Terminal` when there is no retry metadata is what keeps
8585        // bootstrap drain accounting correct, exactly as for a source failure.
8586        //
8587        // The ordinary requeue delay, deliberately. A standing capacity block
8588        // does not need a longer one here: the key returns to pending, and the
8589        // gate at the head of the next cycle defers it for minutes. A separate
8590        // backoff on this path would duplicate that to save one 15 s round, on
8591        // a race the gate already makes rare.
8592        FetchResult::LocalWriteFailed => {
8593            if q.requeue_fetch_for_verification(key, verification_retry_after) {
8594                FetchFollowUp::RequeuedForVerification
8595            } else {
8596                FetchFollowUp::Terminal
8597            }
8598        }
8599    }
8600}
8601
8602/// Whether this node currently sits inside the storage-admission group for
8603/// `key`, per live local routing state.
8604///
8605/// This is the one question every storage decision in this module asks; see
8606/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8607/// network I/O — but it awaits into the DHT manager, so callers must not
8608/// hold the queues lock across it.
8609async fn is_storage_admitted(
8610    self_id: &PeerId,
8611    key: &XorName,
8612    p2p_node: &Arc<P2PNode>,
8613    config: &ReplicationConfig,
8614) -> bool {
8615    admission::is_responsible(
8616        self_id,
8617        key,
8618        p2p_node,
8619        storage_admission_width(config.close_group_size),
8620    )
8621    .await
8622}
8623
8624#[allow(clippy::too_many_lines)]
8625/// Execute a single fetch request against `source` for `key`.
8626///
8627/// Handles encoding, network I/O, integrity checking, storage, and trust
8628/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8629/// queue state without holding any locks during the network round-trip.
8630///
8631/// This is the authoritative storage-responsibility gate: each attempt —
8632/// including every per-source retry, which re-enters here — rechecks live
8633/// routing state before spending bandwidth, and once more before writing
8634/// bytes that arrived after a round-trip. The verification-time check that
8635/// promoted the key into the fetch queue is only a pre-filter; the queue is
8636/// nearest-first and deep, so a promotion decision can go stale under
8637/// topology churn before the key is ever dequeued.
8638async fn execute_single_fetch(
8639    p2p_node: Arc<P2PNode>,
8640    storage: Arc<LmdbStorage>,
8641    config: Arc<ReplicationConfig>,
8642    key: XorName,
8643    source: PeerId,
8644) -> FetchOutcome {
8645    let self_id = *p2p_node.peer_id();
8646    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8647        debug!(
8648            "Skipping fetch for {}: no longer in the storage-admission group",
8649            hex::encode(key)
8650        );
8651        return FetchOutcome {
8652            key,
8653            result: FetchResult::NoLongerResponsible,
8654        };
8655    }
8656
8657    // Possession, then capacity — both before the dial, and in that order.
8658    //
8659    // `LmdbStorage::put` tests `exists` before it tests disk space, so a full
8660    // node still accepts a key it already holds. Checking possession first is
8661    // what keeps this pair of gates from declining work `put` would have
8662    // taken.
8663    if storage.exists(&key).unwrap_or(false) {
8664        debug!(
8665            "Skipping fetch for {}: already held locally",
8666            hex::encode(key)
8667        );
8668        return FetchOutcome {
8669            key,
8670            result: FetchResult::AlreadyHeld,
8671        };
8672    }
8673
8674    // Capacity is checked before the dial rather than after the bytes arrive.
8675    // `put` runs this same check on every write of a key it does not already
8676    // hold, so this reaches the same verdict `put` would reach *at this
8677    // instant*. It is not a guarantee about the later write: both answers can
8678    // change across the round trip. Space freed in between would have let a
8679    // post-download `put` succeed, so a refusal here can cost a fleeting
8680    // acquisition and one retry cycle of delay; space lost in between is why
8681    // the check inside `put` still has to stay.
8682    //
8683    // What it buys is that the refusal costs no bandwidth. Without it a
8684    // disk-full node pulls the whole chunk over the network first, and the
8685    // failure is then classified as the source's — no trust event, but the
8686    // worker walks to every remaining holder, and each re-uploads the same
8687    // chunk into the same full disk.
8688    if let Err(e) = storage.check_capacity() {
8689        debug!(
8690            "Skipping fetch for {}: local storage cannot accept a write: {e}",
8691            hex::encode(key)
8692        );
8693        return FetchOutcome {
8694            key,
8695            result: FetchResult::LocalWriteFailed,
8696        };
8697    }
8698
8699    let request = protocol::FetchRequest { key };
8700    let msg = ReplicationMessage {
8701        request_id: rand::thread_rng().gen::<u64>(),
8702        body: ReplicationMessageBody::FetchRequest(request),
8703    };
8704
8705    let encoded = match msg.encode() {
8706        Ok(data) => data,
8707        Err(e) => {
8708            warn!("Failed to encode fetch request: {e}");
8709            return FetchOutcome {
8710                key,
8711                result: FetchResult::SourceFailed,
8712            };
8713        }
8714    };
8715
8716    let result = p2p_node
8717        .send_request(
8718            &source,
8719            REPLICATION_PROTOCOL_ID,
8720            encoded,
8721            config.fetch_request_timeout,
8722        )
8723        .await;
8724
8725    match result {
8726        Ok(response) => {
8727            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8728                p2p_node
8729                    .report_trust_event(
8730                        &source,
8731                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8732                    )
8733                    .await;
8734                return FetchOutcome {
8735                    key,
8736                    result: FetchResult::SourceFailed,
8737                };
8738            };
8739
8740            match resp_msg.body {
8741                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8742                    key: resp_key,
8743                    data,
8744                }) => {
8745                    // Validate the response key matches the requested key.
8746                    // A malicious peer could serve valid data for a different
8747                    // key, passing integrity checks while the requested key
8748                    // is falsely marked as fetched.
8749                    if resp_key != key {
8750                        warn!(
8751                            "Fetch response key mismatch: requested {}, got {}",
8752                            hex::encode(key),
8753                            hex::encode(resp_key)
8754                        );
8755                        p2p_node
8756                            .report_trust_event(
8757                                &source,
8758                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8759                            )
8760                            .await;
8761                        return FetchOutcome {
8762                            key,
8763                            result: FetchResult::IntegrityFailed,
8764                        };
8765                    }
8766
8767                    // Enforce chunk size invariant on fetched data.
8768                    // Checked before the content-address hash to avoid
8769                    // hashing up to 10 MiB of oversized junk data.
8770                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8771                        warn!(
8772                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8773                            hex::encode(resp_key),
8774                            data.len(),
8775                            crate::ant_protocol::MAX_CHUNK_SIZE,
8776                        );
8777                        p2p_node
8778                            .report_trust_event(
8779                                &source,
8780                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8781                            )
8782                            .await;
8783                        return FetchOutcome {
8784                            key,
8785                            result: FetchResult::IntegrityFailed,
8786                        };
8787                    }
8788
8789                    // Content-address integrity check.
8790                    let computed = crate::client::compute_address(&data);
8791                    if computed != resp_key {
8792                        warn!(
8793                            "Fetched record integrity check failed: expected {}, got {}",
8794                            hex::encode(resp_key),
8795                            hex::encode(computed)
8796                        );
8797                        p2p_node
8798                            .report_trust_event(
8799                                &source,
8800                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8801                            )
8802                            .await;
8803                        return FetchOutcome {
8804                            key,
8805                            result: FetchResult::IntegrityFailed,
8806                        };
8807                    }
8808
8809                    // Responsibility can lapse during the network round-trip.
8810                    // The bandwidth is already spent; declining the write is
8811                    // what still avoids the disk write and the later
8812                    // fetch→store→prune churn. Edge flapping is dampened by
8813                    // the margin `storage_admission_width` adds over
8814                    // `close_group_size`.
8815                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8816                        debug!(
8817                            "Fetched {} but responsibility lapsed in transit; not storing",
8818                            hex::encode(key)
8819                        );
8820                        return FetchOutcome {
8821                            key,
8822                            result: FetchResult::NoLongerResponsible,
8823                        };
8824                    }
8825
8826                    if let Err(e) = storage.put(&resp_key, &data).await {
8827                        // The bytes arrived and passed the content-address
8828                        // check, so the source did its job; the failure is
8829                        // entirely local (disk-full, or an LMDB error). Any
8830                        // valid source must serve identical content, so trying
8831                        // the next one cannot cure a local error — it only
8832                        // re-downloads the same chunk into the same store.
8833                        warn!(
8834                            "Failed to store fetched record {}: {e}",
8835                            hex::encode(resp_key)
8836                        );
8837                        return FetchOutcome {
8838                            key,
8839                            result: FetchResult::LocalWriteFailed,
8840                        };
8841                    }
8842
8843                    FetchOutcome {
8844                        key,
8845                        result: FetchResult::Stored,
8846                    }
8847                }
8848                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::NotFound {
8849                    ..
8850                }) => {
8851                    // This peer was selected as a fetch source because it
8852                    // recently answered `Present` during verification. A
8853                    // subsequent NotFound is evidence of a stale/false claim
8854                    // or chunk wiping, so penalize lightly and try another
8855                    // verified source.
8856                    warn!(
8857                        "Fetch: verified source {source} returned NotFound for {}",
8858                        hex::encode(key)
8859                    );
8860                    p2p_node
8861                        .report_trust_event(
8862                            &source,
8863                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8864                        )
8865                        .await;
8866                    FetchOutcome {
8867                        key,
8868                        result: FetchResult::SourceFailed,
8869                    }
8870                }
8871                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Error {
8872                    reason,
8873                    ..
8874                }) => {
8875                    warn!(
8876                        "Fetch: peer {source} returned error for {}: {reason}",
8877                        hex::encode(key)
8878                    );
8879                    p2p_node
8880                        .report_trust_event(
8881                            &source,
8882                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8883                        )
8884                        .await;
8885                    FetchOutcome {
8886                        key,
8887                        result: FetchResult::SourceFailed,
8888                    }
8889                }
8890                _ => {
8891                    // Unexpected message type — treat as malformed.
8892                    p2p_node
8893                        .report_trust_event(
8894                            &source,
8895                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8896                        )
8897                        .await;
8898                    FetchOutcome {
8899                        key,
8900                        result: FetchResult::SourceFailed,
8901                    }
8902                }
8903            }
8904        }
8905        Err(e) => {
8906            debug!("Fetch request to {source} failed: {e}");
8907            // No ApplicationFailure here — P2PNode::send_request() already
8908            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
8909            FetchOutcome {
8910                key,
8911                result: FetchResult::SourceFailed,
8912            }
8913        }
8914    }
8915}
8916
8917// ---------------------------------------------------------------------------
8918// Audit result handler
8919// ---------------------------------------------------------------------------
8920
8921/// Format the first confirmed-failed key as a 16-hex-char label.
8922///
8923/// Pairs with `challenged_peer` to form a stable cross-host correlation
8924/// handle in the audit-failure log line, e.g.
8925///
8926/// ```text
8927/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
8928/// ```
8929///
8930/// Falls back to `"0x"` when the list is empty so the log line never
8931/// contains a misleading default.
8932fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
8933    confirmed_failed_keys.first().map_or_else(
8934        || "0x".to_string(),
8935        |k| format!("0x{}", hex::encode(&k[..8])),
8936    )
8937}
8938
8939/// Execute the side effects for a subtree storage-commitment audit failure.
8940///
8941/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
8942/// legitimately time out on slow or loaded honest peers, so it never touches the
8943/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
8944/// failures still penalise immediately and revoke holder credit.
8945async fn handle_subtree_failed_audit(
8946    challenged_peer: &PeerId,
8947    confirmed_failed_key_count: usize,
8948    reason: &AuditFailureReason,
8949    p2p_node: &Arc<P2PNode>,
8950    sync_state: &Arc<RwLock<NeighborSyncState>>,
8951    recent_provers: &Arc<RwLock<RecentProvers>>,
8952) {
8953    if matches!(reason, AuditFailureReason::Timeout) {
8954        debug!(
8955            "Audit timeout for {challenged_peer} fully graced \
8956             (subtree audit does not evict on timeout)"
8957        );
8958        return;
8959    }
8960
8961    // The caller already logged the rich failure line with reason + per-category
8962    // summary; avoid a redundant second error log here.
8963    let _ = confirmed_failed_key_count;
8964    {
8965        let mut state = sync_state.write().await;
8966        state.clear_active_bootstrap_claim(challenged_peer);
8967    }
8968    {
8969        let mut provers_guard = recent_provers.write().await;
8970        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
8971    }
8972    p2p_node
8973        .report_trust_event(
8974            challenged_peer,
8975            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
8976        )
8977        .await;
8978}
8979
8980/// Handle audit result: log findings and emit trust events.
8981async fn handle_subtree_audit_result(
8982    result: &AuditTickResult,
8983    p2p_node: &Arc<P2PNode>,
8984    sync_state: &Arc<RwLock<NeighborSyncState>>,
8985    recent_provers: &Arc<RwLock<RecentProvers>>,
8986    config: &ReplicationConfig,
8987) {
8988    match result {
8989        AuditTickResult::Passed {
8990            challenged_peer,
8991            keys_checked,
8992        } => {
8993            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
8994            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
8995            // Peer responded normally — clear the active bootstrap claim while
8996            // retaining history so a later claim is treated as repeated abuse.
8997            {
8998                let mut state = sync_state.write().await;
8999                state.clear_active_bootstrap_claim(challenged_peer);
9000            }
9001            p2p_node
9002                .report_trust_event(
9003                    challenged_peer,
9004                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9005                )
9006                .await;
9007        }
9008        AuditTickResult::Failed {
9009            evidence,
9010            no_response_class,
9011        } => {
9012            if let FailureEvidence::AuditFailure {
9013                challenged_peer,
9014                confirmed_failed_keys,
9015                summary,
9016                reason,
9017                ..
9018            } = evidence
9019            {
9020                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9021                // Rich diagnostics (from main's audit-failure logging) + the
9022                // first-failed-key correlation handle.
9023                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9024                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9025                error!(
9026                    "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}",
9027                    audit_failure_class,
9028                    confirmed_failed_keys.len(),
9029                    summary.challenged_keys,
9030                    summary.absent_keys,
9031                    summary.digest_mismatch_keys,
9032                );
9033                // Route the side effects through the subtree-only failure path.
9034                // Responsible-chunk `AuditChallenge` handling intentionally uses
9035                // its own old immediate-penalty handler below.
9036                handle_subtree_failed_audit(
9037                    challenged_peer,
9038                    confirmed_failed_keys.len(),
9039                    reason,
9040                    p2p_node,
9041                    sync_state,
9042                    recent_provers,
9043                )
9044                .await;
9045            }
9046        }
9047        AuditTickResult::BootstrapClaim { peer } => {
9048            // Gap 6: BootstrapClaimAbuse grace period in audit path.
9049            // Separate state mutation from network I/O to avoid holding the
9050            // write lock across report_trust_event.
9051            let should_report = {
9052                let now = Instant::now();
9053                let mut state = sync_state.write().await;
9054                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9055                {
9056                    BootstrapClaimObservation::WithinGrace { .. } => {
9057                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9058                        false
9059                    }
9060                    BootstrapClaimObservation::PastGrace { first_seen } => {
9061                        warn!(
9062                            "Audit: peer {peer} claiming bootstrap past grace period \
9063                             ({:?} > {:?}), reporting abuse",
9064                            now.duration_since(first_seen),
9065                            config.bootstrap_claim_grace_period,
9066                        );
9067                        true
9068                    }
9069                    BootstrapClaimObservation::Repeated { first_seen } => {
9070                        warn!(
9071                            "Audit: peer {peer} repeated bootstrap claim after previously \
9072                             stopping; first claim was {:?} ago, reporting abuse",
9073                            now.duration_since(first_seen),
9074                        );
9075                        true
9076                    }
9077                }
9078            };
9079            if should_report {
9080                p2p_node
9081                    .report_trust_event(
9082                        peer,
9083                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9084                    )
9085                    .await;
9086            }
9087        }
9088        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9089    }
9090}
9091
9092/// Whether a confirmed audit failure with this reason clears the peer's active
9093/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9094/// bootstrapping); every confirmed storage-integrity reason does.
9095///
9096/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9097/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9098/// still reports the normal audit trust penalty.
9099fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9100    !matches!(reason, AuditFailureReason::Timeout)
9101}
9102
9103/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9104/// events and manage bootstrap-claim state.
9105///
9106/// This is intentionally separate from the subtree audit result handler. A
9107/// responsible-chunk `AuditChallenge` `Failed` result reports
9108/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9109/// restoring the pre-ADR-0002 behaviour.
9110#[allow(clippy::too_many_lines)]
9111async fn handle_audit_result(
9112    result: &AuditTickResult,
9113    p2p_node: &Arc<P2PNode>,
9114    sync_state: &Arc<RwLock<NeighborSyncState>>,
9115    config: &ReplicationConfig,
9116) {
9117    match result {
9118        AuditTickResult::Passed {
9119            challenged_peer,
9120            keys_checked,
9121        } => {
9122            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9123            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9124            {
9125                let mut state = sync_state.write().await;
9126                state.clear_active_bootstrap_claim(challenged_peer);
9127            }
9128            p2p_node
9129                .report_trust_event(
9130                    challenged_peer,
9131                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9132                )
9133                .await;
9134        }
9135        AuditTickResult::Failed {
9136            evidence,
9137            no_response_class,
9138        } => {
9139            if let FailureEvidence::AuditFailure {
9140                challenged_peer,
9141                confirmed_failed_keys,
9142                summary,
9143                reason,
9144                ..
9145            } = evidence
9146            {
9147                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9148                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9149                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9150                error!(
9151                    "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}",
9152                    audit_failure_class,
9153                    confirmed_failed_keys.len(),
9154                    summary.challenged_keys,
9155                    summary.absent_keys,
9156                    summary.digest_mismatch_keys,
9157                );
9158                if audit_failure_clears_bootstrap_claim(reason) {
9159                    let mut state = sync_state.write().await;
9160                    state.clear_active_bootstrap_claim(challenged_peer);
9161                } else {
9162                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9163                }
9164                p2p_node
9165                    .report_trust_event(
9166                        challenged_peer,
9167                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9168                    )
9169                    .await;
9170            }
9171        }
9172        AuditTickResult::BootstrapClaim { peer } => {
9173            let should_report = {
9174                let now = Instant::now();
9175                let mut state = sync_state.write().await;
9176                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9177                {
9178                    BootstrapClaimObservation::WithinGrace { .. } => {
9179                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9180                        false
9181                    }
9182                    BootstrapClaimObservation::PastGrace { first_seen } => {
9183                        warn!(
9184                            "Audit: peer {peer} claiming bootstrap past grace period \
9185                             ({:?} > {:?}), reporting abuse",
9186                            now.duration_since(first_seen),
9187                            config.bootstrap_claim_grace_period,
9188                        );
9189                        true
9190                    }
9191                    BootstrapClaimObservation::Repeated { first_seen } => {
9192                        warn!(
9193                            "Audit: peer {peer} repeated bootstrap claim after previously \
9194                             stopping; first claim was {:?} ago, reporting abuse",
9195                            now.duration_since(first_seen),
9196                        );
9197                        true
9198                    }
9199                }
9200            };
9201            if should_report {
9202                p2p_node
9203                    .report_trust_event(
9204                        peer,
9205                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9206                    )
9207                    .await;
9208            }
9209        }
9210        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9211    }
9212}
9213
9214/// Whether a confirmed audit failure with this reason should revoke the
9215/// peer's `recent_provers` holder credit immediately (v12 §6).
9216///
9217/// `true` for any reason where the peer actually answered (or admitted
9218/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9219/// bytes for committed key"), `MalformedResponse` — these prove the
9220/// peer no longer holds what it committed to, so it must not keep
9221/// holder credit for the proof TTL. `false` for `Timeout`: a single
9222/// dropped packet must not strip an honest peer; the 40-min TTL is the
9223/// deliberate liveness cushion there.
9224fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9225    !matches!(reason, AuditFailureReason::Timeout)
9226}
9227
9228/// Apply the holder-credit revocation decision for a confirmed audit
9229/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9230/// testable without a live `P2PNode`: the production `Failed` arm of
9231/// `handle_subtree_audit_result` calls exactly this.
9232fn apply_audit_failure_credit_revocation(
9233    provers: &mut RecentProvers,
9234    challenged_peer: &PeerId,
9235    reason: &AuditFailureReason,
9236) {
9237    if audit_failure_revokes_holder_credit(reason) {
9238        provers.forget_peer(challenged_peer);
9239    }
9240}
9241
9242// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9243
9244// ---------------------------------------------------------------------------
9245// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9246// ---------------------------------------------------------------------------
9247
9248/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9249/// message handler passes one value instead of a long argument list; all
9250/// fields are cheap `Arc` clones.
9251#[derive(Clone)]
9252struct GossipAuditTrigger {
9253    p2p_node: Arc<P2PNode>,
9254    config: Arc<ReplicationConfig>,
9255    recent_provers: Arc<RwLock<RecentProvers>>,
9256    sync_state: Arc<RwLock<NeighborSyncState>>,
9257    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9258    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9259    /// only when a real audit is about to be sent — never by a losing lottery
9260    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9261    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9262    detached_task_tracker: TaskTracker,
9263    /// Gossip-private lottery attempt window: stamped on every roll (win or
9264    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9265    /// The first-audit scheduler never reads this map.
9266    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9267}
9268
9269/// What a gossip ingest yields for the audit trigger: the commitment hash to
9270/// pin and the `key_count` needed to size the response deadline from the actual
9271/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9272/// or not) so a stable-keyset node stays auditable — not just on its first
9273/// commitment.
9274#[derive(Debug, Clone, Copy)]
9275struct AuditTarget {
9276    pin_hash: [u8; 32],
9277    key_count: u32,
9278}
9279
9280/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9281/// verifier's cross-check so it can receive a **deterministic first audit**.
9282///
9283/// Sent from the verifier to the replication engine's first-audit drainer. The
9284/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9285/// audits of the same peer revert to the gossip lottery), orders most-recently-
9286/// monetized first, and runs the same `run_subtree_audit` under the same
9287/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9288#[derive(Debug, Clone, Copy)]
9289pub struct MonetizedPinEvent {
9290    /// The peer whose commitment backed the payment.
9291    pub peer: PeerId,
9292    /// The pinned commitment hash.
9293    pub pin: [u8; 32],
9294    /// The committed key count (sizes the audit deadline).
9295    pub key_count: u32,
9296    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9297    /// pin whose quote is older than the answerability window (ADR-0004 A1
9298    /// guardrail A): with grace removed, challenging an aged-out pin would
9299    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9300    pub quote_ts: SystemTime,
9301}
9302
9303/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9304/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9305/// stamps `now`), `false` if it was audited within
9306/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9307/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9308/// without a live node: a burst of gossips from one peer yields at most one
9309/// `true` per cooldown window.
9310fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9311    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9312    let known = match map.get(peer) {
9313        Some(&last) => {
9314            if now.saturating_duration_since(last) < cooldown {
9315                return false;
9316            }
9317            true
9318        }
9319        None => false,
9320    };
9321    // Bound the map under churn like its siblings (drop the oldest stamp) before
9322    // admitting a brand-new peer.
9323    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9324        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9325            map.remove(&victim);
9326        }
9327    }
9328    map.insert(*peer, now);
9329    true
9330}
9331
9332/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9333/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9334/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9335/// already covered; the authoritative check-and-stamp still runs at promotion,
9336/// so this is only an optimization and never the security boundary.
9337fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9338    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9339    map.get(peer).map_or(true, |&last| {
9340        now.saturating_duration_since(last) >= cooldown
9341    })
9342}
9343
9344/// The gossip-audit launch decision in ONE place so the ordering is shared
9345/// between production and its test (ADR-0002 "occasional surprise exams").
9346///
9347/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9348/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9349/// sampled first, a gossip flood would re-roll it on every message until one
9350/// won, multiplying audits, so each peer gets at most one lottery roll per
9351/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9352/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9353/// also consults — only after a WIN, i.e. only when a real audit is about to be
9354/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9355/// wire, so it must not defer a paid first audit (repeatable losses could
9356/// otherwise hold a monetized pin past its answerability window). Production
9357/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9358/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9359/// here fails the test.
9360fn audit_launch_decision(
9361    attempts: &mut HashMap<PeerId, Instant>,
9362    launched: &mut HashMap<PeerId, Instant>,
9363    peer: &PeerId,
9364    now: Instant,
9365    lottery_wins: bool,
9366) -> bool {
9367    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9368    // window even on a loss; private to the gossip path).
9369    if !cooldown_allows_audit(attempts, peer, now) {
9370        return false;
9371    }
9372    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9373    // shared.
9374    if !lottery_wins {
9375        return false;
9376    }
9377    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9378    // either path still suppresses this launch), stamped only on launch.
9379    cooldown_allows_audit(launched, peer, now)
9380}
9381
9382/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9383/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9384/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9385/// handling is never blocked on a network round-trip.
9386async fn maybe_trigger_gossip_audit(
9387    trigger: &GossipAuditTrigger,
9388    peer: &PeerId,
9389    target: AuditTarget,
9390) {
9391    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9392    // lives in the pure `audit_launch_decision` so the ordering is shared with
9393    // its test. Sample the lottery here, then let the helper apply the gates.
9394    let now = Instant::now();
9395    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9396    {
9397        // Lock order: attempts before the shared cooldown; this is the only
9398        // place both are held together.
9399        let mut attempts = trigger.lottery_attempts.write().await;
9400        let mut launched = trigger.cooldown.write().await;
9401        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9402            return;
9403        }
9404    }
9405
9406    let detached_task_tracker = trigger.detached_task_tracker.clone();
9407    let trigger = trigger.clone();
9408    let peer = *peer;
9409    detached_task_tracker.spawn(async move {
9410        let credit = storage_commitment_audit::AuditCredit {
9411            recent_provers: &trigger.recent_provers,
9412        };
9413        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9414            &trigger.p2p_node,
9415            &trigger.config,
9416            &peer,
9417            target.pin_hash,
9418            target.key_count,
9419            Some(&credit),
9420            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9421        )
9422        .await;
9423        handle_subtree_audit_result(
9424            &result,
9425            &trigger.p2p_node,
9426            &trigger.sync_state,
9427            &trigger.recent_provers,
9428            &trigger.config,
9429        )
9430        .await;
9431    });
9432}
9433
9434/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9435///
9436/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9437/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9438/// of its last attempt. Holds one write lock across the decision so two
9439/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9440/// caller's expensive verify so a slow/failed verify still rate-limits the next
9441/// message. Bounds the map under a flood of distinct peer ids.
9442async fn sig_verify_rate_limit_ok(
9443    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9444    source: &PeerId,
9445    now: Instant,
9446) -> bool {
9447    let mut attempts = sig_verify_attempts.write().await;
9448    if let Some(&last) = attempts.get(source) {
9449        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9450            return false;
9451        }
9452    }
9453    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9454        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9455            attempts.remove(&victim);
9456        }
9457    }
9458    attempts.insert(*source, now);
9459    true
9460}
9461
9462/// Verify + store an inbound commitment from a gossip peer.
9463///
9464/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9465/// the bootstrap-sync loop. Drops the commitment unless all five gates
9466/// pass:
9467///   1. `source` is in our DHT routing table (sybil/churn cap).
9468///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9469///      binding to the authenticated transport peer).
9470///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9471///      (the embedded pubkey actually belongs to the claimed identity —
9472///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9473///   4. `verify_commitment_signature(commitment)` succeeds against the
9474///      embedded public key. The signed payload binds the pubkey, so an
9475///      adversary cannot swap the key while keeping the body.
9476///   5. The cache has room or this is an update for an existing entry
9477///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9478///
9479/// On all-pass, the commitment is stored as the auditor's per-peer
9480/// "last known commitment" for use as `expected_commitment_hash` in
9481/// future audits.
9482///
9483/// Failures (no commitment / mismatched peer id / bad signature) are
9484/// silent drops — gossip is best-effort and a malformed commitment from
9485/// one peer should not affect anything else.
9486///
9487/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9488/// or not its root changed), so the caller can run a probabilistic,
9489/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9490/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9491/// being auditable, so it cannot pass one audit and then delete data while
9492/// re-gossiping the same root forever. The cooldown + probability bound the
9493/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9494/// gate) or there is nothing to pin.
9495///
9496/// Handle a capable peer gossiping `None` (a commitment downgrade).
9497///
9498/// A capable peer that previously gossiped a commitment but now gossips `None`
9499/// is trying to drop off the audit path. Within the answerability window we keep
9500/// the cached commitment pinned AND return it as an audit target so this gossip
9501/// still schedules a subtree audit against the peer's last known commitment — if
9502/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9503/// the trigger MUST fire here or the downgrade is never re-challenged).
9504///
9505/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9506/// honours for its own retired commitment: once that elapses since we last
9507/// received the peer's commitment, an honest peer has legitimately retired that
9508/// root (its responder side `retire_current`s and lets it age out) and can no
9509/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9510/// failure, so we then forget the cached commitment (keeping the sticky
9511/// `commitment_capable` bit) and stop pinning it.
9512async fn handle_commitment_downgrade(
9513    source: &PeerId,
9514    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9515) -> Option<AuditTarget> {
9516    let now = Instant::now();
9517    let cached = {
9518        let map = last_commitment_by_peer.read().await;
9519        map.get(source).and_then(|rec| {
9520            if !rec.commitment_capable {
9521                return None;
9522            }
9523            let last = rec.last_commitment()?;
9524            let pin = rec.commitment_hash()?;
9525            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9526            Some((pin, last.key_count, fresh))
9527        })
9528    };
9529    match cached {
9530        Some((pin, key_count, true)) => {
9531            warn!(
9532                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9533                 (downgrade attempt); auditing against its last cached commitment"
9534            );
9535            Some(AuditTarget {
9536                pin_hash: pin,
9537                key_count,
9538            })
9539        }
9540        Some((_, _, false)) => {
9541            // Cached commitment has aged past the answerability window — forget
9542            // it so we stop pinning a root the peer is no longer obliged to
9543            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9544            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9545            // from this peer may have refreshed `received_at` in the gap between
9546            // our read and write locks; if so, leave its fresh commitment intact.
9547            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9548                let still_stale =
9549                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9550                if still_stale {
9551                    rec.clear_commitment();
9552                    debug!(
9553                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9554                         commitment aged past the answerability TTL; forgetting it"
9555                    );
9556                }
9557            }
9558            None
9559        }
9560        None => None,
9561    }
9562}
9563
9564async fn ingest_peer_commitment(
9565    source: &PeerId,
9566    commitment: Option<&StorageCommitment>,
9567    p2p_node: &Arc<P2PNode>,
9568    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9569    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9570    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9571) -> Option<AuditTarget> {
9572    let Some(c) = commitment else {
9573        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9574    };
9575    // RT-membership gate: only accept commitments from peers in our
9576    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9577    // populate the cache, which closes the hole where a flood of
9578    // off-RT identities could fill the cap and evict honest
9579    // peers. The neighbor-sync request handler applies the same gate
9580    // before admitting inbound replication hints (see neighbor_sync.rs
9581    // `sender_in_rt`); we mirror that policy here for the commitment
9582    // piggyback.
9583    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9584        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9585        return None;
9586    }
9587    // Peer-id binding: the commitment's claimed sender must match the
9588    // authenticated transport peer (`source`). Defeats relay/replay
9589    // and also pins which embedded public key we are about to verify
9590    // against — the verify itself trusts the embedded key, so the
9591    // peer-id binding is the link to a real identity.
9592    if &c.sender_peer_id != source.as_bytes() {
9593        warn!(
9594            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9595             (dropped, possible relay attempt)"
9596        );
9597        return None;
9598    }
9599    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9600    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9601    // with a throwaway key they own and lie about which identity it
9602    // belongs to (the embedded-key signature would verify trivially).
9603    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9604    if derived_peer_id != c.sender_peer_id {
9605        warn!(
9606            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9607             {source} (dropped, throwaway-key attack)"
9608        );
9609        return None;
9610    }
9611    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9612    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9613    // sybil/RT-membership-bypassing peer that flooded valid-looking
9614    // gossip would otherwise burn CPU on every message. The rate
9615    // limit is checked AFTER cheap structural gates (RT, peer-id
9616    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9617    //
9618    // Tracked in `sig_verify_attempts` (separate from
9619    // last_commitment_by_peer) so EVERY attempt — successful or not —
9620    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9621    // would skip the cap for peers we've never successfully verified,
9622    // letting a flood of invalid-but-structurally-plausible gossips
9623    // burn CPU.
9624    let now = Instant::now();
9625    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9626        debug!(
9627            "ingest_peer_commitment: rate-limited sig verify from {source} \
9628             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9629        );
9630        return None;
9631    }
9632    // Signature verify, using the public key embedded in the commitment
9633    // itself. The pubkey is bound by the signature payload (see
9634    // commitment_signed_payload) so an adversary cannot keep the body
9635    // and swap the key to one they hold the secret for.
9636    if !crate::replication::commitment::verify_commitment_signature(c) {
9637        warn!(
9638            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9639             (dropped, forged commitment)"
9640        );
9641        return None;
9642    }
9643    // The new commitment's hash, used to store and to pin for the audit target.
9644    let new_hash = commitment_hash(c);
9645    let mut map = last_commitment_by_peer.write().await;
9646    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9647    // evict an arbitrary existing entry to make room. Updates for peers
9648    // already in the map are always accepted (they replace, not grow).
9649    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9650        // Drop one arbitrary entry. HashMap iter order is random which
9651        // is fine — over time PeerRemoved cleanup keeps the working set
9652        // anchored on the real RT membership; this cap only fires under
9653        // active flooding attempts.
9654        if let Some(victim) = map.keys().next().copied() {
9655            map.remove(&victim);
9656            warn!(
9657                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9658                 evicted {victim} to admit {source}"
9659            );
9660        }
9661    }
9662    // Preserve sticky commitment_capable across updates — once true,
9663    // always true. New entries start with capable = true (we just
9664    // verified a valid commitment from this peer).
9665    map.entry(*source)
9666        .and_modify(|r| {
9667            // set_commitment refreshes the cached hash (§13) alongside the
9668            // commitment + received_at so they never drift.
9669            r.set_commitment(c.clone(), now);
9670            r.last_sig_verify_at = now;
9671            r.commitment_capable = true; // sticky-redundant but explicit
9672        })
9673        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9674    drop(map);
9675    // Record the sticky "ever v12-capable" bit in a set independent of
9676    // `last_commitment_by_peer` (whose entries can be evicted by
9677    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9678    // shield and the §6 holder-eligibility closure consult to decide
9679    // whether the peer is expected to speak v12.
9680    //
9681    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9682    // identity-rotation attacks: once full, new entries are refused.
9683    // Refusal degrades over-cap peers to the behaviour before this set
9684    // existed (treated as legacy on rejoin), which is not a security
9685    // regression and preserves the historic set stable.
9686    {
9687        let mut set = ever_capable_peers.write().await;
9688        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9689            set.insert(*source);
9690        } else {
9691            warn!(
9692                "ingest_peer_commitment: ever_capable_peers at cap \
9693                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9694            );
9695        }
9696    }
9697    // Return an audit target for EVERY valid stored commitment (changed or
9698    // not), so the caller's cooldown+probability-gated trigger keeps a
9699    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9700    // failure (new_hash == None, unreachable for a real commitment) yields None.
9701    new_hash.map(|pin_hash| AuditTarget {
9702        pin_hash,
9703        key_count: c.key_count,
9704    })
9705}
9706
9707// ---------------------------------------------------------------------------
9708// Storage-bound audit (v12) — responder commitment rotation
9709// ---------------------------------------------------------------------------
9710
9711/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9712/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9713/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9714async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9715    let bytes = match tokio::fs::read(path).await {
9716        Ok(b) => b,
9717        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9718            debug!(
9719                "Commitment retention: no snapshot at {} (fresh start)",
9720                path.display()
9721            );
9722            return;
9723        }
9724        Err(e) => {
9725            warn!(
9726                "Commitment retention: failed to read {}: {e}",
9727                path.display()
9728            );
9729            return;
9730        }
9731    };
9732    if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9733        state.restore(&persisted);
9734        info!(
9735            "Commitment retention: reloaded {} slot(s) from {}",
9736            state.retained_slot_count(),
9737            path.display()
9738        );
9739    } else {
9740        warn!(
9741            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9742            path.display()
9743        );
9744    }
9745}
9746
9747/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9748/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9749/// needless disk writes on idle nodes. On success updates `last` to the bytes
9750/// written; on a serialization/write error the existing on-disk snapshot is left
9751/// intact (never truncated).
9752async fn persist_retention_if_changed(
9753    state: &ResponderCommitmentState,
9754    path: &Path,
9755    last: &mut Option<Vec<u8>>,
9756) {
9757    let Some(bytes) = state.snapshot().to_bytes() else {
9758        warn!("Commitment retention: serialization failed; keeping previous snapshot");
9759        return;
9760    };
9761    if last.as_deref() == Some(bytes.as_slice()) {
9762        return;
9763    }
9764    if write_retention_atomic(path, bytes.clone()).await {
9765        *last = Some(bytes);
9766    }
9767}
9768
9769/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9770/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9771/// success. Only the retention-persist loop writes this path, so a fixed temp
9772/// name is safe.
9773async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9774    let path = path.to_path_buf();
9775    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9776        let tmp = path.with_extension("tmp");
9777        std::fs::write(&tmp, &bytes)?;
9778        std::fs::File::open(&tmp)?.sync_all()?;
9779        std::fs::rename(&tmp, &path)?;
9780        // Fsync the directory so the rename (the durable-commit point) is not
9781        // lost on a crash right after it. An empty parent (relative filename)
9782        // means the current directory.
9783        let dir = path
9784            .parent()
9785            .filter(|p| !p.as_os_str().is_empty())
9786            .unwrap_or_else(|| Path::new("."));
9787        std::fs::File::open(dir)?.sync_all()?;
9788        Ok(())
9789    })
9790    .await;
9791    match res {
9792        Ok(Ok(())) => true,
9793        Ok(Err(e)) => {
9794            warn!("Commitment retention: persist failed: {e}");
9795            false
9796        }
9797        Err(e) => {
9798            warn!("Commitment retention: persist task join failed: {e}");
9799            false
9800        }
9801    }
9802}
9803
9804/// Read the current LMDB key set, build + sign a fresh
9805/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9806/// The prior `current` is demoted to `previous`; the prior `previous` is
9807/// dropped (per `ResponderCommitmentState::rotate`).
9808///
9809/// For content-addressed chunks (Autonomi's chunk store), `address ==
9810/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9811/// re-read each chunk's bytes to compute the leaf hash.
9812///
9813/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9814/// rotate. The auditor side handles "no commitment for this peer" by
9815/// falling back to the legacy plain-digest audit path.
9816async fn rebuild_and_rotate_commitment(
9817    storage: &Arc<LmdbStorage>,
9818    identity: &Arc<NodeIdentity>,
9819    state: &Arc<ResponderCommitmentState>,
9820    p2p: &Arc<P2PNode>,
9821    config: &Arc<ReplicationConfig>,
9822) -> Result<()> {
9823    let stored_keys = storage
9824        .all_keys()
9825        .await
9826        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9827
9828    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9829    // everything currently on disk ("hold"). This is the half of the retention
9830    // contract that lets out-of-range chunks age out: a key that has left our
9831    // close group is excluded from the NEXT commitment, so once its last gossip
9832    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9833    // set, `ResponderCommitmentState::is_held` goes false,
9834    // and the pruner (which until then vetoes its deletion) reclaims it. Without
9835    // this filter the pruner's reprieve would keep re-committing stale keys
9836    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9837    // re-committed and re-gossiped every rotation — a permanent pin).
9838    let storage_empty = stored_keys.is_empty();
9839    let self_id = *p2p.peer_id();
9840    let mut keys = Vec::with_capacity(stored_keys.len());
9841    for k in stored_keys {
9842        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9843            keys.push(k);
9844        }
9845    }
9846
9847    if keys.is_empty() {
9848        if storage_empty {
9849            // Storage is genuinely empty — there is nothing to answer for, so
9850            // drop the previously advertised commitment immediately. Keeping it
9851            // would leave remote auditors pinning a hash we can never satisfy
9852            // again (the bytes are gone).
9853            if state.retained_slot_count() > 0 {
9854                debug!("Commitment rotation: storage empty, clearing retained slots");
9855                state.clear_all();
9856            }
9857            return Ok(());
9858        }
9859        // Bytes are still on disk but no key is currently in range. We must NOT
9860        // clear retention here: a peer may still be pinning a root we gossiped
9861        // moments ago and could demand its bytes in a round-2 challenge, which
9862        // we can still answer (the bytes are present). But we must STOP
9863        // advertising the stale commitment: retire it so `current()` returns
9864        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
9865        // The retired slot then ages out by its gossip-answerability TTL while
9866        // remaining answerable for in-flight pins until then. Once it ages out,
9867        // `is_held` flips false and the pruner reclaims the now-uncommitted,
9868        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
9869        // pointing at the stale root, which the gossip loop would keep
9870        // re-stamping — pinning its keys forever.)
9871        debug!(
9872            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
9873             (stays answerable until its gossip TTL lapses, bytes still on disk)"
9874        );
9875        state.retire_current();
9876        return Ok(());
9877    }
9878
9879    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
9880    // to more than the protocol limit; auditor would reject the
9881    // commitment otherwise).
9882    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
9883    if keys.len() > cap {
9884        warn!(
9885            "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
9886             truncating — investigate as this likely means a misconfiguration",
9887            keys.len(),
9888            cap
9889        );
9890    }
9891
9892    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
9893    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
9894    // full chunk re-read per rotation.
9895    //
9896    // Consequence to be precise about: because the leaf is `(key, key)`,
9897    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
9898    // commitment therefore binds "which keys I claim to hold"; it does NOT
9899    // by itself prove byte possession. Byte possession is enforced by the
9900    // round-2 slice audit: a Bao verified slice decoded against the chunk
9901    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
9902    // nonce, so a responder that holds the key list but dropped the bytes
9903    // cannot answer. This is sound ONLY while keys are content addresses;
9904    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
9905    // (`evaluate_subtree_structure`), so a non-content-addressed
9906    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
9907    // earn credit for `key`. If this module is ever reused for
9908    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
9909    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
9910    let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
9911
9912    // No-op-rotation guard: compute just the Merkle root from `entries`
9913    // and compare against the currently-advertised commitment's root.
9914    // If they match, the key set is unchanged and a new rotation would
9915    // only swap a randomized ML-DSA signature for a fresh one — same
9916    // content, different commitment_hash. That invalidates every
9917    // outstanding `recent_provers` credit on this node across the
9918    // close group with no security benefit, breaking steady-state
9919    // quorum liveness on large nodes that can't re-audit every key
9920    // every rotation interval. Skip the rotation entirely when the
9921    // tree is unchanged.
9922    // Build the tree ONCE here (moving `entries`): it serves both the no-op
9923    // root check below and, if we proceed, the signed commitment via
9924    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
9925    // inside `BuiltCommitment::build`).
9926    let candidate_tree = commitment::MerkleTree::build(entries)
9927        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
9928    let candidate_root = candidate_tree.root();
9929    if let Some(current) = state.current() {
9930        if current.commitment().root == candidate_root {
9931            debug!(
9932                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
9933                hex::encode(candidate_root)
9934            );
9935            // Even though we skip re-signing (to avoid invalidating holder
9936            // credit), retention must still advance on the wall clock: a
9937            // previously-gossiped commitment that holds a now-out-of-range key
9938            // must be able to age out of the answerability window even when the
9939            // committed key set is frozen here for many rotations. Without this,
9940            // the no-op guard would pin a stale slot — and its key — forever.
9941            state.age_out();
9942            return Ok(());
9943        }
9944    }
9945
9946    let sk_bytes = identity.secret_key_bytes().to_vec();
9947    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
9948        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
9949    let pk_bytes = identity.public_key().as_bytes().to_vec();
9950    let peer_id_bytes = *p2p.peer_id().as_bytes();
9951
9952    let built = commitment_state::BuiltCommitment::build_from_tree(
9953        candidate_tree,
9954        &peer_id_bytes,
9955        &sk,
9956        &pk_bytes,
9957    )
9958    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
9959
9960    let hash = hex::encode(built.hash());
9961    let key_count = built.commitment().key_count;
9962    state.rotate(built);
9963    info!("Storage commitment rotated: hash={hash} key_count={key_count}");
9964    Ok(())
9965}
9966
9967#[cfg(test)]
9968#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
9969mod tests {
9970    use super::*;
9971    use super::{
9972        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
9973        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
9974        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
9975        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
9976        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
9977        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
9978        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
9979        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
9980    };
9981    use crate::payment::VerificationContext;
9982    use crate::replication::audit::AuditTickResult;
9983    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
9984    use crate::replication::recent_provers::RecentProvers;
9985    use crate::replication::types::{AuditFailureReason, FailureEvidence};
9986    use lru::LruCache;
9987    use saorsa_core::identity::PeerId;
9988    use std::collections::HashMap;
9989    use std::num::NonZeroUsize;
9990    use std::sync::atomic::Ordering;
9991    use std::sync::Arc;
9992    use std::time::Duration;
9993    use std::time::Instant;
9994    use std::time::SystemTime;
9995
9996    #[test]
9997    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
9998        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
9999            assert_eq!(match_replication_protocol(id), Some((id, false)));
10000            assert_eq!(
10001                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10002                Some((id, true))
10003            );
10004        }
10005        assert_eq!(
10006            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10007            None
10008        );
10009        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10010        assert_eq!(match_replication_protocol(RR_PREFIX), None);
10011    }
10012
10013    #[test]
10014    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10015        use crate::replication::protocol::{
10016            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10017            SubtreeSliceChallenge,
10018        };
10019
10020        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10021            challenge_id: 1,
10022            nonce: [0u8; 32],
10023            challenged_peer_id: [0u8; 32],
10024            expected_commitment_hash: [0u8; 32],
10025            openings: vec![],
10026        });
10027        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10028            challenge_id: 1,
10029            nonce: [0u8; 32],
10030            challenged_peer_id: [0u8; 32],
10031            keys: vec![[0u8; 32]],
10032        });
10033        let digest_response =
10034            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10035        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10036            key: [0u8; 32],
10037            data: vec![],
10038            proof_of_payment: vec![],
10039        });
10040
10041        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10042        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10043
10044        for body in [&digest_challenge, &digest_response, &core] {
10045            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10046            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10047        }
10048
10049        for body in [&subtree, &digest_challenge, &digest_response, &core] {
10050            assert!(body_matches_protocol(body, response_protocol_for(body)));
10051        }
10052    }
10053
10054    fn test_peer(b: u8) -> PeerId {
10055        let mut bytes = [0u8; 32];
10056        bytes[0] = b;
10057        PeerId::from_bytes(bytes)
10058    }
10059
10060    /// A structurally valid offer for `data`: real content address, a proof of
10061    /// the minimum accepted size, distinguished by `proof_marker` so a test can
10062    /// tell whose proof came back out of the queue.
10063    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10064        protocol::FreshReplicationOffer {
10065            key: crate::client::compute_address(&data),
10066            data,
10067            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10068        }
10069    }
10070
10071    fn admit_test_offer(
10072        in_flight: &FreshOfferInFlight,
10073        offer: protocol::FreshReplicationOffer,
10074        source: PeerId,
10075    ) -> FreshOfferAdmission {
10076        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10077    }
10078
10079    #[test]
10080    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10081        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10082        let data = vec![0x11u8; 64];
10083
10084        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10085        let FreshOfferAdmission::Opened(entry) = opened else {
10086            panic!("first offer for a key should open the entry")
10087        };
10088
10089        // A second sender contributes its proof instead of being turned away:
10090        // its bytes are provably the same, so only the proof is worth keeping.
10091        assert!(
10092            matches!(
10093                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10094                FreshOfferAdmission::Joined
10095            ),
10096            "a duplicate from a new source should queue its proof"
10097        );
10098        // The same peer twice is not extra evidence, just extra work.
10099        assert!(
10100            matches!(
10101                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10102                FreshOfferAdmission::DuplicateSource
10103            ),
10104            "one source should hold at most one queued proof per key"
10105        );
10106
10107        // An entry that outlived its handler would bar the key forever.
10108        drop(entry);
10109        assert!(
10110            matches!(
10111                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10112                FreshOfferAdmission::Opened(_)
10113            ),
10114            "a released key should be openable again"
10115        );
10116    }
10117
10118    #[test]
10119    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10120        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10121
10122        // A node only receives offers for keys close to its own ID, so accepted
10123        // keys share a long prefix. Any prefix-derived shard index would have
10124        // funnelled these two onto one lock and serialized them.
10125        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10126        assert!(
10127            matches!(
10128                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10129                FreshOfferAdmission::Opened(_)
10130            ),
10131            "distinct keys should never block each other"
10132        );
10133    }
10134
10135    /// The regression that motivated queueing proofs at all.
10136    ///
10137    /// A sender whose proof does not verify must cost the network its own
10138    /// attempt and nothing more. Refusing every later offer outright made the
10139    /// first arrival the only arrival, so one bad proof lost the record — and
10140    /// the delayed possession check then charged that absence to this node.
10141    #[test]
10142    fn a_failing_proof_hands_the_key_to_the_next_sender() {
10143        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10144        let data = vec![0x5Au8; 128];
10145        let forger = test_peer(0xF0);
10146        let genuine = test_peer(0x0F);
10147
10148        let FreshOfferAdmission::Opened(mut entry) =
10149            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10150        else {
10151            panic!("the first offer should open the entry");
10152        };
10153        assert!(
10154            matches!(
10155                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10156                FreshOfferAdmission::Joined
10157            ),
10158            "the genuine sender must not be turned away by the forger"
10159        );
10160
10161        let first = entry
10162            .next_attempt()
10163            .expect("the opener's proof comes first");
10164        assert_eq!(first.source, forger);
10165
10166        // Treat the forger's proof as failed: the next one is still reachable,
10167        // and it is tried against the bytes already held rather than a refetch.
10168        let second = entry
10169            .next_attempt()
10170            .expect("a failed proof must not consume the key");
10171        assert_eq!(second.source, genuine);
10172        assert_eq!(
10173            second.proof_of_payment,
10174            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10175        );
10176        assert_eq!(
10177            entry.data(),
10178            data.as_slice(),
10179            "every proof is tried against the one copy of the bytes"
10180        );
10181
10182        // Draining the queue releases the key rather than stranding it.
10183        assert!(entry.next_attempt().is_none());
10184        assert!(
10185            matches!(
10186                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10187                FreshOfferAdmission::Opened(_)
10188            ),
10189            "an exhausted entry should release its key"
10190        );
10191    }
10192
10193    /// The cap has to be a lifetime budget, not a queue depth.
10194    ///
10195    /// The handler pops a proof before verifying it, so gating admission on the
10196    /// *instantaneous* queue length lets a fresh source refill the slot that pop
10197    /// just freed. Each refill is another on-chain payment verification, run
10198    /// sequentially while the entry holds its admission permit and a worker
10199    /// slot, so a stream of distinct sources could keep one key's handler — and
10200    /// one of only four workers — busy indefinitely.
10201    #[test]
10202    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10203        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10204        let data = vec![0x3Du8; 32];
10205
10206        let FreshOfferAdmission::Opened(mut entry) =
10207            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10208        else {
10209            panic!("the first offer should open the entry")
10210        };
10211
10212        // Drive pop-then-admit with a fresh source every time, exactly as a
10213        // sybil stream would. The budget must be spent by admissions, not
10214        // returned by pops.
10215        let mut admitted = 1;
10216        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10217            let _ = entry.next_attempt();
10218            if matches!(
10219                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10220                FreshOfferAdmission::Joined
10221            ) {
10222                admitted += 1;
10223            }
10224        }
10225
10226        assert!(
10227            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10228            "a key accepted {admitted} proofs over its lifetime, but the budget is \
10229             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10230        );
10231    }
10232
10233    #[test]
10234    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10235        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10236        let data = vec![0x2Cu8; 32];
10237
10238        // The opener occupies the first slot, so the cap is reached after
10239        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10240        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10241        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10242            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10243            assert!(
10244                matches!(
10245                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10246                    FreshOfferAdmission::Joined
10247                ),
10248                "sender {i} is within the legitimate close-group fan-out"
10249            );
10250        }
10251
10252        let surplus = test_peer(0xEE);
10253        assert!(
10254            matches!(
10255                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10256                FreshOfferAdmission::Full
10257            ),
10258            "past the cap a proof is surplus: enough are already queued to place the record"
10259        );
10260    }
10261
10262    #[test]
10263    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10264        assert!(!verification_request_exceeds_limit(
10265            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10266        ));
10267        assert!(verification_request_exceeds_limit(
10268            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10269        ));
10270    }
10271
10272    // The heavy round-1 limiter enforces the per-peer rate cooldown
10273    // and single-use round-1 → round-2 sessions.
10274    #[tokio::test]
10275    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10276        let limiter = SubtreeRound1Limiter::new(
10277            Duration::from_secs(3600),
10278            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10279        );
10280        let peer = test_peer(1);
10281
10282        // First round-1 is admitted; drop the guard so concurrency is free again.
10283        let guard = limiter.admit(&peer).await;
10284        assert!(guard.is_some(), "first round-1 admitted");
10285        drop(guard);
10286        // A second round-1 within the cooldown is dropped even though the heavy
10287        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10288        assert!(
10289            limiter.admit(&peer).await.is_none(),
10290            "second round-1 within cooldown is rate-dropped"
10291        );
10292        // A different peer has its own cooldown.
10293        assert!(limiter.admit(&test_peer(2)).await.is_some());
10294
10295        // Session: opened by round 1, consumed exactly once by the matching round 2.
10296        let hash = [7u8; 32];
10297        let nonce = [9u8; 32];
10298        limiter.open_session(peer, 42, hash, nonce).await;
10299        // Wrong nonce / commitment does not match.
10300        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10301        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10302        // A round 2 with no prior round 1 (wrong challenge_id) misses.
10303        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10304        // The matching round 2 consumes it — and only once (single-use).
10305        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10306        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10307    }
10308
10309    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10310    // so a party holding several identities refills its allowance by rotating
10311    // between them and can keep the heavy pool busy indefinitely. The work
10312    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10313    // so a fresh identity is refused exactly like a repeat caller once it is
10314    // spent. That is the difference between bounding concurrency and bounding
10315    // sustained work.
10316    #[tokio::test]
10317    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10318        // Cooldown disabled so only the work budget can refuse anything.
10319        let limiter =
10320            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10321        assert!(
10322            limiter.admit(&test_peer(1)).await.is_some(),
10323            "a node starts with budget in hand so it can serve audits at once"
10324        );
10325
10326        // Serve enough proof work to run the balance into debt. Charging exactly
10327        // the burst would leave it at zero, which the next nanosecond of refill
10328        // lifts back above the line — the debt is the point.
10329        limiter
10330            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10331            .await;
10332
10333        for id in 2..8u8 {
10334            assert!(
10335                limiter.admit(&test_peer(id)).await.is_none(),
10336                "a never-seen peer must still be refused while the budget is spent"
10337            );
10338        }
10339    }
10340
10341    // The budget is a rate, not a quota: it comes back on its own, so an honest
10342    // auditor blocked by a flood is only delayed. Carrying the debt is what
10343    // prices an expensive proof above a cheap one — without it, a proof reading
10344    // a maximal subtree would cost no more of the next caller's wait than a
10345    // one-leaf proof.
10346    #[test]
10347    fn round1_work_budget_carries_debt_and_refills_over_time() {
10348        let now = Instant::now();
10349        let at = |secs: u64| {
10350            now.checked_add(Duration::from_secs(secs))
10351                .unwrap_or_else(Instant::now)
10352        };
10353        let mut budget = Round1WorkBudget {
10354            balance: 0,
10355            last_refill: now,
10356        };
10357        assert!(!budget.has_budget(now), "empty means empty");
10358
10359        // A proof costing four seconds' worth of refill leaves four seconds of
10360        // debt, so the wait scales with what was actually served.
10361        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10362        assert!(
10363            !budget.has_budget(at(3)),
10364            "still in debt three seconds after an over-large proof"
10365        );
10366        assert!(
10367            budget.has_budget(at(5)),
10368            "the debt is worked off at the refill rate"
10369        );
10370
10371        // Idle time does not bank unbounded credit for a later flood.
10372        budget.refill(at(24 * 60 * 60));
10373        assert_eq!(
10374            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10375            "refill is capped at the burst size"
10376        );
10377    }
10378
10379    // The heavy round-1 pool size is the tightest bound the responder applies and
10380    // the one least backed by fleet measurement, so it is read from config rather
10381    // than baked into the binary: a fleet that lands on the wrong number retunes
10382    // instead of waiting for a release. These pin that the configured value is
10383    // what actually gates admission, and that a 0 degrades to slow, not to off —
10384    // a wedged-shut responder would read on every auditor as a graced timeout,
10385    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10386    #[tokio::test]
10387    async fn round1_pool_size_comes_from_config() {
10388        // Cooldown disabled so only concurrency can refuse anything.
10389        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10390        let held = limiter.admit(&test_peer(1)).await;
10391        assert!(held.is_some(), "the single configured slot is admitted");
10392        assert!(
10393            limiter.admit(&test_peer(2)).await.is_none(),
10394            "a second concurrent round 1 is refused at a configured pool of 1, \
10395             proving admission follows config rather than the compiled-in default"
10396        );
10397        drop(held);
10398        assert!(
10399            limiter.admit(&test_peer(2)).await.is_some(),
10400            "the slot is reusable once the first proof completes"
10401        );
10402    }
10403
10404    #[tokio::test]
10405    async fn round1_pool_size_of_zero_is_clamped_to_one() {
10406        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10407        assert!(
10408            limiter.admit(&test_peer(1)).await.is_some(),
10409            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10410        );
10411    }
10412
10413    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10414        let mut k = [0u8; 32];
10415        k[0] = b;
10416        k
10417    }
10418
10419    #[test]
10420    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10421        let source = test_peer(0x91);
10422        let corroborator = test_peer(0x92);
10423        let mut evidence = types::KeyVerificationEvidence {
10424            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10425            paid_list: HashMap::new(),
10426        };
10427        let failed = KeyVerificationOutcome::QuorumFailed;
10428
10429        assert_eq!(
10430            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10431            Some(source)
10432        );
10433        assert_eq!(
10434            punishable_singleton_replica_hint_source(
10435                &HashSet::from([source, corroborator]),
10436                &failed,
10437                &evidence,
10438            ),
10439            None,
10440            "corroborated hints must not use the sole-source penalty lane"
10441        );
10442        assert_eq!(
10443            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10444            None,
10445            "paid-list advertisements do not claim possession, so they leave the \
10446             replica-hint source set empty and cannot be penalized"
10447        );
10448
10449        evidence
10450            .presence
10451            .insert(source, PresenceEvidence::Unresolved);
10452        assert_eq!(
10453            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10454            Some(source),
10455            "definitive close-group rejection is punishable without direct contradiction"
10456        );
10457        assert_eq!(
10458            punishable_singleton_replica_hint_source(
10459                &HashSet::from([source]),
10460                &KeyVerificationOutcome::QuorumInconclusive,
10461                &evidence,
10462            ),
10463            None,
10464            "timeouts and inconclusive evidence are neutral"
10465        );
10466
10467        evidence.presence.insert(source, PresenceEvidence::Absent);
10468        assert_eq!(
10469            punishable_singleton_replica_hint_source(
10470                &HashSet::from([source]),
10471                &KeyVerificationOutcome::QuorumVerified {
10472                    sources: vec![corroborator],
10473                },
10474                &evidence,
10475            ),
10476            Some(source),
10477            "an explicit denial is punishable regardless of the overall outcome"
10478        );
10479    }
10480
10481    /// Build a round-2 slice challenge matching an open session. `openings` is
10482    /// empty: these tests exercise admission and session handling only, which
10483    /// run before any block is opened.
10484    fn slice_challenge(
10485        challenge_id: u64,
10486        commitment_hash: [u8; 32],
10487        nonce: [u8; 32],
10488    ) -> protocol::SubtreeSliceChallenge {
10489        protocol::SubtreeSliceChallenge {
10490            challenge_id,
10491            nonce,
10492            challenged_peer_id: [0u8; 32],
10493            expected_commitment_hash: commitment_hash,
10494            openings: Vec::new(),
10495        }
10496    }
10497
10498    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10499    // responder caps MUST NOT burn the single-use round-1 session.
10500    //
10501    // The handler used to consume the session first and admit second, so a
10502    // transient local capacity drop permanently destroyed that audit exchange —
10503    // every retry hit the `no live round-1 session` path and got `Transient`,
10504    // even after load cleared. Turning momentary local load into a deterministic
10505    // round-2 miss costs the responder its whole-slice credit for that round.
10506    #[tokio::test]
10507    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10508        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10509        let inflight = Arc::new(RwLock::new(HashMap::new()));
10510        let round1 =
10511            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10512        let peer = test_peer(0xB1);
10513        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10514        let challenge = slice_challenge(id, hash, nonce);
10515
10516        round1.open_session(peer, id, hash, nonce).await;
10517
10518        // Saturate this peer's share so the next admission must be refused.
10519        let mut hold = Vec::new();
10520        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10521            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10522                .await
10523            {
10524                Ok(guard) => hold.push(guard),
10525                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10526            }
10527        }
10528
10529        let refused =
10530            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10531        assert!(
10532            matches!(refused, SliceAdmission::Capacity(_)),
10533            "a saturated peer share must refuse on capacity, not on session"
10534        );
10535
10536        // Load clears. The session must have survived the refusal.
10537        drop(hold);
10538        let retried =
10539            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10540        assert!(
10541            matches!(retried, SliceAdmission::Admitted(_)),
10542            "the round-1 session must survive a capacity refusal so the retry succeeds"
10543        );
10544
10545        // Still single-use: the successful admission consumed it exactly once.
10546        drop(retried);
10547        let replayed =
10548            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10549        assert!(
10550            matches!(replayed, SliceAdmission::NoSession),
10551            "a consumed session must not be replayable"
10552        );
10553    }
10554
10555    // The permit taken for the session probe is released when the probe misses,
10556    // so an unsessioned flood cannot pin the responder pool shut.
10557    #[tokio::test]
10558    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10559        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10560        let inflight = Arc::new(RwLock::new(HashMap::new()));
10561        let round1 =
10562            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10563        let peer = test_peer(0xB2);
10564        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10565
10566        // Far more unsessioned challenges than the per-peer cap would allow if
10567        // the slot leaked on the miss path.
10568        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10569            let outcome =
10570                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10571            assert!(
10572                matches!(outcome, SliceAdmission::NoSession),
10573                "no session was ever opened, so every attempt must miss"
10574            );
10575        }
10576
10577        assert_eq!(
10578            semaphore.available_permits(),
10579            MAX_CONCURRENT_AUDIT_RESPONSES,
10580            "every global permit must be returned"
10581        );
10582        assert!(
10583            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10584            "no per-peer slot may be left occupied"
10585        );
10586    }
10587
10588    #[test]
10589    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10590        assert!(!audit_failure_revokes_holder_credit(
10591            &AuditFailureReason::Timeout
10592        ));
10593        assert!(audit_failure_revokes_holder_credit(
10594            &AuditFailureReason::DigestMismatch
10595        ));
10596    }
10597
10598    #[tokio::test]
10599    async fn audit_responder_admission_reports_per_peer_cap_full() {
10600        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10601        let inflight = Arc::new(RwLock::new(HashMap::new()));
10602        let peer = test_peer(0xA1);
10603
10604        let mut guards = Vec::new();
10605        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10606            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10607                .await
10608            {
10609                Ok(guard) => guards.push(guard),
10610                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10611            }
10612        }
10613
10614        let Err(err) =
10615            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10616        else {
10617            panic!("admission should fail once per-peer cap is full");
10618        };
10619        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10620        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10621        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10622        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10623
10624        drop(guards);
10625    }
10626
10627    #[tokio::test]
10628    async fn audit_responder_admission_reports_global_pool_full() {
10629        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10630        let inflight = Arc::new(RwLock::new(HashMap::new()));
10631        let peer = test_peer(0xA2);
10632
10633        let mut held_global_permits = Vec::new();
10634        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10635            held_global_permits.push(
10636                Arc::clone(&semaphore)
10637                    .try_acquire_owned()
10638                    .expect("test should be able to exhaust the global pool"),
10639            );
10640        }
10641
10642        let Err(err) =
10643            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10644        else {
10645            panic!("admission should fail once global pool is full");
10646        };
10647        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10648        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10649        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10650        assert_eq!(err.peer_inflight, 0);
10651        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10652
10653        drop(held_global_permits);
10654    }
10655
10656    #[tokio::test]
10657    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10658        let semaphore = Arc::new(Semaphore::new(1));
10659        let inflight = Arc::new(RwLock::new(HashMap::new()));
10660        let peer = test_peer(0xA3);
10661
10662        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10663            .await
10664            .expect("first responder should be admitted");
10665        assert_eq!(semaphore.available_permits(), 0);
10666        assert_eq!(inflight.read().await.get(&peer), Some(&1));
10667
10668        drop(guard);
10669        assert_eq!(semaphore.available_permits(), 1);
10670        assert!(!inflight.read().await.contains_key(&peer));
10671    }
10672
10673    #[tokio::test]
10674    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10675        let semaphore = Arc::new(Semaphore::new(1));
10676        let inflight = Arc::new(RwLock::new(HashMap::new()));
10677        let peer = test_peer(0xA4);
10678        let held_map = inflight.write().await;
10679
10680        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10681        assert!(
10682            tokio::time::timeout(Duration::from_millis(10), waiting)
10683                .await
10684                .is_err(),
10685            "admission should still be waiting for the peer map"
10686        );
10687
10688        drop(held_map);
10689        assert_eq!(semaphore.available_permits(), 1);
10690        assert!(!inflight.read().await.contains_key(&peer));
10691    }
10692
10693    #[test]
10694    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10695        let timeout = Duration::from_secs(1);
10696        let old_received_at = Instant::now()
10697            .checked_sub(timeout)
10698            .unwrap_or_else(Instant::now);
10699
10700        assert!(request_is_stale(old_received_at, timeout));
10701        assert!(!request_is_stale(Instant::now(), timeout));
10702    }
10703
10704    #[tokio::test]
10705    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10706        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10707        let inflight = Arc::new(RwLock::new(HashMap::new()));
10708        let first_peer = test_peer(0xB3);
10709        let second_peer = test_peer(0xB4);
10710
10711        let first_guard = admit_bounded_responder(
10712            &semaphore,
10713            &inflight,
10714            &first_peer,
10715            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10716            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10717        )
10718        .await
10719        .expect("first sync from a peer should be admitted");
10720        let duplicate = admit_bounded_responder(
10721            &semaphore,
10722            &inflight,
10723            &first_peer,
10724            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10725            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10726        )
10727        .await;
10728        let other_peer = admit_bounded_responder(
10729            &semaphore,
10730            &inflight,
10731            &second_peer,
10732            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10733            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10734        )
10735        .await;
10736
10737        assert!(matches!(
10738            duplicate,
10739            Err(ResponderAdmissionFailure {
10740                reason: ResponderRejectReason::PerPeerCapFull,
10741                ..
10742            })
10743        ));
10744        assert!(other_peer.is_ok());
10745        drop(first_guard);
10746        drop(other_peer);
10747    }
10748
10749    /// One flooding peer must not be able to hold every fresh-offer slot.
10750    ///
10751    /// This is the eviction primitive the per-peer share closes: with only a
10752    /// global bound, a single source occupies the pool, every honest offer in
10753    /// that window is refused, and because a refusal reads as absence to the
10754    /// sender's delayed possession check those refusals land as
10755    /// audit-severity penalties on *this* node.
10756    #[tokio::test]
10757    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10758        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10759        let inflight = Arc::new(RwLock::new(HashMap::new()));
10760        let flooder = test_peer(0xC1);
10761        let honest = test_peer(0xC2);
10762
10763        let mut held = Vec::new();
10764        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
10765            held.push(
10766                admit_bounded_responder(
10767                    &semaphore,
10768                    &inflight,
10769                    &flooder,
10770                    FRESH_OFFER_MAX_OUTSTANDING,
10771                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10772                )
10773                .await
10774                .expect("offers within the per-peer share are admitted"),
10775            );
10776        }
10777
10778        let flooder_excess = admit_bounded_responder(
10779            &semaphore,
10780            &inflight,
10781            &flooder,
10782            FRESH_OFFER_MAX_OUTSTANDING,
10783            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10784        )
10785        .await;
10786        assert!(
10787            matches!(
10788                flooder_excess,
10789                Err(ResponderAdmissionFailure {
10790                    reason: ResponderRejectReason::PerPeerCapFull,
10791                    ..
10792                })
10793            ),
10794            "one source must not exceed its fresh-offer share"
10795        );
10796
10797        let honest_offer = admit_bounded_responder(
10798            &semaphore,
10799            &inflight,
10800            &honest,
10801            FRESH_OFFER_MAX_OUTSTANDING,
10802            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
10803        )
10804        .await;
10805        assert!(
10806            honest_offer.is_ok(),
10807            "an honest sender must still be admitted while another peer floods"
10808        );
10809
10810        assert!(
10811            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
10812                < FRESH_OFFER_MAX_OUTSTANDING,
10813            "the per-peer share must leave room for other sources"
10814        );
10815
10816        drop(held);
10817        drop(honest_offer);
10818    }
10819
10820    /// Paid notifies get the same per-source treatment as every other class.
10821    #[tokio::test]
10822    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
10823        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
10824        let inflight = Arc::new(RwLock::new(HashMap::new()));
10825        let flooder = test_peer(0xC3);
10826        let honest = test_peer(0xC4);
10827
10828        let mut held = Vec::new();
10829        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
10830            held.push(
10831                admit_bounded_responder(
10832                    &semaphore,
10833                    &inflight,
10834                    &flooder,
10835                    PAID_NOTIFY_MAX_OUTSTANDING,
10836                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10837                )
10838                .await
10839                .expect("notifies within the per-peer share are admitted"),
10840            );
10841        }
10842
10843        assert!(
10844            matches!(
10845                admit_bounded_responder(
10846                    &semaphore,
10847                    &inflight,
10848                    &flooder,
10849                    PAID_NOTIFY_MAX_OUTSTANDING,
10850                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10851                )
10852                .await,
10853                Err(ResponderAdmissionFailure {
10854                    reason: ResponderRejectReason::PerPeerCapFull,
10855                    ..
10856                })
10857            ),
10858            "one source must not exceed its paid-notify share"
10859        );
10860        assert!(
10861            admit_bounded_responder(
10862                &semaphore,
10863                &inflight,
10864                &honest,
10865                PAID_NOTIFY_MAX_OUTSTANDING,
10866                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
10867            )
10868            .await
10869            .is_ok(),
10870            "an honest sender must still be admitted while another peer floods"
10871        );
10872
10873        drop(held);
10874    }
10875
10876    /// The fresh-offer per-source bound must guarantee headroom for a peer
10877    /// holding nothing, without throttling a single legitimate fan-out.
10878    ///
10879    /// Sized as a quota rather than a reserve, this bound refused offers during
10880    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
10881    /// refusal is charged to THIS node at audit severity because the sender
10882    /// never reads it.
10883    #[test]
10884    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
10885        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
10886
10887        assert_eq!(
10888            FRESH_OFFER_MAX_OUTSTANDING - share,
10889            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
10890            "a source holding none must always find a free slot"
10891        );
10892        assert!(
10893            share < FRESH_OFFER_MAX_OUTSTANDING,
10894            "one peer must not be able to take the whole pool"
10895        );
10896        // The failure this pins: a share sized like the request/response
10897        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
10898        // one-way bulk traffic.
10899        assert!(
10900            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
10901            "fresh offers are one-way bulk, not request/response — their share \
10902             must not be sized like the request classes'"
10903        );
10904    }
10905
10906    /// A malformed offer must be refused before it can occupy an admission
10907    /// slot, so junk cannot hold capacity for the length of a verification.
10908    #[test]
10909    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
10910        let key = test_key(0xC5);
10911
10912        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10913
10914        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
10915            .expect("an offer with no proof must be refused");
10916        assert!(
10917            rejection.penalise,
10918            "an honest sender always attaches a proof"
10919        );
10920
10921        // A proof is retained per queued sender, so its size has to be bounded
10922        // here rather than at the verifier, which only sees it on a worker.
10923        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
10924        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
10925            .expect("an undersized proof must be refused");
10926        assert!(
10927            rejection.penalise,
10928            "no honest sender constructs an undersized proof"
10929        );
10930        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
10931        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
10932            .expect("an oversized proof must be refused");
10933        assert!(
10934            rejection.penalise,
10935            "no honest sender constructs an oversized proof"
10936        );
10937
10938        let rejection = fresh_offer_structural_rejection(
10939            &key,
10940            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
10941            &valid_proof,
10942        )
10943        .expect("an oversized offer must be refused");
10944        assert!(
10945            rejection.penalise,
10946            "no honest sender constructs an oversized offer"
10947        );
10948
10949        let data = vec![0u8; 1];
10950        assert!(
10951            fresh_offer_structural_rejection(
10952                &crate::client::compute_address(&data),
10953                &data,
10954                &valid_proof
10955            )
10956            .is_none(),
10957            "a well-formed offer must reach admission"
10958        );
10959    }
10960
10961    /// Knowing a key must not be enough to enter its entry.
10962    ///
10963    /// Opening an entry on an unverified key/bytes association would let a peer
10964    /// that has only *learned* the key — every recipient of its `PaidNotify`,
10965    /// not just the close group that gets the chunk — seize it with junk.
10966    /// Joining one would be worse: the handler tries each queued proof against
10967    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
10968    /// on bytes it never offered.
10969    #[test]
10970    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
10971        let genuine_data = vec![0x5Au8; 128];
10972        let key = crate::client::compute_address(&genuine_data);
10973        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
10974
10975        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
10976            .expect("bytes that do not hash to the advertised key must be refused");
10977        assert!(
10978            rejection.penalise,
10979            "no honest sender offers bytes that do not hash to the advertised key"
10980        );
10981
10982        // Dispatch reaches the entry only past that rejection, so the forged
10983        // offer never touched the key and the genuine one still opens it.
10984        assert!(
10985            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
10986            "the offer that actually carries the key's bytes must reach the entry"
10987        );
10988
10989        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10990        assert!(
10991            matches!(
10992                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
10993                FreshOfferAdmission::Opened(_)
10994            ),
10995            "an offer refused on payload shape must leave the key openable"
10996        );
10997    }
10998
10999    #[tokio::test]
11000    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11001        let peer = test_peer(0xA5);
11002        let key = test_key(0xA5);
11003        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11004        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11005        let is_bootstrapping = Arc::new(RwLock::new(true));
11006        let bootstrap_complete_notify = Arc::new(Notify::new());
11007
11008        let now = Instant::now();
11009        queues.write().await.add_pending_verify(
11010            key,
11011            VerificationEntry {
11012                state: VerificationState::PendingVerify,
11013                verified_sources: Vec::new(),
11014                tried_sources: HashSet::new(),
11015                created_at: now,
11016                next_verify_at: now,
11017                hint_sources: HashSet::from([peer]),
11018                replica_hint_sources: HashSet::from([peer]),
11019                unresolved_retries: 0,
11020                no_holder_reported: false,
11021            },
11022        );
11023        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11024        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11025        {
11026            let q = queues.read().await;
11027            assert!(
11028                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11029                "capacity rejection should initially block bootstrap drain"
11030            );
11031        }
11032
11033        update_bootstrap_after_peer_removed(
11034            &peer,
11035            &bootstrap_state,
11036            &queues,
11037            &is_bootstrapping,
11038            &bootstrap_complete_notify,
11039        )
11040        .await;
11041
11042        let state = bootstrap_state.read().await;
11043        assert!(state.capacity_rejected_sources.is_empty());
11044        assert!(state.pending_keys.is_empty());
11045        assert!(state.is_drained());
11046        drop(state);
11047        assert!(!*is_bootstrapping.read().await);
11048    }
11049
11050    /// A fairness displacement forfeits the key but must not stamp its former
11051    /// owner: the owner did nothing wrong, and stamping it lets a flooding
11052    /// source block bootstrap drain through an unrelated honest peer.
11053    #[tokio::test]
11054    async fn fairness_displacement_does_not_stamp_its_victim() {
11055        let displaced_owner = test_peer(0xB1);
11056        let incoming_source = test_peer(0xB2);
11057        let displaced_key = test_key(0xB1);
11058        let admitted_key = test_key(0xB2);
11059        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11060        {
11061            let mut state = bootstrap_state.write().await;
11062            state.pending_keys.insert(displaced_key);
11063            state
11064                .capacity_rejected_sources
11065                .insert(incoming_source, Instant::now());
11066        }
11067        let outcomes = [(
11068            incoming_source,
11069            AdmissionOutcome {
11070                discovered: HashSet::from([admitted_key]),
11071                capacity_rejected_count: 0,
11072                displaced: vec![CapacityDisplacement {
11073                    key: displaced_key,
11074                    owner: displaced_owner,
11075                }],
11076            },
11077        )];
11078
11079        publish_bootstrap_admission_outcomes(
11080            &bootstrap_state,
11081            &outcomes,
11082            &HashSet::from([admitted_key]),
11083        )
11084        .await;
11085
11086        let state = bootstrap_state.read().await;
11087        assert!(!state.pending_keys.contains(&displaced_key));
11088        assert!(state.pending_keys.contains(&admitted_key));
11089        assert!(
11090            !state
11091                .capacity_rejected_sources
11092                .contains_key(&displaced_owner),
11093            "the displaced owner must not be charged for our own fairness reclaim"
11094        );
11095        assert!(!state
11096            .capacity_rejected_sources
11097            .contains_key(&incoming_source));
11098    }
11099
11100    /// A source that keeps overflowing us must not keep its own record fresh.
11101    ///
11102    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11103    /// rejection the debt could never age out, so `check_bootstrap_drained`
11104    /// stayed false forever and auditing never started (Invariant 19).
11105    #[tokio::test]
11106    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11107        const REJECTION_ROUNDS: usize = 5;
11108
11109        let source = test_peer(0xB3);
11110        let key = test_key(0xB3);
11111        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11112
11113        let first_seen = {
11114            let outcomes = [(
11115                source,
11116                AdmissionOutcome {
11117                    discovered: HashSet::new(),
11118                    capacity_rejected_count: 1,
11119                    displaced: Vec::new(),
11120                },
11121            )];
11122            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11123                .await;
11124            bootstrap_state
11125                .read()
11126                .await
11127                .capacity_rejected_sources
11128                .get(&source)
11129                .copied()
11130                .expect("first rejection recorded")
11131        };
11132
11133        for _ in 0..REJECTION_ROUNDS {
11134            let outcomes = [(
11135                source,
11136                AdmissionOutcome {
11137                    discovered: HashSet::from([key]),
11138                    capacity_rejected_count: 1,
11139                    displaced: Vec::new(),
11140                },
11141            )];
11142            publish_bootstrap_admission_outcomes(
11143                &bootstrap_state,
11144                &outcomes,
11145                &HashSet::from([key]),
11146            )
11147            .await;
11148        }
11149
11150        let recorded = bootstrap_state
11151            .read()
11152            .await
11153            .capacity_rejected_sources
11154            .get(&source)
11155            .copied()
11156            .expect("debt still outstanding");
11157        assert_eq!(
11158            recorded, first_seen,
11159            "repeat rejections must not restart the expiry clock"
11160        );
11161    }
11162
11163    /// The verification-worker tick's self-heal path: a capacity rejection
11164    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11165    /// blocks drain until the TTL expires it, at which point the same tick
11166    /// completes bootstrap without any external event.
11167    #[tokio::test]
11168    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11169        let peer = test_peer(0xA6);
11170        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11171        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11172        let is_bootstrapping = Arc::new(RwLock::new(true));
11173        let bootstrap_complete_notify = Arc::new(Notify::new());
11174
11175        // PeerRemoved was fully processed before the rejection landed, so no
11176        // future event will ever clear this entry.
11177        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11178
11179        // Within the TTL the tick keeps waiting for re-delivery.
11180        expire_and_recheck_bootstrap_drain(
11181            &bootstrap_state,
11182            &queues,
11183            &is_bootstrapping,
11184            &bootstrap_complete_notify,
11185            ReplicationConfig::default().capacity_rejected_max_age(),
11186        )
11187        .await;
11188        assert!(!bootstrap_state.read().await.is_drained());
11189        assert!(*is_bootstrapping.read().await);
11190
11191        // Past the TTL the tick expires the orphan and completes bootstrap.
11192        expire_and_recheck_bootstrap_drain(
11193            &bootstrap_state,
11194            &queues,
11195            &is_bootstrapping,
11196            &bootstrap_complete_notify,
11197            Duration::ZERO,
11198        )
11199        .await;
11200        assert!(bootstrap_state.read().await.is_drained());
11201        assert!(!*is_bootstrapping.read().await);
11202    }
11203
11204    #[test]
11205    fn first_audit_terminal_outcomes_are_stable() {
11206        let peer = test_peer(1);
11207        let passed = AuditTickResult::Passed {
11208            challenged_peer: peer,
11209            keys_checked: 1,
11210        };
11211        let timed_out = AuditTickResult::Failed {
11212            evidence: FailureEvidence::AuditFailure {
11213                challenge_id: 1,
11214                challenged_peer: peer,
11215                confirmed_failed_keys: vec![test_key(1)],
11216                summary: crate::replication::types::AuditFailureSummary::default(),
11217                reason: AuditFailureReason::Timeout,
11218            },
11219            no_response_class: Some("timeout"),
11220        };
11221
11222        assert_eq!(
11223            first_audit_terminal_outcome(&passed),
11224            FirstAuditTerminalOutcome::Passed
11225        );
11226        assert_eq!(
11227            first_audit_terminal_outcome(&timed_out),
11228            FirstAuditTerminalOutcome::Timeout
11229        );
11230        assert_eq!(
11231            first_audit_terminal_outcome(&AuditTickResult::Idle),
11232            FirstAuditTerminalOutcome::Idle
11233        );
11234        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11235        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11236        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11237        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11238        assert_eq!(
11239            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11240            "insufficient_keys"
11241        );
11242        assert_eq!(
11243            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11244            "bootstrap_claim"
11245        );
11246    }
11247
11248    #[test]
11249    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11250        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11251        let mut rng = StdRng::seed_from_u64(7);
11252        let peer = test_peer(1);
11253        let base = MonetizedPinEvent {
11254            peer,
11255            pin: [1; 32],
11256            key_count: 100,
11257            quote_ts: SystemTime::now(),
11258        };
11259
11260        // First insert into an empty slot: Queued.
11261        assert_eq!(
11262            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11263            FirstAuditQueueOutcome::Queued
11264        );
11265
11266        // A strictly LOWER-count same-peer nomination must NOT displace it.
11267        let lower = MonetizedPinEvent {
11268            pin: [2; 32],
11269            key_count: 50,
11270            ..base
11271        };
11272        assert_eq!(
11273            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11274            FirstAuditQueueOutcome::SuppressedLower
11275        );
11276        assert_eq!(
11277            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11278            Some(([1; 32], 100)),
11279            "the higher-count pin is retained"
11280        );
11281
11282        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11283        let higher = MonetizedPinEvent {
11284            pin: [3; 32],
11285            key_count: 400,
11286            ..base
11287        };
11288        assert_eq!(
11289            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11290            FirstAuditQueueOutcome::Coalesced
11291        );
11292        assert_eq!(
11293            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11294            Some(([3; 32], 400))
11295        );
11296
11297        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11298        let equal_newer = MonetizedPinEvent {
11299            pin: [4; 32],
11300            key_count: 400,
11301            ..base
11302        };
11303        assert_eq!(
11304            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11305            FirstAuditQueueOutcome::Coalesced
11306        );
11307        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11308        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11309        let equal_older = MonetizedPinEvent {
11310            pin: [5; 32],
11311            key_count: 400,
11312            ..base
11313        };
11314        assert_eq!(
11315            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11316            FirstAuditQueueOutcome::RetainedOnTie
11317        );
11318        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11319
11320        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11321        let other_peer = MonetizedPinEvent {
11322            peer: test_peer(2),
11323            pin: [6; 32],
11324            key_count: 100,
11325            ..base
11326        };
11327        assert_eq!(
11328            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11329            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11330        );
11331        assert_eq!(pending.len(), 1);
11332        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11333    }
11334
11335    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11336
11337    #[test]
11338    fn first_audit_limiter_enforces_burst_then_refills() {
11339        let base = Instant::now();
11340        let mut limiter = FirstAuditLimiter::new(base);
11341        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11342
11343        // The full burst is admitted back-to-back (distinct peers).
11344        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11345            let peer = test_peer(u8::try_from(i).expect("small burst"));
11346            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11347            limiter.commit_launch(peer, 10, base);
11348        }
11349        // Bucket empty: the next distinct peer is deferred, never dropped.
11350        let extra = test_peer(0xEE);
11351        assert_eq!(
11352            limiter.assess(&extra, 10, base, 0),
11353            LimiterVerdict::RateDeferred
11354        );
11355
11356        // One full interval later exactly one token is available again.
11357        let later = base + interval;
11358        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11359        limiter.commit_launch(extra, 10, later);
11360        let extra2 = test_peer(0xEF);
11361        assert_eq!(
11362            limiter.assess(&extra2, 10, later, 0),
11363            LimiterVerdict::RateDeferred
11364        );
11365    }
11366
11367    #[test]
11368    fn first_audit_limiter_refill_keeps_fractional_remainder() {
11369        let base = Instant::now();
11370        let mut limiter = FirstAuditLimiter::new(base);
11371        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11372        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11373            let peer = test_peer(u8::try_from(i).expect("small burst"));
11374            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11375            limiter.commit_launch(peer, 1, base);
11376        }
11377        // 1.5 intervals later one token is earned and the half interval is
11378        // NOT lost to drift...
11379        let at_1_5 = base + interval + interval / 2;
11380        let p = test_peer(0xAA);
11381        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11382        limiter.commit_launch(p, 1, at_1_5);
11383        // ...so the next token arrives at 2.0 intervals, not 2.5.
11384        let at_2_0 = base + interval * 2;
11385        let q = test_peer(0xAB);
11386        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11387    }
11388
11389    #[test]
11390    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11391        let base = Instant::now();
11392        let mut limiter = FirstAuditLimiter::new(base);
11393        let peer = test_peer(1);
11394        assert_eq!(
11395            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11396            LimiterVerdict::RateDeferred
11397        );
11398        // A freed slot admits without any clock movement.
11399        assert_eq!(
11400            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11401            LimiterVerdict::Admit
11402        );
11403    }
11404
11405    #[test]
11406    fn first_audit_limiter_assess_consumes_nothing() {
11407        let base = Instant::now();
11408        let mut limiter = FirstAuditLimiter::new(base);
11409        let peer = test_peer(3);
11410        // Repeated assessment must not burn budget or stamp the window: only
11411        // `commit_launch` consumes (the cooldown gate between assess and
11412        // commit can defer, and that deferral must be free).
11413        for _ in 0..10 {
11414            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11415        }
11416        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11417            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11418            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11419            limiter.commit_launch(p, 5, base);
11420        }
11421    }
11422
11423    #[test]
11424    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11425        let base = Instant::now();
11426        let mut limiter = FirstAuditLimiter::new(base);
11427        let peer = test_peer(7);
11428        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11429        limiter.commit_launch(peer, 100, base);
11430
11431        // A rotated pin with a similar count inside the window is dropped...
11432        let soon = base + Duration::from_secs(60);
11433        assert_eq!(
11434            limiter.assess(&peer, 100, soon, 0),
11435            LimiterVerdict::WindowDeduped
11436        );
11437        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11438        assert_eq!(
11439            limiter.assess(&peer, 150, soon, 0),
11440            LimiterVerdict::WindowDeduped
11441        );
11442        // ...but a >1.5x committed-count jump re-nominates immediately (an
11443        // inflated sidecar-only pin is invisible to the gossip lottery, so
11444        // the window must not shield it).
11445        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11446
11447        // Window expiry re-admits an unchanged count.
11448        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11449        assert_eq!(
11450            limiter.assess(&peer, 100, expired, 0),
11451            LimiterVerdict::Admit
11452        );
11453    }
11454
11455    #[test]
11456    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11457        // A window-deduped nomination must be DROPPED, not kept pending as
11458        // rate-deferred, even when the bucket is also empty: re-queuing a
11459        // suppressed rotation would hold a pending slot for two hours.
11460        let base = Instant::now();
11461        let mut limiter = FirstAuditLimiter::new(base);
11462        let peer = test_peer(9);
11463        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11464        limiter.commit_launch(peer, 10, base);
11465        let other = test_peer(10);
11466        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11467        limiter.commit_launch(other, 10, base);
11468        assert_eq!(
11469            limiter.assess(&peer, 10, base, 0),
11470            LimiterVerdict::WindowDeduped
11471        );
11472    }
11473
11474    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11475    /// is answerable now but would age out of the answerability window during
11476    /// the launch jitter, so scheduling state is only ever committed for a pin
11477    /// that can still be challenged when it actually sends.
11478    #[test]
11479    fn first_audit_horizon_prefilter_boundary() {
11480        let now = SystemTime::now();
11481        // C = the too-old cutoff; H = the worst-case send horizon.
11482        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11483        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11484        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11485        let boundary = now
11486            .checked_add(h)
11487            .and_then(|t| t.checked_sub(c))
11488            .expect("boundary time");
11489
11490        // In window at `now` (age = C - H < C)...
11491        assert!(quote_within_audit_window(boundary, now));
11492        // ...but the horizon prefilter rejects it (age == C at now + H).
11493        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11494
11495        // A hair newer stays answerable through the horizon; a hair older does
11496        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11497        // a nanosecond step would round to the same instant there.
11498        let newer = boundary
11499            .checked_add(Duration::from_micros(1))
11500            .expect("newer");
11501        let older = boundary
11502            .checked_sub(Duration::from_micros(1))
11503            .expect("older");
11504        assert!(quote_answerable_through_nominal_jitter(newer, now));
11505        assert!(!quote_answerable_through_nominal_jitter(older, now));
11506
11507        // A quote too far in the FUTURE is rejected at `now`, independent of the
11508        // horizon.
11509        let future = now
11510            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11511            .and_then(|t| t.checked_add(Duration::from_secs(60)))
11512            .expect("future");
11513        assert!(!quote_answerable_through_nominal_jitter(future, now));
11514    }
11515
11516    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11517    /// answerability check fails at promotion is fully state-neutral — it stamps
11518    /// no `first_audited`, no per-peer window, refunds its token, releases its
11519    /// in-flight slot, does not flip the lane, and does not count a launch — and
11520    /// a same-peer, same-count successor enqueued DURING the reservation is
11521    /// retained and becomes the next reservation after the cancel. This is the
11522    /// exact hole the reviewer flagged: suppression must never outlive a launch
11523    /// that did not send.
11524    /// A pending pin that has aged past the answerability horizon must not
11525    /// suppress a live lower-count nomination for the same peer: under token
11526    /// starvation no reserve scan ever collects the dead entry, so without the
11527    /// enqueue-time check the peer would stay unauditable through this path
11528    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11529    #[test]
11530    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11531        let obs = Arc::new(FirstAuditObservability::default());
11532        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11533        let peer = test_peer(1);
11534
11535        let dead_quote = SystemTime::now()
11536            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11537            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11538            .expect("past wall time");
11539        let stale_high = MonetizedPinEvent {
11540            peer,
11541            pin: [1; 32],
11542            key_count: 400,
11543            quote_ts: dead_quote,
11544        };
11545        scheduler.enqueue(stale_high, &obs);
11546        assert_eq!(scheduler.pending_len(), 1);
11547
11548        // A fresh, lower-count nomination (a post-prune commitment).
11549        let fresh_lower = MonetizedPinEvent {
11550            peer,
11551            pin: [2; 32],
11552            key_count: 100,
11553            quote_ts: SystemTime::now(),
11554        };
11555        scheduler.enqueue(fresh_lower, &obs);
11556
11557        assert_eq!(scheduler.pending_len(), 1);
11558        assert_eq!(
11559            scheduler.pending.peek(&peer).map(|e| e.pin),
11560            Some([2; 32]),
11561            "the live nomination replaced the dead incumbent"
11562        );
11563        assert_eq!(
11564            obs.suppressed_lower.load(Ordering::Relaxed),
11565            0,
11566            "no self-erasure signal for displacing a dead pin"
11567        );
11568        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11569        assert_eq!(
11570            obs.outside_answerability_window.load(Ordering::Relaxed),
11571            1,
11572            "the dead incumbent is accounted as an expiry"
11573        );
11574    }
11575
11576    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11577    /// nomination still loses to an answerable higher-count pending pin.
11578    #[test]
11579    fn first_audit_live_incumbent_still_suppresses_lower_count() {
11580        let obs = Arc::new(FirstAuditObservability::default());
11581        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11582        let peer = test_peer(1);
11583
11584        let live_high = MonetizedPinEvent {
11585            peer,
11586            pin: [1; 32],
11587            key_count: 400,
11588            quote_ts: SystemTime::now(),
11589        };
11590        scheduler.enqueue(live_high, &obs);
11591        let cheaper = MonetizedPinEvent {
11592            peer,
11593            pin: [2; 32],
11594            key_count: 100,
11595            quote_ts: SystemTime::now(),
11596        };
11597        scheduler.enqueue(cheaper, &obs);
11598
11599        assert_eq!(scheduler.pending_len(), 1);
11600        assert_eq!(
11601            scheduler.pending.peek(&peer).map(|e| e.pin),
11602            Some([1; 32]),
11603            "the higher-count live pin is retained"
11604        );
11605        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11606        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11607    }
11608
11609    /// A fresh nomination for peer `b` (distinct pin per peer).
11610    fn live_nomination(b: u8) -> MonetizedPinEvent {
11611        MonetizedPinEvent {
11612            peer: test_peer(b),
11613            pin: [b; 32],
11614            key_count: 100,
11615            quote_ts: SystemTime::now(),
11616        }
11617    }
11618
11619    /// The pending admission cap must equal the number of usable launches the
11620    /// token budget can perform inside one answerability window, counted by
11621    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11622    /// tokens at age zero, one refill per launch interval), not by repeating
11623    /// the derivation formula. Any larger and admitted work is guaranteed to
11624    /// expire unlaunched; any smaller and the budget idles while nominations
11625    /// are displaced.
11626    #[test]
11627    fn first_audit_pending_cap_matches_strict_launch_horizon() {
11628        let quote_ts = SystemTime::now();
11629        // Burst launches fire at age zero and must pass the reserve predicate.
11630        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11631        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11632        let mut refill = 1u32;
11633        loop {
11634            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11635            let at = quote_ts + age;
11636            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11637                break;
11638            }
11639            usable += 1;
11640            refill += 1;
11641            assert!(refill < 10_000, "runaway horizon simulation");
11642        }
11643        assert_eq!(
11644            FIRST_AUDIT_PENDING_CAP, usable,
11645            "cap must match the simulated strict launch horizon"
11646        );
11647    }
11648
11649    /// The pending queue is sized to the launch budget while the dedup set
11650    /// keeps the commitment-cache bound: shrinking `first_audited` would
11651    /// forget audited pins and re-admit duplicates.
11652    #[test]
11653    fn first_audit_pending_cap_independent_of_dedup_cap() {
11654        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11655        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11656        assert_eq!(
11657            scheduler.first_audited.cap().get(),
11658            MAX_LAST_COMMITMENT_BY_PEER
11659        );
11660    }
11661
11662    /// Admission beyond the cap displaces exactly one incumbent per overflow
11663    /// and every displacement is accounted as `capacity_evicted` — the steady
11664    /// overload signal — never silent loss, and never an admission refusal.
11665    #[test]
11666    fn first_audit_admission_beyond_cap_displaces_and_counts() {
11667        let obs = Arc::new(FirstAuditObservability::default());
11668        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11669        let overflow: usize = 5;
11670        let total = FIRST_AUDIT_PENDING_CAP + overflow;
11671
11672        for i in 0..total {
11673            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11674            scheduler.enqueue(live_nomination(b), &obs);
11675        }
11676
11677        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11678        assert_eq!(
11679            obs.capacity_evicted.load(Ordering::Relaxed),
11680            u64::try_from(overflow).expect("overflow fits u64"),
11681            "each admission past the cap displaces exactly one entry"
11682        );
11683        assert_eq!(
11684            obs.queued.load(Ordering::Relaxed),
11685            u64::try_from(total).expect("total fits u64"),
11686            "displacement is not an admission refusal"
11687        );
11688        // Every arrival was admitted (the newest always enters the sample).
11689        let last = u8::try_from(total).expect("test peer count fits u8");
11690        assert!(
11691            scheduler.pending.peek(&test_peer(last)).is_some(),
11692            "the newest arrival always enters the sample"
11693        );
11694    }
11695
11696    /// The reviewer-demonstrated suppression route: a target followed by an
11697    /// ordered batch of distinct-peer nominations, all inside one ingress
11698    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11699    /// the token bucket EMPTY so no reservation can intervene. Under the old
11700    /// keep-newest LRU the target was evicted with certainty; under random
11701    /// displacement its per-overflow eviction probability is `1/cap`, so
11702    /// across repeated trials the target must survive some runs and be
11703    /// displaced in others — never deterministically flushed, and every
11704    /// displacement accounted.
11705    #[test]
11706    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11707        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11708        assert!(FIRST_AUDIT_PENDING_CAP < flood);
11709        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11710
11711        let trials = 100u64;
11712        let mut survived = 0u32;
11713        let mut evicted = 0u32;
11714        for trial in 0..trials {
11715            let obs = Arc::new(FirstAuditObservability::default());
11716            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11717            // Deterministic per-trial seed: the run is fully reproducible (no
11718            // flake budget at all) while still exercising 100 distinct
11719            // eviction sequences.
11720            scheduler.rng = StdRng::seed_from_u64(trial);
11721            // Drain the burst tokens so the pre-overflow reservation
11722            // opportunity cannot fire: this isolates pure retention.
11723            scheduler.limiter.reserve_token();
11724            scheduler.limiter.reserve_token();
11725
11726            let target = test_peer(200);
11727            scheduler.enqueue(live_nomination(200), &obs);
11728            for i in 0..flood {
11729                let b = u8::try_from(i + 1).expect("flood peer fits u8");
11730                scheduler.enqueue(live_nomination(b), &obs);
11731            }
11732
11733            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11734            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11735                .expect("overflow count fits u64");
11736            assert_eq!(
11737                obs.capacity_evicted.load(Ordering::Relaxed),
11738                overflows,
11739                "every overflow past the cap is accounted, none silent"
11740            );
11741            if scheduler.pending.peek(&target).is_some() {
11742                survived += 1;
11743            } else {
11744                evicted += 1;
11745            }
11746        }
11747        // With eviction probability 1/cap per overflow, P(target survives one
11748        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11749        // 100 seeded trials — and the seeds make the split exactly
11750        // reproducible rather than a (vanishingly small) flake budget.
11751        assert!(
11752            survived > 0,
11753            "target must survive some ordered floods — deterministic eviction \
11754             would mean keep-newest retention regressed"
11755        );
11756        assert!(
11757            evicted > 0,
11758            "target must also be displaceable — otherwise overflow is refusing \
11759             admissions instead of sampling"
11760        );
11761    }
11762
11763    /// With a token AVAILABLE, an overflowing arrival must first give pending
11764    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
11765    /// one entry out of the queue, so admission proceeds without any eviction.
11766    #[test]
11767    fn first_audit_overflow_reserves_before_destructive_eviction() {
11768        let obs = Arc::new(FirstAuditObservability::default());
11769        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11770        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11771
11772        for i in 0..FIRST_AUDIT_PENDING_CAP {
11773            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11774            scheduler.enqueue(live_nomination(b), &obs);
11775        }
11776        let overflowing = live_nomination(250);
11777        assert!(scheduler.would_displace(&overflowing));
11778
11779        // The drainer's pre-overflow sequence: reserve, then enqueue.
11780        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
11781        assert!(
11782            !scheduler.would_displace(&overflowing),
11783            "a successful reservation frees the slot"
11784        );
11785        scheduler.enqueue(overflowing, &obs);
11786
11787        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11788        assert_eq!(
11789            obs.capacity_evicted.load(Ordering::Relaxed),
11790            0,
11791            "no destructive eviction when a launch opportunity existed"
11792        );
11793    }
11794
11795    /// Displacement stamps no suppression state: a displaced peer's next
11796    /// nomination re-enters like any newcomer (it is NOT window-deduped or
11797    /// treated as a duplicate), so under overload every peer keeps an
11798    /// unpredictable chance of prompt first audit.
11799    #[test]
11800    fn first_audit_displaced_peer_may_be_renominated() {
11801        let obs = Arc::new(FirstAuditObservability::default());
11802        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11803        let total = FIRST_AUDIT_PENDING_CAP + 1;
11804
11805        for i in 0..total {
11806            let b = u8::try_from(i + 1).expect("test peer count fits u8");
11807            scheduler.enqueue(live_nomination(b), &obs);
11808        }
11809        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
11810        // Find whichever peer the random displacement removed.
11811        let displaced = (1..=total)
11812            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
11813            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
11814            .expect("exactly one admitted peer was displaced");
11815
11816        scheduler.enqueue(live_nomination(displaced), &obs);
11817
11818        assert!(
11819            scheduler.pending.peek(&test_peer(displaced)).is_some(),
11820            "the displaced peer re-enters the sample"
11821        );
11822        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11823        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
11824        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
11825        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
11826    }
11827
11828    /// The periodic sweep collects expired pending entries even when the token
11829    /// bucket is empty — the reserve path returns at the budget gate and never
11830    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
11831    /// honest under fleet-wide starvation.
11832    #[test]
11833    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
11834        let obs = Arc::new(FirstAuditObservability::default());
11835        let mono = Instant::now();
11836        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11837
11838        let dead_quote = SystemTime::now()
11839            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11840            .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11841            .expect("past wall time");
11842        scheduler.enqueue(
11843            MonetizedPinEvent {
11844                peer: test_peer(1),
11845                pin: [1; 32],
11846                key_count: 100,
11847                quote_ts: dead_quote,
11848            },
11849            &obs,
11850        );
11851        scheduler.enqueue(
11852            MonetizedPinEvent {
11853                peer: test_peer(2),
11854                pin: [2; 32],
11855                key_count: 100,
11856                quote_ts: SystemTime::now(),
11857            },
11858            &obs,
11859        );
11860        assert_eq!(scheduler.pending_len(), 2);
11861
11862        // Empty the bucket so the reserve path is budget-gated (fleet-wide
11863        // starvation) and cannot collect the dead entry itself.
11864        scheduler.limiter.tokens = 0;
11865        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
11866        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
11867        assert_eq!(
11868            scheduler.pending_len(),
11869            2,
11870            "budget-gated reserve scans nothing"
11871        );
11872
11873        let wall_now = SystemTime::now();
11874        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
11875        assert_eq!(scheduler.pending_len(), 1);
11876        assert!(
11877            scheduler.pending.peek(&test_peer(2)).is_some(),
11878            "the live entry survives the sweep"
11879        );
11880        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
11881        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
11882        assert!(
11883            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
11884            "the age gauge reflects only live work after the sweep"
11885        );
11886    }
11887
11888    #[test]
11889    #[allow(clippy::too_many_lines)]
11890    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
11891        let obs = Arc::new(FirstAuditObservability::default());
11892        let mono = Instant::now();
11893        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
11894
11895        // A pre-existing window sentinel for an UNRELATED peer must survive the
11896        // cancel byte-for-byte (cancel never touches `recent`).
11897        let sentinel_peer = test_peer(0xAA);
11898        scheduler.limiter.promote(sentinel_peer, 500, mono);
11899        let sentinel_before = scheduler
11900            .limiter
11901            .recent
11902            .peek(&sentinel_peer)
11903            .copied()
11904            .expect("sentinel present");
11905
11906        let peer = test_peer(1);
11907        let a = MonetizedPinEvent {
11908            peer,
11909            pin: [1; 32],
11910            key_count: 100,
11911            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
11912        };
11913        scheduler.enqueue(a, &obs);
11914
11915        let tokens_before = scheduler.tokens();
11916        let lane_before = scheduler.oldest_first_lane;
11917        let launched_before = obs.launched.load(Ordering::Relaxed);
11918        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
11919
11920        // Reserve A (jitter 0 so it is immediately due).
11921        let inflight0 = obs.inflight.load(Ordering::Relaxed);
11922        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
11923        assert_eq!(scheduler.reserved_peer(), Some(peer));
11924        assert_eq!(
11925            scheduler.tokens(),
11926            tokens_before - 1,
11927            "reserve consumes a token"
11928        );
11929        assert_eq!(
11930            obs.inflight.load(Ordering::Relaxed),
11931            1,
11932            "reserve holds a slot"
11933        );
11934
11935        // A same-peer, same-count successor arrives DURING the reservation. It
11936        // must be retained (bypasses the window for the reserved peer) and must
11937        // NOT create a second reservation.
11938        let b = MonetizedPinEvent {
11939            peer,
11940            pin: [2; 32],
11941            key_count: 100,
11942            quote_ts: SystemTime::now(),
11943        };
11944        scheduler.enqueue(b, &obs);
11945        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
11946        assert!(
11947            !scheduler.try_reserve(
11948                mono,
11949                obs.inflight.load(Ordering::Relaxed),
11950                Duration::ZERO,
11951                &cooldown,
11952                &obs
11953            ),
11954            "no second reservation while one is outstanding"
11955        );
11956
11957        // Resolve A with an injected wall time PAST A's answerability cutoff.
11958        let reservation = scheduler
11959            .take_due_reservation(mono)
11960            .expect("A is due at jitter 0");
11961        let wall_fail = a
11962            .quote_ts
11963            .checked_add(GOSSIP_ANSWERABILITY_TTL)
11964            .and_then(|t| t.checked_add(Duration::from_secs(1)))
11965            .expect("past-cutoff wall time");
11966        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
11967        assert!(
11968            promoted.is_none(),
11969            "answerability lapsed -> cancelled, not promoted"
11970        );
11971
11972        // State-neutral cancel.
11973        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
11974        assert!(
11975            scheduler.limiter.recent.peek(&peer).is_none(),
11976            "cancel stamps no per-peer window"
11977        );
11978        assert_eq!(
11979            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
11980            Some(sentinel_before),
11981            "unrelated window sentinel untouched"
11982        );
11983        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
11984        assert_eq!(
11985            scheduler.tokens(),
11986            tokens_before,
11987            "token refunded on cancel"
11988        );
11989        assert_eq!(
11990            obs.inflight.load(Ordering::Relaxed),
11991            0,
11992            "in-flight slot released"
11993        );
11994        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
11995        assert_eq!(
11996            obs.launched.load(Ordering::Relaxed),
11997            launched_before,
11998            "no launch counted"
11999        );
12000        assert_eq!(
12001            obs.outside_answerability_window.load(Ordering::Relaxed),
12002            1,
12003            "the cancel reason is recorded"
12004        );
12005
12006        // The successor is still pending and is now fully schedulable: a fresh
12007        // reserve makes B the next reservation (proving eligibility, not merely
12008        // that the limiter would admit it).
12009        assert_eq!(
12010            scheduler.pending_len(),
12011            1,
12012            "successor still pending after cancel"
12013        );
12014        assert!(scheduler.reserved.is_none());
12015        assert!(scheduler.try_reserve(
12016            mono,
12017            obs.inflight.load(Ordering::Relaxed),
12018            Duration::ZERO,
12019            &cooldown,
12020            &obs
12021        ));
12022        assert_eq!(
12023            scheduler.reserved_peer(),
12024            Some(peer),
12025            "the retained successor becomes the next reservation"
12026        );
12027    }
12028
12029    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12030    /// race, the reserved event is requeued ONLY if no same-peer successor is
12031    /// already pending. A successor arrived after the reservation, so it is the
12032    /// newer nomination (e.g. a count jump) and must not be overwritten by the
12033    /// older reserved event.
12034    #[test]
12035    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12036        let obs = Arc::new(FirstAuditObservability::default());
12037        let mono = Instant::now();
12038        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12039        let peer = test_peer(1);
12040
12041        // Reserve A.
12042        let a = MonetizedPinEvent {
12043            peer,
12044            pin: [1; 32],
12045            key_count: 100,
12046            quote_ts: SystemTime::now(),
12047        };
12048        scheduler.enqueue(a, &obs);
12049        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12050        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12051
12052        // A newer same-peer successor B (a count jump) arrives during the
12053        // reservation and is retained.
12054        let b = MonetizedPinEvent {
12055            peer,
12056            pin: [2; 32],
12057            key_count: 400,
12058            quote_ts: SystemTime::now(),
12059        };
12060        scheduler.enqueue(b, &obs);
12061        assert_eq!(scheduler.pending_len(), 1);
12062
12063        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12064        // is already stamped for the peer, so promotion loses the race.
12065        let reservation = scheduler.take_due_reservation(mono).expect("due");
12066        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12067        cooldown.insert(peer, mono); // freshly on cooldown
12068        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12069        assert!(promoted.is_none(), "cooldown race -> not promoted");
12070
12071        // B (newer) is preserved; A did NOT overwrite it.
12072        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12073        assert_eq!(
12074            scheduler.pending.peek(&peer).map(|e| e.pin),
12075            Some([2; 32]),
12076            "the newer successor B is retained, not the older reserved A"
12077        );
12078        assert!(scheduler.first_audited.is_empty());
12079        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12080    }
12081
12082    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12083    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12084    /// and saturates to `0` for a future-dated quote (clock skew) without
12085    /// panicking. A climbing value is the pending-work-aging-out signal.
12086    #[test]
12087    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12088        let now = SystemTime::now();
12089        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12090        assert_eq!(
12091            scheduler.oldest_pending_quote_age_ms(now),
12092            0,
12093            "empty pending -> zero"
12094        );
12095
12096        // Two peers: quotes 10s and 2s old. The gauge must track the older.
12097        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12098            let _ = coalesce_first_audit_event(
12099                &mut scheduler.pending,
12100                MonetizedPinEvent {
12101                    peer: test_peer(peer_id),
12102                    pin,
12103                    key_count: 100,
12104                    quote_ts: now - Duration::from_secs(secs),
12105                },
12106                true,
12107                &mut scheduler.rng,
12108            );
12109        }
12110        assert_eq!(
12111            scheduler.oldest_pending_quote_age_ms(now),
12112            10_000,
12113            "tracks the oldest (10s), not the newest (2s)"
12114        );
12115
12116        // A future-dated quote (clock skew) saturates to zero, never panics.
12117        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12118        let _ = coalesce_first_audit_event(
12119            &mut skewed.pending,
12120            MonetizedPinEvent {
12121                peer: test_peer(3),
12122                pin: [3; 32],
12123                key_count: 100,
12124                quote_ts: now + Duration::from_secs(5),
12125            },
12126            true,
12127            &mut skewed.rng,
12128        );
12129        assert_eq!(
12130            skewed.oldest_pending_quote_age_ms(now),
12131            0,
12132            "future quote_ts saturates to zero"
12133        );
12134    }
12135
12136    /// A flood of strictly-lower-count same-peer nominations must neither
12137    /// displace the retained higher pin NOR disturb its recency position (each
12138    /// is suppressed via `peek`, no `push`), and each must be counted as
12139    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12140    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12141    /// (the documented `lru` contract that also drives the reserve scan's lane
12142    /// ordering), deliberately independent of the overflow policy: eviction is
12143    /// random-victim, so no assertion may require a particular peer to be
12144    /// displaced.
12145    #[test]
12146    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12147        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12148            LruCache::new(NonZeroUsize::new(2).unwrap());
12149        let mut rng = StdRng::seed_from_u64(11);
12150        let victim = test_peer(1);
12151        let other = test_peer(2);
12152        // Victim (high count) inserted first (older), then `other` (newer/MRU).
12153        let _ = coalesce_first_audit_event(
12154            &mut pending,
12155            MonetizedPinEvent {
12156                peer: victim,
12157                pin: [1; 32],
12158                key_count: 400,
12159                quote_ts: SystemTime::now(),
12160            },
12161            true,
12162            &mut rng,
12163        );
12164        let _ = coalesce_first_audit_event(
12165            &mut pending,
12166            MonetizedPinEvent {
12167                peer: other,
12168                pin: [9; 32],
12169                key_count: 100,
12170                quote_ts: SystemTime::now(),
12171            },
12172            true,
12173            &mut rng,
12174        );
12175        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12176        assert_eq!(
12177            order_before,
12178            vec![other, victim],
12179            "sanity: `other` is MRU, the victim is LRU"
12180        );
12181
12182        // Flood the victim with cheaper nominations.
12183        let mut suppressed = 0u64;
12184        for i in 0..8u8 {
12185            let out = coalesce_first_audit_event(
12186                &mut pending,
12187                MonetizedPinEvent {
12188                    peer: victim,
12189                    pin: [i; 32],
12190                    key_count: 50,
12191                    quote_ts: SystemTime::now(),
12192                },
12193                true,
12194                &mut rng,
12195            );
12196            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12197            suppressed += 1;
12198        }
12199        assert_eq!(suppressed, 8);
12200        // Victim pin/count unchanged.
12201        assert_eq!(
12202            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12203            Some(([1; 32], 400))
12204        );
12205        // Recency untouched: the iteration order (which the reserve lanes
12206        // consume) is byte-for-byte what it was before the flood.
12207        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12208        assert_eq!(
12209            order_after, order_before,
12210            "the suppressed-lower flood must not have changed any recency position"
12211        );
12212    }
12213
12214    /// The cooldown-race requeue counts a genuine different-peer capacity
12215    /// eviction (the ADR promises capacity loss is observable).
12216    #[test]
12217    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12218        let obs = Arc::new(FirstAuditObservability::default());
12219        let mono = Instant::now();
12220        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12221        // Pending capacity 1 so a requeue of a different peer must evict.
12222        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12223        let reserved_peer = test_peer(1);
12224        let other_peer = test_peer(2);
12225
12226        // Reserve peer 1.
12227        scheduler.enqueue(
12228            MonetizedPinEvent {
12229                peer: reserved_peer,
12230                pin: [1; 32],
12231                key_count: 100,
12232                quote_ts: SystemTime::now(),
12233            },
12234            &obs,
12235        );
12236        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12237        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12238
12239        // A DIFFERENT peer fills the single pending slot during the reservation.
12240        scheduler.enqueue(
12241            MonetizedPinEvent {
12242                peer: other_peer,
12243                pin: [2; 32],
12244                key_count: 100,
12245                quote_ts: SystemTime::now(),
12246            },
12247            &obs,
12248        );
12249        assert_eq!(scheduler.pending_len(), 1);
12250
12251        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12252        let reservation = scheduler.take_due_reservation(mono).expect("due");
12253        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12254        cooldown.insert(reserved_peer, mono);
12255        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12256        assert!(scheduler
12257            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12258            .is_none());
12259        assert_eq!(
12260            obs.capacity_evicted.load(Ordering::Relaxed),
12261            cap_before + 1,
12262            "the requeue eviction of a different peer is counted"
12263        );
12264        assert_eq!(
12265            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12266            Some([1; 32])
12267        );
12268    }
12269
12270    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12271    /// nomination arriving while an inflated pin is PENDING must not displace it.
12272    /// The inflated pin stays and is the one launched.
12273    #[test]
12274    fn first_audit_pending_lower_count_does_not_replace_higher() {
12275        let obs = Arc::new(FirstAuditObservability::default());
12276        let mono = Instant::now();
12277        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12278        let peer = test_peer(1);
12279
12280        // Inflated (high-count) sidecar pin lands in pending.
12281        scheduler.enqueue(
12282            MonetizedPinEvent {
12283                peer,
12284                pin: [1; 32],
12285                key_count: 400,
12286                quote_ts: SystemTime::now(),
12287            },
12288            &obs,
12289        );
12290        // A cheaper same-peer settlement arrives right after.
12291        scheduler.enqueue(
12292            MonetizedPinEvent {
12293                peer,
12294                pin: [2; 32],
12295                key_count: 100,
12296                quote_ts: SystemTime::now(),
12297            },
12298            &obs,
12299        );
12300
12301        assert_eq!(scheduler.pending_len(), 1);
12302        assert_eq!(
12303            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12304            Some(([1; 32], 400)),
12305            "the inflated pin must not be erased by the cheaper successor"
12306        );
12307        // The dropped cheaper nomination is counted through the enqueue path.
12308        assert_eq!(
12309            obs.suppressed_lower.load(Ordering::Relaxed),
12310            1,
12311            "the attempted cheaper-pin self-erasure is observable"
12312        );
12313
12314        // It reserves and promotes as the inflated pin/count.
12315        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12316        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12317        let reservation = scheduler.take_due_reservation(mono).expect("due");
12318        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12319        let (event, _slot) = scheduler
12320            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12321            .expect("promotes");
12322        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12323    }
12324
12325    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12326    /// loses the cooldown race must be requeued OVER a lower-count same-peer
12327    /// successor that arrived during its jitter, and must remain launchable once
12328    /// the shared cooldown expires — the cheaper successor cannot suppress it.
12329    #[test]
12330    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12331        let obs = Arc::new(FirstAuditObservability::default());
12332        let mono = Instant::now();
12333        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12334        let peer = test_peer(1);
12335
12336        // Reserve the inflated pin.
12337        scheduler.enqueue(
12338            MonetizedPinEvent {
12339                peer,
12340                pin: [1; 32],
12341                key_count: 400,
12342                quote_ts: SystemTime::now(),
12343            },
12344            &obs,
12345        );
12346        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12347        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12348
12349        // A cheaper successor arrives during the reservation (bypasses the
12350        // window as the reserved peer) and sits in pending.
12351        scheduler.enqueue(
12352            MonetizedPinEvent {
12353                peer,
12354                pin: [2; 32],
12355                key_count: 100,
12356                quote_ts: SystemTime::now(),
12357            },
12358            &obs,
12359        );
12360        assert_eq!(scheduler.pending_len(), 1);
12361
12362        // Resolve: answerability passes but the shared cooldown is already
12363        // stamped, so the reservation loses the race and requeues.
12364        let reservation = scheduler.take_due_reservation(mono).expect("due");
12365        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12366        cooldown.insert(peer, mono);
12367        assert!(scheduler
12368            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12369            .is_none());
12370
12371        // The inflated pin (400) replaced the cheaper successor (100).
12372        assert_eq!(scheduler.pending_len(), 1);
12373        assert_eq!(
12374            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12375            Some(([1; 32], 400)),
12376            "the inflated reserved pin must survive the requeue over the cheaper successor"
12377        );
12378        assert!(scheduler.first_audited.is_empty());
12379        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12380
12381        // Once the shared cooldown expires, the inflated pin reserves and
12382        // promotes with its intended pin/count.
12383        let later = mono
12384            .checked_add(Duration::from_secs(
12385                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12386            ))
12387            .expect("later");
12388        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12389        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12390        let reservation = scheduler.take_due_reservation(later).expect("due");
12391        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12392        let (event, _slot) = scheduler
12393            .resolve(
12394                reservation,
12395                SystemTime::now(),
12396                later,
12397                &mut cooldown_later,
12398                &obs,
12399            )
12400            .expect("promotes after cooldown");
12401        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12402    }
12403
12404    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12405    /// launch lane, driven through the real scheduler (reserve -> resolve ->
12406    /// promote), so a stream of fresh nominations cannot keep every launch on
12407    /// the newest lane and starve the oldest.
12408    #[test]
12409    fn first_audit_lane_alternates_across_promotions() {
12410        let obs = Arc::new(FirstAuditObservability::default());
12411        let mono = Instant::now();
12412        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12413        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12414
12415        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12416        let oldest_peer = test_peer(1);
12417        let newest_peer = test_peer(2);
12418        scheduler.enqueue(
12419            MonetizedPinEvent {
12420                peer: oldest_peer,
12421                pin: [1; 32],
12422                key_count: 100,
12423                quote_ts: SystemTime::now(),
12424            },
12425            &obs,
12426        );
12427        scheduler.enqueue(
12428            MonetizedPinEvent {
12429                peer: newest_peer,
12430                pin: [2; 32],
12431                key_count: 100,
12432                quote_ts: SystemTime::now(),
12433            },
12434            &obs,
12435        );
12436
12437        let mut launched_peers = Vec::new();
12438        for _ in 0..2 {
12439            assert!(scheduler.try_reserve(
12440                mono,
12441                obs.inflight.load(Ordering::Relaxed),
12442                Duration::ZERO,
12443                &cooldown,
12444                &obs
12445            ));
12446            let reservation = scheduler.take_due_reservation(mono).expect("due");
12447            // Answerable wall time == the quote's own time (age 0).
12448            let (event, _slot) = scheduler
12449                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12450                .expect("fresh in-window quote promotes");
12451            launched_peers.push(event.peer);
12452        }
12453
12454        // First launch takes the newest lane (lane starts false = newest), the
12455        // second takes the oldest lane: strict alternation.
12456        assert_eq!(
12457            launched_peers,
12458            vec![newest_peer, oldest_peer],
12459            "consecutive promotions alternate newest-then-oldest lane"
12460        );
12461    }
12462
12463    #[test]
12464    fn first_audit_count_jump_boundaries() {
12465        // Exactly 1.5x is NOT a jump; strictly above is.
12466        assert!(!first_audit_count_jump(100, 150));
12467        assert!(first_audit_count_jump(100, 151));
12468        // Anything beats an audited zero; zero never jumps.
12469        assert!(first_audit_count_jump(0, 1));
12470        assert!(!first_audit_count_jump(0, 0));
12471        // Equal max counts must not jump (and must not overflow).
12472        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12473    }
12474
12475    /// A verified payment's quote list includes the local node's own quote, so
12476    /// the verifier emits a monetized-pin event for the local peer on every
12477    /// payment it verifies. The node cannot network-audit itself, so the
12478    /// scheduler must drop such an event at ingress: never queued, and hence
12479    /// never launched nor marked first-audited.
12480    #[test]
12481    fn first_audit_queue_drops_self_targeting_events() {
12482        let obs = Arc::new(FirstAuditObservability::default());
12483        let self_peer = test_peer(1);
12484        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12485        let self_event = MonetizedPinEvent {
12486            peer: self_peer,
12487            pin: [7; 32],
12488            key_count: 1,
12489            quote_ts: SystemTime::now(),
12490        };
12491
12492        scheduler.enqueue(self_event, &obs);
12493        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12494        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12495        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12496
12497        // A remote peer's event still queues normally under the same filter.
12498        let remote_event = MonetizedPinEvent {
12499            peer: test_peer(2),
12500            pin: [8; 32],
12501            ..self_event
12502        };
12503        scheduler.enqueue(remote_event, &obs);
12504        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12505        assert_eq!(scheduler.pending_len(), 1);
12506        assert_eq!(
12507            obs.self_target_skipped.load(Ordering::Relaxed),
12508            1,
12509            "remote event must not count as a self-target skip"
12510        );
12511    }
12512
12513    #[test]
12514    fn fresh_offer_runs_store_admission_payment_checks() {
12515        let context = fresh_offer_payment_context();
12516        assert_eq!(context, VerificationContext::FreshReplication);
12517        // Fresh replication must keep verifying exactly like a direct client
12518        // PUT (store-strength cache, same live checks); the variant only
12519        // exists so price-floor telemetry can tell the two paths apart.
12520        assert!(context.is_store_admission());
12521    }
12522
12523    #[test]
12524    fn paid_notify_uses_paid_list_admission_payment_checks() {
12525        assert_eq!(
12526            paid_notify_payment_context(),
12527            VerificationContext::PaidListAdmission
12528        );
12529    }
12530
12531    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12532    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12533    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12534    #[test]
12535    fn monetized_quote_audit_window_fails_closed_both_ends() {
12536        let now = SystemTime::now();
12537        // Fresh (just quoted) and small future/past skew -> audited.
12538        assert!(quote_within_audit_window(now, now));
12539        assert!(quote_within_audit_window(
12540            now + Duration::from_secs(60),
12541            now
12542        ));
12543        assert!(quote_within_audit_window(
12544            now - Duration::from_secs(3600),
12545            now
12546        ));
12547        // Far future (badly-skewed / replayed) -> skipped.
12548        assert!(!quote_within_audit_window(
12549            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12550            now
12551        ));
12552        // Older than the window -> skipped (pin may have aged out).
12553        assert!(!quote_within_audit_window(
12554            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12555            now
12556        ));
12557    }
12558
12559    #[tokio::test]
12560    async fn replication_branch_lagged_events_are_counted() {
12561        let before = audit_metrics::replication_event_lagged_total();
12562        let flow = handle_replication_event_recv_error(
12563            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12564        );
12565        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12566        let after = audit_metrics::replication_event_lagged_total();
12567        assert_eq!(after.saturating_sub(before), 3);
12568    }
12569
12570    #[tokio::test]
12571    async fn replication_branch_closed_events_stop_the_loop() {
12572        let flow =
12573            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12574        assert_eq!(flow, std::ops::ControlFlow::Break(()));
12575    }
12576
12577    #[tokio::test]
12578    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12579        let (sender, mut receiver) = mpsc::channel(1);
12580        let dropped_body =
12581            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12582                keys: Vec::new(),
12583                paid_list_check_indices: Vec::new(),
12584            });
12585        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12586        let first = InboundReplicationMessage {
12587            source: test_peer(0xC1),
12588            msg: ReplicationMessage {
12589                request_id: 1,
12590                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12591                    key: test_key(1),
12592                }),
12593            },
12594            rr_message_id: None,
12595            received_at: Instant::now(),
12596        };
12597        let second = InboundReplicationMessage {
12598            source: test_peer(0xC2),
12599            msg: ReplicationMessage {
12600                request_id: 2,
12601                body: dropped_body.clone(),
12602            },
12603            rr_message_id: None,
12604            received_at: Instant::now(),
12605        };
12606
12607        assert!(try_enqueue_serial_message(&sender, first).is_ok());
12608        let dropped = try_enqueue_serial_message(&sender, second)
12609            .expect_err("a full serial queue must refuse the second message");
12610        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12611        assert_eq!(dropped.message_class, "verification_request");
12612        assert_eq!(dropped.queue_depth, 1);
12613        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12614        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12615
12616        let queued = receiver
12617            .recv()
12618            .await
12619            .expect("first message should remain queued");
12620        assert_eq!(queued.msg.request_id, 1);
12621        assert!(receiver.try_recv().is_err());
12622    }
12623
12624    #[tokio::test]
12625    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12626        let peer = test_peer(0x44);
12627        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12628
12629        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12630        let mut digest_guards = Vec::new();
12631        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12632            let guard = admit_audit_responder(
12633                &semaphore,
12634                &digest_inflight,
12635                &peer,
12636                AuditResponderClass::Digest,
12637            )
12638            .await;
12639            assert!(guard.is_ok());
12640            digest_guards.push(guard);
12641        }
12642        assert!(
12643            admit_audit_responder(
12644                &semaphore,
12645                &digest_inflight,
12646                &peer,
12647                AuditResponderClass::Digest,
12648            )
12649            .await
12650            .is_err(),
12651            "digest class must stop at its documented per-source cap"
12652        );
12653        drop(digest_guards);
12654
12655        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12656        let mut subtree_guards = Vec::new();
12657        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12658            let guard = admit_audit_responder(
12659                &semaphore,
12660                &subtree_inflight,
12661                &peer,
12662                AuditResponderClass::Subtree,
12663            )
12664            .await;
12665            assert!(guard.is_ok());
12666            subtree_guards.push(guard);
12667        }
12668        assert!(
12669            admit_audit_responder(
12670                &semaphore,
12671                &subtree_inflight,
12672                &peer,
12673                AuditResponderClass::Subtree,
12674            )
12675            .await
12676            .is_err(),
12677            "subtree class must retain the deployed cap of two"
12678        );
12679        drop(subtree_guards);
12680    }
12681
12682    #[test]
12683    fn in_scope_audit_deadlines_share_one_formula() {
12684        let config = config::ReplicationConfig::default();
12685        for key_count in [1, 4, 16] {
12686            assert_eq!(
12687                audit::responsible_audit_response_timeout(&config, key_count),
12688                config.audit_response_timeout(key_count)
12689            );
12690            assert_eq!(
12691                pruning::prune_audit_response_timeout(&config, key_count),
12692                config.audit_response_timeout(key_count)
12693            );
12694        }
12695        assert_eq!(
12696            possession::possession_probe_response_timeout(&config),
12697            config.audit_response_timeout(1)
12698        );
12699    }
12700
12701    #[test]
12702    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12703        const EXISTING_SOURCE_ID: u8 = 1;
12704        const HINT_SENDER_ID: u8 = 2;
12705
12706        let existing_source = test_peer(EXISTING_SOURCE_ID);
12707        let hint_sender = test_peer(HINT_SENDER_ID);
12708        let mut sources = vec![existing_source];
12709
12710        let hint_sources = HashSet::from([hint_sender]);
12711        add_replica_hint_sources(&mut sources, &hint_sources);
12712        add_replica_hint_sources(&mut sources, &hint_sources);
12713
12714        // A paid-only advertiser leaves the claim set empty (see
12715        // `queue_admitted_hints`), so it contributes no fetch source.
12716        add_replica_hint_sources(&mut sources, &HashSet::new());
12717
12718        assert_eq!(sources, vec![existing_source, hint_sender]);
12719    }
12720
12721    #[test]
12722    fn audit_timeout_preserves_active_bootstrap_claim() {
12723        assert!(!audit_failure_clears_bootstrap_claim(
12724            &AuditFailureReason::Timeout
12725        ));
12726    }
12727
12728    fn strike_peer(b: u8) -> PeerId {
12729        let mut bytes = [0u8; 32];
12730        bytes[0] = b;
12731        PeerId::from_bytes(bytes)
12732    }
12733
12734    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12735    // cooldown must collapse a gossip flood into at most one audit per window.
12736
12737    #[test]
12738    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12739        let peer = strike_peer(1);
12740        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12741        let t0 = Instant::now();
12742        // First gossip in the window passes; a burst of further gossips at the
12743        // same instant are all suppressed.
12744        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12745        let mut passed = 1;
12746        for _ in 0..100 {
12747            if cooldown_allows_audit(&mut map, &peer, t0) {
12748                passed += 1;
12749            }
12750        }
12751        assert_eq!(
12752            passed, 1,
12753            "a flood at one instant must trigger exactly one audit"
12754        );
12755    }
12756
12757    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12758    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12759    // consumes the window. This is the property the isolated cooldown tests above
12760    // cannot see: they never sample the lottery, so a regression that reordered
12761    // the gates (sample probability first, only stamp the cooldown on a win)
12762    // would still pass them while breaking flood-resistance: a flood would then
12763    // re-roll the lottery on EVERY message until one won, multiplying audits.
12764    //
12765    // We model the exact production gate order (attempt-window, lottery,
12766    // shared cooldown) with a lottery driven by a fixed outcome instead of
12767    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
12768    // messages all WIN. With the production order, the losing first ticket
12769    // burns the ATTEMPT window and every later winner in the same window is
12770    // blocked, so there are 0 audits this window. If the gates were flipped,
12771    // the second message's winning ticket would slip through. The window only
12772    // reopens after it elapses.
12773    //
12774    // FLIPS IF: the lottery is sampled before the attempt-window
12775    // check-and-stamp (a losing ticket no longer consumes the window),
12776    // re-enabling a flood-amplified audit storm.
12777    #[test]
12778    fn losing_lottery_still_consumes_attempt_window() {
12779        // Calls the SHIPPED `audit_launch_decision` (the same function
12780        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
12781        // production fails this test — not a local reimplementation.
12782        let peer = strike_peer(3);
12783        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12784        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12785        let t0 = Instant::now();
12786
12787        // First flooded message at t0 LOSES the lottery, but the attempt window
12788        // is stamped BEFORE the lottery is consulted, so the window is consumed.
12789        assert!(
12790            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
12791            "a losing ticket launches no audit"
12792        );
12793
12794        // 99 more flooded messages at the same instant would all WIN the lottery,
12795        // yet every one must be blocked by the attempt window the loser stamped.
12796        // (If production sampled the lottery FIRST, these would each get a fresh
12797        // roll and audits would multiply — this assertion catches that reorder.)
12798        let mut audits = 0;
12799        for _ in 0..99 {
12800            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
12801                audits += 1;
12802            }
12803        }
12804        assert_eq!(
12805            audits, 0,
12806            "a losing first ticket must consume the attempt window so no later \
12807             flooded message in the same window can audit"
12808        );
12809
12810        // The window only reopens after it elapses; the next winning ticket
12811        // then launches exactly one audit and stamps the SHARED cooldown.
12812        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12813        assert!(
12814            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
12815            "after the window a winning ticket audits again"
12816        );
12817        assert!(
12818            launched.contains_key(&peer),
12819            "a real launch stamps the shared cooldown"
12820        );
12821    }
12822
12823    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
12824    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
12825    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
12826    /// first audit deferred until its answerability window expires.
12827    ///
12828    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
12829    /// loss (the pre-split behavior, where both paths shared one map).
12830    #[test]
12831    fn losing_lottery_does_not_suppress_monetized_first_audit() {
12832        let peer = strike_peer(4);
12833        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
12834        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
12835        let t0 = Instant::now();
12836
12837        // A losing ticket consumes the gossip attempt window...
12838        assert!(!audit_launch_decision(
12839            &mut attempts,
12840            &mut launched,
12841            &peer,
12842            t0,
12843            false
12844        ));
12845        // ...but leaves the shared map untouched, so the first-audit reserve
12846        // gate (read-only) and the authoritative promotion check-and-stamp both
12847        // still allow the paid audit to launch immediately.
12848        assert!(
12849            cooldown_would_allow(&launched, &peer, t0),
12850            "reserve gate must not see a losing ticket as audit coverage"
12851        );
12852        assert!(
12853            cooldown_allows_audit(&mut launched, &peer, t0),
12854            "promotion must not be deferred by a losing ticket"
12855        );
12856
12857        // Conversely a WINNING ticket (real audit sent) does suppress the
12858        // first audit for the window, which is the intended shared semantics.
12859        let peer_won = strike_peer(5);
12860        assert!(audit_launch_decision(
12861            &mut attempts,
12862            &mut launched,
12863            &peer_won,
12864            t0,
12865            true
12866        ));
12867        assert!(
12868            !cooldown_would_allow(&launched, &peer_won, t0),
12869            "a real gossip audit still covers the peer for the window"
12870        );
12871    }
12872
12873    #[test]
12874    fn cooldown_lets_audit_through_after_the_window() {
12875        let peer = strike_peer(2);
12876        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12877        let t0 = Instant::now();
12878        assert!(cooldown_allows_audit(&mut map, &peer, t0));
12879        // Within the window: suppressed.
12880        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
12881        assert!(!cooldown_allows_audit(&mut map, &peer, within));
12882        // Past the window: allowed again.
12883        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
12884        assert!(cooldown_allows_audit(&mut map, &peer, after));
12885    }
12886
12887    #[test]
12888    fn cooldown_is_per_peer_independent() {
12889        let mut map: HashMap<PeerId, Instant> = HashMap::new();
12890        let t0 = Instant::now();
12891        // Different peers each get their own first-audit pass at the same instant.
12892        for i in 0..20u8 {
12893            assert!(
12894                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
12895                "peer {i} should be auditable independently"
12896            );
12897        }
12898    }
12899
12900    #[test]
12901    fn audit_on_gossip_constants_match_adr() {
12902        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
12903        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
12904        // values above 5 would silently never be requested).
12905        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
12906        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
12907        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
12908    }
12909
12910    // (d) A confirmed storage-integrity failure penalizes immediately and
12911    // revokes credit; it is not a timeout.
12912    #[test]
12913    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
12914        assert!(audit_failure_clears_bootstrap_claim(
12915            &AuditFailureReason::DigestMismatch
12916        ));
12917        assert!(audit_failure_revokes_holder_credit(
12918            &AuditFailureReason::DigestMismatch
12919        ));
12920    }
12921
12922    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
12923    /// uses: confirmed failures revoke credit, `Timeout` does not.
12924    #[test]
12925    fn confirmed_failures_revoke_credit_timeout_does_not() {
12926        for reason in [
12927            AuditFailureReason::MalformedResponse,
12928            AuditFailureReason::DigestMismatch,
12929            AuditFailureReason::KeyAbsent,
12930            AuditFailureReason::Rejected,
12931        ] {
12932            assert!(
12933                audit_failure_revokes_holder_credit(&reason),
12934                "confirmed failure {reason:?} must revoke holder credit"
12935            );
12936        }
12937        assert!(
12938            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
12939            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
12940        );
12941    }
12942
12943    /// Wiring test for the security fix: the helper the handler calls
12944    /// actually strips a credited peer on a confirmed failure
12945    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
12946    /// Records genuine credit first so neither assertion is vacuous;
12947    /// this fails if `forget_peer` stops being called, or if the
12948    /// `Timeout` exclusion is dropped (both verified by mutation).
12949    #[test]
12950    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
12951        let peer = test_peer(0xAB);
12952        let key = test_key(1);
12953        let hash = [0xCD; 32];
12954
12955        // Confirmed failure -> credit revoked.
12956        let mut provers = RecentProvers::new();
12957        provers.record_proof(key, peer, hash, Instant::now());
12958        assert!(
12959            provers.is_credited_holder(&key, &peer, &hash),
12960            "precondition: peer credited before failure"
12961        );
12962        apply_audit_failure_credit_revocation(
12963            &mut provers,
12964            &peer,
12965            &AuditFailureReason::DigestMismatch,
12966        );
12967        assert!(
12968            !provers.is_credited_holder(&key, &peer, &hash),
12969            "DigestMismatch must strip the peer's holder credit"
12970        );
12971
12972        // Timeout -> credit retained.
12973        let mut provers_timeout = RecentProvers::new();
12974        provers_timeout.record_proof(key, peer, hash, Instant::now());
12975        apply_audit_failure_credit_revocation(
12976            &mut provers_timeout,
12977            &peer,
12978            &AuditFailureReason::Timeout,
12979        );
12980        assert!(
12981            provers_timeout.is_credited_holder(&key, &peer, &hash),
12982            "Timeout must retain holder credit (deliberate liveness cushion)"
12983        );
12984    }
12985
12986    #[test]
12987    fn decoded_audit_failures_clear_active_bootstrap_claim() {
12988        for reason in [
12989            AuditFailureReason::MalformedResponse,
12990            AuditFailureReason::DigestMismatch,
12991            AuditFailureReason::KeyAbsent,
12992            AuditFailureReason::Rejected,
12993        ] {
12994            assert!(
12995                audit_failure_clears_bootstrap_claim(&reason),
12996                "decoded non-bootstrap failure {reason:?} should clear active claim"
12997            );
12998        }
12999    }
13000
13001    #[test]
13002    fn first_failed_key_label_truncates_to_16_hex_chars() {
13003        // The high-order 8 bytes of the XorName determine the label so an
13004        // operator can group audit-failures on the same chunk prefix.
13005        let mut key = [0u8; 32];
13006        key[0] = 0x18;
13007        key[7] = 0xff;
13008        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13009        // to verify they are NOT included in the label.
13010        for byte in &mut key[8..] {
13011            *byte = 0xAA;
13012        }
13013        let label = first_failed_key_label(&[key]);
13014        // Only the first 8 bytes are encoded, low-order bytes are dropped.
13015        assert_eq!(label, "0x18000000000000ff");
13016        assert_eq!(label.len(), "0x".len() + 16);
13017    }
13018
13019    #[test]
13020    fn first_failed_key_label_falls_back_when_empty() {
13021        // Should never happen in production (audit failure handling rejects
13022        // empty sets), but the formatter must still produce a valid label
13023        // so the log line doesn't contain a misleading default.
13024        assert_eq!(first_failed_key_label(&[]), "0x");
13025    }
13026
13027    #[test]
13028    fn first_failed_key_label_uses_first_key_only() {
13029        let first = [0x11u8; 32];
13030        let second = [0x22u8; 32];
13031        assert_eq!(
13032            first_failed_key_label(&[first, second]),
13033            format!("0x{}", hex::encode(&first[..8]))
13034        );
13035    }
13036
13037    // -- apply_fetch_result --------------------------------------------------
13038    //
13039    // The worker's disposition of a fetch outcome. Note there is no trust
13040    // handle in `apply_fetch_result`'s signature: the worker cannot report a
13041    // trust event for ANY outcome, and `execute_single_fetch` returns
13042    // `NoLongerResponsible` before its trust-reporting paths — the source did
13043    // nothing wrong when this node's own responsibility lapsed.
13044
13045    /// Route `key` through the real pipeline stages (pending → promoted →
13046    /// dequeued → in-flight) so it carries a verification retry-slot
13047    /// reservation, exactly as a worker-dequeued key does. Returns the
13048    /// in-flight source.
13049    fn drive_key_in_flight(
13050        q: &mut ReplicationQueues,
13051        key: XorName,
13052        sources: Vec<PeerId>,
13053    ) -> PeerId {
13054        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13055        let now = Instant::now();
13056        let entry = VerificationEntry {
13057            state: VerificationState::PendingVerify,
13058            verified_sources: Vec::new(),
13059            tried_sources: HashSet::new(),
13060            created_at: now,
13061            next_verify_at: now,
13062            hint_sources: HashSet::from([hinter]),
13063            replica_hint_sources: HashSet::from([hinter]),
13064            unresolved_retries: 0,
13065            no_holder_reported: false,
13066        };
13067        assert!(q.add_pending_verify(key, entry).admitted());
13068        assert!(q.promote_pending_to_fetch(key, key, sources));
13069        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13070        let source = *candidate.sources.first().expect("candidate has a source");
13071        q.start_dequeued_fetch(candidate, source);
13072        source
13073    }
13074
13075    #[test]
13076    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13077        const RETRY_AFTER: Duration = Duration::from_secs(60);
13078
13079        let mut q = ReplicationQueues::new();
13080        let key = test_key(0xAB);
13081        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13082        assert_eq!(q.retry_reserved_slot_count(), 1);
13083
13084        let follow_up =
13085            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13086
13087        assert_eq!(
13088            follow_up,
13089            FetchFollowUp::Terminal,
13090            "lapsed responsibility must run the caller's terminal bootstrap accounting"
13091        );
13092        assert!(
13093            !q.contains_key(&key),
13094            "the key must leave every pipeline stage — alternate sources included"
13095        );
13096        assert_eq!(
13097            q.pending_count(),
13098            0,
13099            "a lapsed-responsibility key must not be requeued for verification"
13100        );
13101        assert_eq!(
13102            q.retry_reserved_slot_count(),
13103            0,
13104            "terminal exit must release the verification retry-slot reservation"
13105        );
13106    }
13107
13108    #[test]
13109    fn no_longer_responsible_shares_the_stored_terminal_path() {
13110        const RETRY_AFTER: Duration = Duration::from_secs(60);
13111
13112        // Both variants must walk the identical terminal gate so the
13113        // battle-tested Stored accounting (retry-slot release + bootstrap
13114        // pending-set shrink in the caller) covers lapsed responsibility too.
13115        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13116            let mut q = ReplicationQueues::new();
13117            let key = test_key(0xCD);
13118            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13119
13120            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13121
13122            assert_eq!(follow_up, FetchFollowUp::Terminal);
13123            assert!(!q.contains_key(&key));
13124            assert_eq!(q.retry_reserved_slot_count(), 0);
13125        }
13126    }
13127
13128    #[test]
13129    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13130        const RETRY_AFTER: Duration = Duration::from_secs(60);
13131
13132        let mut q = ReplicationQueues::new();
13133        let key = test_key(0xEF);
13134        let first = test_peer(0x04);
13135        let second = test_peer(0x05);
13136        drive_key_in_flight(&mut q, key, vec![first, second]);
13137
13138        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13139        assert_eq!(
13140            follow_up,
13141            FetchFollowUp::RetryFrom(second),
13142            "a failed source must not abandon the remaining verified sources"
13143        );
13144        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13145
13146        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13147        assert_eq!(
13148            follow_up,
13149            FetchFollowUp::RequeuedForVerification,
13150            "exhausted sources must restore the reserved verification entry"
13151        );
13152        assert_eq!(q.pending_count(), 1);
13153        assert_eq!(
13154            q.retry_reserved_slot_count(),
13155            0,
13156            "the reservation converts back into the pending entry itself"
13157        );
13158    }
13159
13160    #[test]
13161    fn source_failure_without_retry_metadata_is_terminal() {
13162        const RETRY_AFTER: Duration = Duration::from_secs(60);
13163
13164        // Direct enqueue (no pending entry) models a fetch with no
13165        // verification retry reservation to restore.
13166        let mut q = ReplicationQueues::new();
13167        let key = test_key(0x1F);
13168        let source = test_peer(0x06);
13169        assert!(q.enqueue_fetch(key, key, vec![source]));
13170        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13171        q.start_dequeued_fetch(candidate, source);
13172
13173        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13174
13175        assert_eq!(follow_up, FetchFollowUp::Terminal);
13176        assert!(!q.contains_key(&key));
13177    }
13178
13179    #[test]
13180    fn already_held_key_leaves_the_pipeline_terminally() {
13181        const RETRY_AFTER: Duration = Duration::from_secs(60);
13182
13183        let mut q = ReplicationQueues::new();
13184        let key = test_key(0x4C);
13185        let source = test_peer(0x0B);
13186        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13187
13188        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13189
13190        assert_eq!(
13191            follow_up,
13192            FetchFollowUp::Terminal,
13193            "holding the key already discharges the duty, so the key must leave \
13194             the pipeline exactly as a completed fetch does — requeueing it \
13195             would re-verify a key that needs nothing"
13196        );
13197        assert!(!q.contains_key(&key));
13198        assert_eq!(
13199            q.retry_reserved_slot_count(),
13200            0,
13201            "the terminal path must release the retry-slot reservation, or the \
13202             owner's verification budget leaks"
13203        );
13204    }
13205
13206    #[test]
13207    fn local_write_failure_does_not_conscript_the_remaining_sources() {
13208        const RETRY_AFTER: Duration = Duration::from_secs(60);
13209
13210        let mut q = ReplicationQueues::new();
13211        let key = test_key(0x2A);
13212        let first = test_peer(0x07);
13213        let second = test_peer(0x08);
13214        let third = test_peer(0x09);
13215        drive_key_in_flight(&mut q, key, vec![first, second, third]);
13216
13217        let follow_up =
13218            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13219
13220        assert_eq!(
13221            follow_up,
13222            FetchFollowUp::RequeuedForVerification,
13223            "a local write failure must go straight back to verification: the two \
13224             untried sources would each re-upload the same chunk into the same \
13225             full disk, and neither of them did anything wrong"
13226        );
13227        assert_eq!(q.in_flight_count(), 0);
13228        assert_eq!(
13229            q.pending_count(),
13230            1,
13231            "the key must come back — capacity frees up, and a stranded key is \
13232             a replica this node silently stops owing"
13233        );
13234        assert_eq!(q.retry_reserved_slot_count(), 0);
13235    }
13236
13237    #[test]
13238    fn local_write_failure_without_retry_metadata_is_terminal() {
13239        const RETRY_AFTER: Duration = Duration::from_secs(60);
13240
13241        // No pending entry to restore, so the only way not to strand the key
13242        // in `in_flight_fetch` forever — which would also stall bootstrap
13243        // drain — is the terminal path.
13244        let mut q = ReplicationQueues::new();
13245        let key = test_key(0x3B);
13246        let source = test_peer(0x0A);
13247        assert!(q.enqueue_fetch(key, key, vec![source]));
13248        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13249        q.start_dequeued_fetch(candidate, source);
13250
13251        let follow_up =
13252            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13253
13254        assert_eq!(follow_up, FetchFollowUp::Terminal);
13255        assert!(!q.contains_key(&key));
13256        assert_eq!(q.retry_reserved_slot_count(), 0);
13257    }
13258}