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, ChunkStore};
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<ChunkStore>,
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<ChunkStore>,
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<ChunkStore>,
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 /// Neighbour-sync state, for the storage migration's possession challenges.
1992 #[must_use]
1993 pub fn sync_state(&self) -> &Arc<RwLock<NeighborSyncState>> {
1994 &self.sync_state
1995 }
1996
1997 /// The audit-challenge coordinator, for the storage migration's possession challenges.
1998 #[must_use]
1999 pub fn audit_challenge_coordinator(&self) -> &Arc<AuditChallengeCoordinator> {
2000 &self.audit_challenge_coordinator
2001 }
2002
2003 /// Replication settings, for the storage migration's possession challenges.
2004 #[must_use]
2005 pub fn config(&self) -> &Arc<ReplicationConfig> {
2006 &self.config
2007 }
2008
2009 /// Get a reference to the auditor's last-commitment-by-peer table.
2010 #[must_use]
2011 pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2012 &self.last_commitment_by_peer
2013 }
2014
2015 /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2016 /// will be read by quorum / paid-list eligibility checks.
2017 #[must_use]
2018 pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2019 &self.recent_provers
2020 }
2021
2022 /// Test-only: rebuild + rotate this node's storage commitment now over its
2023 /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2024 /// just stored without waiting for the rotation cadence.
2025 ///
2026 /// # Errors
2027 ///
2028 /// Propagates any error from reading the local key set or building/signing
2029 /// the commitment.
2030 #[cfg(any(test, feature = "test-utils"))]
2031 pub async fn rebuild_commitment_now(&self) -> Result<()> {
2032 rebuild_and_rotate_commitment(
2033 &self.storage,
2034 &self.identity,
2035 &self.commitment_state,
2036 &self.p2p_node,
2037 &self.config,
2038 )
2039 .await
2040 }
2041
2042 /// Test-only: directly seed this node's cached commitment for `peer`,
2043 /// simulating "we received `peer`'s gossiped commitment" without depending
2044 /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2045 /// peer's commitment deterministically.
2046 #[cfg(any(feature = "test-utils", test))]
2047 pub async fn inject_peer_commitment_for_test(
2048 &self,
2049 peer: &PeerId,
2050 commitment: StorageCommitment,
2051 ) {
2052 let now = Instant::now();
2053 self.last_commitment_by_peer
2054 .write()
2055 .await
2056 .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2057 self.ever_capable_peers.write().await.insert(*peer);
2058 }
2059
2060 /// Test-only: isolate a monetized first audit of `peer` from live gossip
2061 /// audits. Suppresses new gossip lottery attempts for the current cooldown
2062 /// window and clears any shared cooldown stamped by an earlier gossip
2063 /// launch. The locks follow the production gossip-audit lock order.
2064 #[cfg(any(test, feature = "test-utils"))]
2065 pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2066 let now = Instant::now();
2067 let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2068 let mut launched = self.audit_on_gossip_cooldown.write().await;
2069 lottery_attempts.insert(*peer, now);
2070 launched.remove(peer);
2071 }
2072
2073 /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2074 /// commitment this node has cached for it (from gossip), over the live wire.
2075 /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2076 /// in a real two-node setting without waiting for the gossip cadence.
2077 ///
2078 /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2079 /// peer yet (gossip hasn't reached us). Gated to test builds.
2080 #[cfg(any(test, feature = "test-utils"))]
2081 pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2082 let target = {
2083 let map = self.last_commitment_by_peer.read().await;
2084 map.get(peer)
2085 .and_then(PeerCommitmentRecord::last_commitment)
2086 .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2087 };
2088 let Some((pin, key_count)) = target else {
2089 return audit::AuditTickResult::Idle;
2090 };
2091 let credit = storage_commitment_audit::AuditCredit {
2092 recent_provers: &self.recent_provers,
2093 };
2094 storage_commitment_audit::run_subtree_audit(
2095 &self.p2p_node,
2096 &self.config,
2097 peer,
2098 pin,
2099 key_count,
2100 Some(&credit),
2101 )
2102 .await
2103 }
2104
2105 /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2106 /// tests assert what the live drainer decided for an injected
2107 /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2108 #[cfg(any(test, feature = "test-utils"))]
2109 #[must_use]
2110 pub fn first_audit_stats(&self) -> FirstAuditStats {
2111 let o = &self.first_audit_observability;
2112 FirstAuditStats {
2113 received: o.received.load(Ordering::Relaxed),
2114 queued: o.queued.load(Ordering::Relaxed),
2115 self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2116 launched: o.launched.load(Ordering::Relaxed),
2117 passed: o.passed.load(Ordering::Relaxed),
2118 timed_out: o.timed_out.load(Ordering::Relaxed),
2119 failed: o.failed.load(Ordering::Relaxed),
2120 }
2121 }
2122
2123 /// Test-only: run the possession check immediately for `key` against
2124 /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2125 ///
2126 /// Penalises any peer that does not hold `key` at `AuditChallenge`
2127 /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2128 /// deterministically without waiting for the scheduled check.
2129 #[cfg(any(test, feature = "test-utils"))]
2130 pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2131 possession::run_possession_check(
2132 key,
2133 peers,
2134 &self.p2p_node,
2135 &self.storage,
2136 &self.config,
2137 &self.sync_state,
2138 &self.audit_challenge_coordinator,
2139 &self.shutdown,
2140 )
2141 .await;
2142 }
2143
2144 /// Test-only: place `key` directly into the fetch queue as though a
2145 /// verification cycle had just promoted it, with `sources` as its
2146 /// verified holders. Returns whether the key was enqueued.
2147 ///
2148 /// Bypasses admission, verification, and the promotion-time
2149 /// responsibility pre-filter, modelling a promotion decision that has
2150 /// since gone stale (topology churn between promotion and download).
2151 /// The only guard left standing is the per-attempt recheck inside
2152 /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2153 /// exercise.
2154 #[cfg(any(test, feature = "test-utils"))]
2155 pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2156 let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2157 self.queues
2158 .write()
2159 .await
2160 .enqueue_fetch(key, distance, sources)
2161 }
2162
2163 /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2164 /// (pending verification, fetch queue, or in-flight fetch).
2165 #[cfg(any(test, feature = "test-utils"))]
2166 pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2167 self.queues.read().await.contains_key(key)
2168 }
2169
2170 /// Test-only: place `key` into pending verification as though `hinter` had
2171 /// just advertised it with a replica hint. Returns whether it was admitted.
2172 ///
2173 /// Enters the pipeline one stage earlier than
2174 /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2175 /// decides about the key is observable.
2176 #[cfg(any(test, feature = "test-utils"))]
2177 pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2178 let now = Instant::now();
2179 let entry = VerificationEntry {
2180 state: VerificationState::PendingVerify,
2181 verified_sources: Vec::new(),
2182 tried_sources: HashSet::new(),
2183 created_at: now,
2184 next_verify_at: now,
2185 hint_sources: HashSet::from([hinter]),
2186 replica_hint_sources: HashSet::from([hinter]),
2187 unresolved_retries: 0,
2188 no_holder_reported: false,
2189 };
2190 self.queues
2191 .write()
2192 .await
2193 .add_pending_verify(key, entry)
2194 .admitted()
2195 }
2196
2197 /// Test-only: how far ahead `key`'s next verification round is scheduled,
2198 /// or `None` when the key is not pending verification.
2199 #[cfg(any(test, feature = "test-utils"))]
2200 pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2201 self.queues.read().await.get_pending(key).map(|entry| {
2202 entry
2203 .next_verify_at
2204 .saturating_duration_since(Instant::now())
2205 })
2206 }
2207
2208 /// Start all background tasks.
2209 ///
2210 /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2211 /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2212 /// missed by the bootstrap-sync gate.
2213 pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2214 if !self.task_handles.is_empty() {
2215 error!("ReplicationEngine::start() called while already running — ignoring");
2216 return;
2217 }
2218 info!("Starting replication engine");
2219
2220 self.start_message_handler();
2221 self.start_neighbor_sync_loop();
2222 self.start_self_lookup_loop();
2223 // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2224 // chunks they SHOULD store (responsibility + prior hint).
2225 self.start_audit_loop();
2226 // Audit #1 (storage-commitment) is gossip-triggered in the message
2227 // handler when a peer's commitment is ingested, not on a periodic tick.
2228 self.start_commitment_rotation_loop();
2229 self.start_retention_persist_loop();
2230 self.start_fetch_worker();
2231 self.start_verification_worker();
2232 self.start_bootstrap_sync(dht_events);
2233 self.start_fresh_write_drainer();
2234 self.start_possession_check_scheduler();
2235 // ADR-0004: deterministic first audit of commitments that backed a
2236 // payment (surfaced by the verifier cross-check).
2237 self.start_first_audit_drainer();
2238 // V2-623: periodic cumulative per-variant traffic accounting.
2239 self.start_traffic_summary_loop();
2240 // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2241 #[cfg(feature = "logging")]
2242 self.start_bootstrap_state_snapshot_loop();
2243 #[cfg(feature = "logging")]
2244 self.start_audit_responder_summary_loop();
2245
2246 info!(
2247 "Replication engine started with {} background tasks",
2248 self.task_handles.len()
2249 );
2250 }
2251
2252 /// Returns `true` if the node is still in the replication bootstrap phase.
2253 ///
2254 /// During bootstrap, audit challenges return `Bootstrapping` instead of
2255 /// digests, and neighbor sync responses carry `bootstrapping: true`.
2256 pub async fn is_bootstrapping(&self) -> bool {
2257 *self.is_bootstrapping.read().await
2258 }
2259
2260 /// Wait until the replication bootstrap phase completes.
2261 ///
2262 /// Returns immediately if bootstrap has already completed. Useful for
2263 /// readiness probes, health checks, and test harnesses that need the
2264 /// node to be fully operational before proceeding.
2265 ///
2266 /// Returns `true` if bootstrap completed within the timeout, `false`
2267 /// if the timeout elapsed first.
2268 pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2269 // Register the notification future *before* checking the flag so that
2270 // a transition between the read and the await is not missed.
2271 let notified = self.bootstrap_complete_notify.notified();
2272 tokio::pin!(notified);
2273 notified.as_mut().enable();
2274
2275 if !*self.is_bootstrapping.read().await {
2276 return true;
2277 }
2278
2279 tokio::time::timeout(timeout, notified).await.is_ok()
2280 }
2281
2282 /// Cancel all background tasks and wait for them to terminate.
2283 ///
2284 /// This must be awaited before dropping the engine when the caller needs
2285 /// the `Arc<ChunkStore>` references held by background tasks to be
2286 /// released (e.g. before reopening the same LMDB environment).
2287 ///
2288 /// When this returns, no engine-spawned task still holds
2289 /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no LMDB blocking operation
2290 /// (read or write, on either the chunk store or the paid-list
2291 /// environment) is still running. Engine tasks race their work against
2292 /// the shutdown token; a dropped future may leave a `spawn_blocking`
2293 /// LMDB transaction running detached, so this method additionally waits
2294 /// for both storage layers to go quiescent before returning.
2295 pub async fn shutdown(&mut self) {
2296 self.shutdown.cancel();
2297 for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2298 match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2299 Ok(Ok(())) => {}
2300 Ok(Err(e)) if e.is_cancelled() => {}
2301 Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2302 Err(_) => {
2303 warn!(
2304 "Replication task {i} did not stop within {}s, aborting",
2305 SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2306 );
2307 handle.abort();
2308 // `abort` only requests cancellation. Await the handle so
2309 // synchronous sections finish and the task drops every
2310 // storage/P2P clone before we claim producer quiescence.
2311 match handle.await {
2312 Ok(()) => {}
2313 Err(e) if e.is_cancelled() => {}
2314 Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2315 }
2316 }
2317 }
2318 }
2319
2320 // Close the responder worker pools. Detached tasks still queued for a
2321 // worker take the `Err` arm of `acquire_owned()` and exit immediately
2322 // rather than waiting for a slot that will never free up — without
2323 // this, work admitted just before shutdown would queue behind the last
2324 // in-flight batch and hold the drain below open for its full duration.
2325 self.fresh_offer_worker_semaphore.close();
2326 self.paid_notify_worker_semaphore.close();
2327 self.fetch_responder_worker_semaphore.close();
2328 self.verification_responder_worker_semaphore.close();
2329 self.neighbor_sync_responder_worker_semaphore.close();
2330
2331 // All producers have stopped, so close and drain their detached work.
2332 // A started storage operation must run to completion: dropping an async
2333 // waiter does not cancel `spawn_blocking`, and would let shutdown return
2334 // while an LMDB transaction still owns the environment.
2335 //
2336 // Deliberately unbounded: the LMDB contract requires every worker to
2337 // release its `Arc<ChunkStore>` before the caller may reopen the
2338 // environment, and a timeout here could return with one still held.
2339 // What makes that safe is that every detached task is now guaranteed to
2340 // finish — the pools above are closed, stale work is shed at dequeue,
2341 // and the one genuinely unbounded await (payment verification) races
2342 // `self.shutdown` via `verify_payment_until_shutdown`.
2343 self.detached_task_tracker.close();
2344 self.detached_task_tracker.wait().await;
2345
2346 // Every producer is gone, but a select! racing the shutdown token may
2347 // have dropped a future while it awaited an LMDB `spawn_blocking` op
2348 // (fetch `storage.put`, prune `storage.delete` /
2349 // `paid_list.remove_batch`, verification `paid_list.insert`). The
2350 // detached blocking closure owns a cloned `Env`; wait for both
2351 // environments to go quiescent — bounded by one in-flight transaction
2352 // per op — so the caller may reopen them.
2353 self.storage.wait_idle().await;
2354 self.paid_list.wait_idle().await;
2355 }
2356
2357 /// Trigger an early neighbor sync round.
2358 ///
2359 /// Useful after topology changes (new nodes joining, network heal after
2360 /// partition) when the caller wants replication to converge faster than
2361 /// the regular 10-20 minute cadence.
2362 pub fn trigger_neighbor_sync(&self) {
2363 self.sync_trigger.notify_one();
2364 }
2365
2366 /// Execute fresh replication for a newly stored record, then schedule the
2367 /// delayed possession check for the responsible close-group peers
2368 /// (ADR-0003). The production PUT path schedules via the fresh-write
2369 /// drainer; this direct entry point schedules here so callers (and tests)
2370 /// that drive replication directly still get the possession check.
2371 pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2372 let peers = fresh::replicate_fresh(
2373 key,
2374 data,
2375 proof_of_payment,
2376 &self.p2p_node,
2377 &self.paid_list,
2378 &self.config,
2379 &self.send_semaphore,
2380 )
2381 .await;
2382 if !peers.is_empty() {
2383 let _ = self
2384 .possession_check_tx
2385 .send(possession::PossessionCheckEvent { key: *key, peers });
2386 }
2387 }
2388
2389 // =======================================================================
2390 // Background task launchers
2391 // =======================================================================
2392
2393 /// Spawn a task that drains the fresh-write channel and triggers
2394 /// replication for each newly-stored chunk.
2395 fn start_fresh_write_drainer(&mut self) {
2396 let Some(mut rx) = self.fresh_write_rx.take() else {
2397 return;
2398 };
2399 let p2p = Arc::clone(&self.p2p_node);
2400 let paid_list = Arc::clone(&self.paid_list);
2401 let config = Arc::clone(&self.config);
2402 let send_semaphore = Arc::clone(&self.send_semaphore);
2403 let possession_tx = self.possession_check_tx.clone();
2404 let shutdown = self.shutdown.clone();
2405
2406 let handle = tokio::spawn(async move {
2407 loop {
2408 tokio::select! {
2409 () = shutdown.cancelled() => break,
2410 event = rx.recv() => {
2411 let Some(event) = event else { break };
2412 let peers = fresh::replicate_fresh(
2413 &event.key,
2414 &event.data,
2415 &event.payment_proof,
2416 &p2p,
2417 &paid_list,
2418 &config,
2419 &send_semaphore,
2420 )
2421 .await;
2422 // Schedule the delayed possession check (ADR-0003) for
2423 // the responsible close-group peers. A closed receiver
2424 // (engine shutting down) is ignored.
2425 if !peers.is_empty() {
2426 let _ = possession_tx.send(possession::PossessionCheckEvent {
2427 key: event.key,
2428 peers,
2429 });
2430 }
2431 }
2432 }
2433 }
2434 debug!("Fresh-write drainer shut down");
2435 });
2436 self.task_handles.push(handle);
2437 }
2438
2439 /// Spawn the possession-check scheduler (ADR-0003).
2440 ///
2441 /// Drains scheduled possession-check events and, for each, waits a
2442 /// randomised 5-15 minute settle delay before probing every responsible
2443 /// peer for actual possession. A peer that fails to prove possession or does
2444 /// not answer is penalised at `AuditChallenge` severity.
2445 fn start_possession_check_scheduler(&mut self) {
2446 let Some(mut rx) = self.possession_check_rx.take() else {
2447 return;
2448 };
2449 let p2p = Arc::clone(&self.p2p_node);
2450 let storage = Arc::clone(&self.storage);
2451 let config = Arc::clone(&self.config);
2452 let sync_state = Arc::clone(&self.sync_state);
2453 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2454 let shutdown = self.shutdown.clone();
2455 let detached_task_tracker = self.detached_task_tracker.clone();
2456
2457 let handle = tokio::spawn(async move {
2458 loop {
2459 tokio::select! {
2460 () = shutdown.cancelled() => break,
2461 event = rx.recv() => {
2462 let Some(event) = event else { break };
2463 // Spawn a per-chunk delayed check so the drain loop
2464 // keeps pace with the write rate. Each check sleeps the
2465 // randomised settle delay, then probes every peer.
2466 let p2p = Arc::clone(&p2p);
2467 let storage = Arc::clone(&storage);
2468 let config = Arc::clone(&config);
2469 let sync_state = Arc::clone(&sync_state);
2470 let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2471 let shutdown = shutdown.clone();
2472 let delay_min = config.possession_check_delay_min;
2473 let delay_max = config.possession_check_delay_max;
2474 detached_task_tracker.spawn(async move {
2475 let delay = possession::random_delay(delay_min, delay_max);
2476 // Race shutdown against the whole settle-then-probe
2477 // sequence, not just the sleep. Once a check starts it
2478 // may park on the per-target audit coordinator, which
2479 // has no deadline of its own: with the settle delay
2480 // inside the branch BODY the select is already resolved,
2481 // so those waiters would drain only at the probe timeout
2482 // (roughly `queued / per-target-limit` probes deep) while
2483 // `detached_task_tracker.wait()` — deliberately unbounded
2484 // for the LMDB contract — held shutdown open.
2485 //
2486 // Dropping this future mid-probe is safe and is the same
2487 // shape the neighbor-sync round uses: a parked coordinator
2488 // acquire releases its counted reference via
2489 // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2490 // covered by the storage-quiescence wait in `shutdown`.
2491 tokio::select! {
2492 () = shutdown.cancelled() => {}
2493 () = async {
2494 tokio::time::sleep(delay).await;
2495 possession::run_possession_check(
2496 event.key,
2497 event.peers,
2498 &p2p,
2499 &storage,
2500 &config,
2501 &sync_state,
2502 &audit_challenge_coordinator,
2503 &shutdown,
2504 )
2505 .await;
2506 } => {}
2507 }
2508 });
2509 }
2510 }
2511 }
2512 debug!("Possession-check scheduler shut down");
2513 });
2514 self.task_handles.push(handle);
2515 }
2516
2517 /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2518 /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2519 /// as the gossip path, under the same per-peer cooldown and concurrency
2520 /// caps, but with the probability lottery BYPASSED (the lottery governs
2521 /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2522 /// deterministic first audit; a peer minting fresh pins faster than the
2523 /// cooldown forfeits the older ones' coverage, never the newest's (the
2524 /// channel surfaces newest pins as they are monetized).
2525 #[allow(clippy::too_many_lines)]
2526 fn start_first_audit_drainer(&mut self) {
2527 let Some(mut rx) = self.monetized_pin_rx.take() else {
2528 return;
2529 };
2530 let gossip_audit = GossipAuditTrigger {
2531 p2p_node: Arc::clone(&self.p2p_node),
2532 config: Arc::clone(&self.config),
2533 recent_provers: Arc::clone(&self.recent_provers),
2534 sync_state: Arc::clone(&self.sync_state),
2535 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2536 detached_task_tracker: self.detached_task_tracker.clone(),
2537 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2538 };
2539 let shutdown = self.shutdown.clone();
2540 let observability = Arc::clone(&self.first_audit_observability);
2541 let self_peer = *self.p2p_node.peer_id();
2542
2543 let handle = tokio::spawn(async move {
2544 // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2545 // scheduler. Payments only NOMINATE pins; the token bucket launches
2546 // them at a fixed per-node rate, and durable suppression is stamped
2547 // only at PROMOTION (after an authoritative post-jitter answerability
2548 // + cooldown check), so a cancelled reservation leaves nothing behind.
2549 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2550 // Periodic retry tick so budget/cooldown-deferred pins get retried
2551 // even when no new nomination arrives. `Skip` collapses a backlog.
2552 let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2553 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2554 let mut last_summary = Instant::now();
2555 loop {
2556 // The reservation's jitter deadline is a wake source: if a
2557 // reservation is outstanding, sleep until it is due; otherwise
2558 // a far-future deadline effectively disables that arm and only
2559 // shutdown/rx/tick wake the loop. Recreated each iteration so a
2560 // newly reserved (earlier) deadline is honoured next turn.
2561 let promotion_due = scheduler
2562 .reserved_ready_at()
2563 .unwrap_or_else(first_audit_far_future);
2564 tokio::select! {
2565 () = shutdown.cancelled() => break,
2566 event = rx.recv() => match event {
2567 Some(e) => {
2568 observability.received.fetch_add(1, Ordering::Relaxed);
2569 // Pre-overflow reservation opportunity: before an
2570 // arrival may displace a DIFFERENT peer, let the
2571 // queue launch — a successful reservation frees the
2572 // slot without eviction. One reservation can be
2573 // outstanding at a time, so this consumes at most
2574 // one slot per jitter window; arrivals beyond it
2575 // fall through to random displacement (ADR-0004
2576 // Amendment 4).
2577 if scheduler.would_displace(&e) {
2578 open_first_audit_reservation(
2579 &mut scheduler,
2580 &gossip_audit.cooldown,
2581 &observability,
2582 )
2583 .await;
2584 }
2585 scheduler.enqueue(e, &observability);
2586 // Drain a bounded burst so a flood cannot starve the
2587 // launch phase.
2588 let mut drained = 1usize;
2589 while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2590 match rx.try_recv() {
2591 Ok(e) => {
2592 observability.received.fetch_add(1, Ordering::Relaxed);
2593 if scheduler.would_displace(&e) {
2594 open_first_audit_reservation(
2595 &mut scheduler,
2596 &gossip_audit.cooldown,
2597 &observability,
2598 )
2599 .await;
2600 }
2601 scheduler.enqueue(e, &observability);
2602 drained += 1;
2603 }
2604 Err(_) => break,
2605 }
2606 }
2607 }
2608 None => break,
2609 },
2610 _ = tick.tick() => {}
2611 () = tokio::time::sleep_until(promotion_due.into()) => {}
2612 }
2613
2614 // 1) Promote a due reservation. Resolved after EVERY wake (not
2615 // only when the timer arm wins) so a continuously-ready `rx`
2616 // cannot indefinitely delay a due promotion. The authoritative
2617 // answerability + cooldown check-and-stamp happens here under
2618 // the shared cooldown write lock, immediately before the send.
2619 if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2620 let promoted = {
2621 let mut cooldown = gossip_audit.cooldown.write().await;
2622 scheduler.resolve(
2623 reservation,
2624 SystemTime::now(),
2625 Instant::now(),
2626 &mut cooldown,
2627 &observability,
2628 )
2629 };
2630 if let Some((event, inflight_slot)) = promoted {
2631 debug!(
2632 "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2633 event.peer, hex::encode(event.pin), event.key_count,
2634 observability.inflight.load(Ordering::Relaxed)
2635 );
2636 let trigger = gossip_audit.clone();
2637 let audit_observability = Arc::clone(&observability);
2638 // Track the launch so `shutdown()`'s detached drain
2639 // covers it. This task outlives the drainer loop that
2640 // spawned it — the loop breaks on the shutdown token
2641 // while the audit is still awaiting its response — so a
2642 // bare spawn would let an in-flight subtree audit keep
2643 // running, and keep its `Arc<P2PNode>`, past the point
2644 // `shutdown()` claims every engine task has stopped.
2645 let tracker = trigger.detached_task_tracker.clone();
2646 tracker.spawn(async move {
2647 // The jitter already elapsed as the reservation's
2648 // timer; the slot is held for the audit's duration
2649 // and released on drop (panic-safe).
2650 let inflight_slot = inflight_slot;
2651 let started = Instant::now();
2652 let credit = storage_commitment_audit::AuditCredit {
2653 recent_provers: &trigger.recent_provers,
2654 };
2655 let result = storage_commitment_audit::run_subtree_audit(
2656 &trigger.p2p_node,
2657 &trigger.config,
2658 &event.peer,
2659 event.pin,
2660 event.key_count,
2661 Some(&credit),
2662 )
2663 .await;
2664 let outcome = first_audit_terminal_outcome(&result);
2665 match outcome {
2666 FirstAuditTerminalOutcome::Passed => {
2667 audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2668 }
2669 FirstAuditTerminalOutcome::Timeout => {
2670 audit_observability
2671 .timed_out
2672 .fetch_add(1, Ordering::Relaxed);
2673 }
2674 FirstAuditTerminalOutcome::Failed => {
2675 audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2676 }
2677 FirstAuditTerminalOutcome::BootstrapClaim => {
2678 audit_observability
2679 .bootstrap_claims
2680 .fetch_add(1, Ordering::Relaxed);
2681 }
2682 FirstAuditTerminalOutcome::Idle => {
2683 audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2684 }
2685 FirstAuditTerminalOutcome::InsufficientKeys => {
2686 audit_observability
2687 .insufficient_keys
2688 .fetch_add(1, Ordering::Relaxed);
2689 }
2690 }
2691 drop(inflight_slot);
2692 debug!(
2693 "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2694 outcome.as_str(),
2695 event.peer, hex::encode(event.pin), event.key_count,
2696 started.elapsed().as_millis(),
2697 audit_observability.inflight.load(Ordering::Relaxed)
2698 );
2699 handle_subtree_audit_result(
2700 &result,
2701 &trigger.p2p_node,
2702 &trigger.sync_state,
2703 &trigger.recent_provers,
2704 &trigger.config,
2705 )
2706 .await;
2707 });
2708 }
2709 }
2710
2711 // 2) Open the single reservation from the pending queue if none
2712 // is outstanding (read-only cooldown snapshot; the
2713 // authoritative stamp is at promotion). Serializing
2714 // reservations preserves per-launch lane alternation and keeps
2715 // at most one jitter timer live.
2716 open_first_audit_reservation(
2717 &mut scheduler,
2718 &gossip_audit.cooldown,
2719 &observability,
2720 )
2721 .await;
2722
2723 if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2724 // Token-independent hygiene: collect entries that aged past
2725 // the answerability horizon while the budget gate kept the
2726 // reserve scan from running, so the summary below reports
2727 // only live work.
2728 let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2729 if swept > 0 {
2730 debug!(
2731 "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2732 scheduler.pending_len()
2733 );
2734 }
2735 info!(
2736 "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={}",
2737 FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2738 observability.received.load(Ordering::Relaxed),
2739 observability.queued.load(Ordering::Relaxed),
2740 observability.coalesced.load(Ordering::Relaxed),
2741 observability.suppressed_lower.load(Ordering::Relaxed),
2742 observability.duplicates.load(Ordering::Relaxed),
2743 observability.capacity_evicted.load(Ordering::Relaxed),
2744 observability.self_target_skipped.load(Ordering::Relaxed),
2745 observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2746 observability.rate_deferred_attempts.load(Ordering::Relaxed),
2747 observability.window_deduped.load(Ordering::Relaxed),
2748 observability.launched.load(Ordering::Relaxed),
2749 observability.passed.load(Ordering::Relaxed),
2750 observability.timed_out.load(Ordering::Relaxed),
2751 observability.failed.load(Ordering::Relaxed),
2752 observability.bootstrap_claims.load(Ordering::Relaxed),
2753 observability.idle.load(Ordering::Relaxed),
2754 observability.insufficient_keys.load(Ordering::Relaxed),
2755 observability.outside_answerability_window.load(Ordering::Relaxed),
2756 scheduler.pending_len(),
2757 FIRST_AUDIT_PENDING_CAP,
2758 u8::from(scheduler.has_reservation()),
2759 scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2760 observability.inflight.load(Ordering::Relaxed),
2761 scheduler.tokens(),
2762 );
2763 last_summary = Instant::now();
2764 }
2765 }
2766 debug!("First-audit drainer shut down");
2767 });
2768 self.task_handles.push(handle);
2769 }
2770
2771 #[allow(clippy::too_many_lines)]
2772 fn start_message_handler(&mut self) {
2773 let mut p2p_events = self.p2p_node.subscribe_events();
2774 let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2775 let p2p = Arc::clone(&self.p2p_node);
2776 let storage = Arc::clone(&self.storage);
2777 let paid_list = Arc::clone(&self.paid_list);
2778 let payment_verifier = Arc::clone(&self.payment_verifier);
2779 let queues = Arc::clone(&self.queues);
2780 let config = Arc::clone(&self.config);
2781 let shutdown = self.shutdown.clone();
2782 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2783 let bootstrap_state = Arc::clone(&self.bootstrap_state);
2784 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2785 let sync_history = Arc::clone(&self.sync_history);
2786 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2787 let repair_proofs = Arc::clone(&self.repair_proofs);
2788 let sync_trigger = Arc::clone(&self.sync_trigger);
2789 let my_commitment_state = Arc::clone(&self.commitment_state);
2790 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2791 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2792 let recent_provers = Arc::clone(&self.recent_provers);
2793 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2794 let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2795 let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2796 let sync_state = Arc::clone(&self.sync_state);
2797 let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2798 let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2799 let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2800 let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2801 let fetch_responder_admission_semaphore =
2802 Arc::clone(&self.fetch_responder_admission_semaphore);
2803 let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2804 let verification_responder_worker_semaphore =
2805 Arc::clone(&self.verification_responder_worker_semaphore);
2806 let verification_responder_admission_semaphore =
2807 Arc::clone(&self.verification_responder_admission_semaphore);
2808 let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2809 let neighbor_sync_responder_worker_semaphore =
2810 Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2811 let neighbor_sync_responder_admission_semaphore =
2812 Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2813 let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2814 let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2815 let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2816 let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2817 let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2818 let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2819 let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2820 let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2821 let detached_task_tracker = self.detached_task_tracker.clone();
2822 let subtree_round1 = self.subtree_round1.clone();
2823
2824 // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2825 // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2826 let gossip_audit = GossipAuditTrigger {
2827 p2p_node: Arc::clone(&p2p),
2828 config: Arc::clone(&config),
2829 recent_provers: Arc::clone(&recent_provers),
2830 sync_state: Arc::clone(&sync_state),
2831 cooldown: Arc::clone(&audit_on_gossip_cooldown),
2832 detached_task_tracker: detached_task_tracker.clone(),
2833 lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2834 };
2835
2836 let handler_context = ReplicationMessageHandlerContext {
2837 p2p_node: Arc::clone(&p2p),
2838 storage,
2839 paid_list,
2840 payment_verifier,
2841 queues,
2842 config: Arc::clone(&config),
2843 is_bootstrapping,
2844 bootstrap_state,
2845 sync_history,
2846 sync_cycle_epoch,
2847 repair_proofs: Arc::clone(&repair_proofs),
2848 last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2849 ever_capable_peers,
2850 sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2851 my_commitment_state,
2852 gossip_audit,
2853 audit_responder_semaphore,
2854 audit_responder_inflight,
2855 audit_responder_metrics,
2856 subtree_round1,
2857 fetch_responder_worker_semaphore,
2858 fetch_responder_admission_semaphore,
2859 fetch_responder_inflight,
2860 verification_responder_worker_semaphore,
2861 verification_responder_admission_semaphore,
2862 verification_responder_inflight,
2863 neighbor_sync_responder_worker_semaphore,
2864 neighbor_sync_responder_admission_semaphore,
2865 neighbor_sync_responder_inflight,
2866 fresh_offer_worker_semaphore,
2867 fresh_offer_admission_semaphore,
2868 fresh_offer_responder_inflight,
2869 fresh_offer_in_flight,
2870 paid_notify_worker_semaphore,
2871 paid_notify_admission_semaphore,
2872 paid_notify_responder_inflight,
2873 shutdown: shutdown.clone(),
2874 detached_task_tracker,
2875 };
2876
2877 let (replication_tx, mut replication_rx) =
2878 mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2879 let serial_context = handler_context.clone();
2880 let serial_shutdown = shutdown.clone();
2881 let serial_handle = tokio::spawn(async move {
2882 loop {
2883 tokio::select! {
2884 () = serial_shutdown.cancelled() => break,
2885 inbound = replication_rx.recv() => {
2886 let Some(inbound) = inbound else { break };
2887 let source = inbound.source;
2888 match handle_replication_message(
2889 &source,
2890 inbound.msg,
2891 &serial_context,
2892 inbound.received_at,
2893 inbound.rr_message_id.as_deref(),
2894 )
2895 .await
2896 {
2897 Ok(()) => {}
2898 Err(e) => {
2899 debug!("Replication message from {source} error: {e}");
2900 }
2901 }
2902 }
2903 }
2904 }
2905 debug!("Replication non-audit serial handler shut down");
2906 });
2907 self.task_handles.push(serial_handle);
2908
2909 let handle = tokio::spawn(async move {
2910 loop {
2911 tokio::select! {
2912 () = shutdown.cancelled() => break,
2913 event = p2p_events.recv() => {
2914 let event = match event {
2915 Ok(event) => event,
2916 Err(error) => match handle_replication_event_recv_error(&error) {
2917 ControlFlow::Continue(()) => continue,
2918 ControlFlow::Break(()) => break,
2919 },
2920 };
2921 let Some((source, payload, inbound_protocol, rr_message_id)) =
2922 replication_payload_from_event(event)
2923 else {
2924 continue;
2925 };
2926 let received_at = Instant::now();
2927 let msg = match ReplicationMessage::decode(&payload) {
2928 Ok(msg) => msg,
2929 Err(e) => {
2930 debug!("Replication message from {source} decode error: {e}");
2931 continue;
2932 }
2933 };
2934 if !body_matches_protocol(&msg.body, inbound_protocol) {
2935 debug!(
2936 "Dropping replication body (variant {}) on protocol \
2937 {inbound_protocol}: wrong id for its family \
2938 (cross-version or misrouted)",
2939 msg.body.variant_index()
2940 );
2941 continue;
2942 }
2943 if let Some(class) = audit_responder_class(&msg.body) {
2944 handler_context
2945 .audit_responder_metrics
2946 .record_received(source, class);
2947 }
2948 let inbound = InboundReplicationMessage {
2949 source,
2950 msg,
2951 rr_message_id,
2952 received_at,
2953 };
2954 if matches!(
2955 inbound.msg.body,
2956 ReplicationMessageBody::AuditChallenge(_)
2957 | ReplicationMessageBody::SubtreeAuditChallenge(_)
2958 | ReplicationMessageBody::SubtreeSliceChallenge(_)
2959 ) {
2960 let source = inbound.source;
2961 match handle_replication_message(
2962 &source,
2963 inbound.msg,
2964 &handler_context,
2965 inbound.received_at,
2966 inbound.rr_message_id.as_deref(),
2967 )
2968 .await
2969 {
2970 Ok(()) => {}
2971 Err(e) => {
2972 debug!("Replication message from {source} error: {e}");
2973 }
2974 }
2975 continue;
2976 }
2977 if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
2978 if dropped.audit_responder_class.is_some() {
2979 handler_context
2980 .audit_responder_metrics
2981 .record_serial_queue_drop(dropped.source);
2982 }
2983 // Every serial-lane class has protocol recovery: syncs rerun,
2984 // fetches retry, verification re-asks, and a dropped fresh
2985 // offer is refilled by neighbor sync (the possession check
2986 // penalises the absence but never re-offers). Responses are
2987 // covered by their requester's deadline/retry path. Never run
2988 // a bulk handler here: event receipt must remain non-blocking.
2989 warn!(
2990 message_class = dropped.message_class,
2991 source = %dropped.source,
2992 queue_depth = dropped.queue_depth,
2993 reason = dropped.reason.as_str(),
2994 "Replication serial-queue message dropped"
2995 );
2996 }
2997 }
2998 // Gap 4: Topology churn handling (Section 13).
2999 //
3000 // The DHT routing table emits KClosestPeersChanged when the
3001 // K-closest peer set actually changes, which is the precise
3002 // signal for triggering neighbor sync. This replaces the
3003 // previous approach of checking every PeerConnected /
3004 // PeerDisconnected event against the close group.
3005 dht_event = dht_events.recv() => {
3006 let dht_event = match dht_event {
3007 Ok(event) => event,
3008 Err(RecvError::Lagged(missed)) => {
3009 // Under heavy churn the broadcast buffer can overflow
3010 // and drop routing-table events — the moment
3011 // convergence matters most. A dropped
3012 // KClosestPeersChanged means its entrants were never
3013 // queued and its departures were never pruned, so
3014 // draining priority_order cannot recover either.
3015 // Resync from ground truth instead: snapshot the
3016 // current close-peer set, prune pending peers that
3017 // left it during the lost window (retain_sync_peers,
3018 // as the normal topology-change path does), and queue
3019 // every member. Dedup (queue_priority_peers) and
3020 // per-peer cooldown (select_next_sync_peer) drop peers
3021 // already queued or recently synced, so only genuine
3022 // entrants surface.
3023 warn!(
3024 "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3025 );
3026 let self_id = *p2p.peer_id();
3027 let neighbors = neighbor_sync::snapshot_close_neighbors(
3028 &p2p,
3029 &self_id,
3030 config.neighbor_sync_scope,
3031 )
3032 .await;
3033 let neighbor_set =
3034 neighbors.iter().copied().collect::<HashSet<_>>();
3035 let (requeued, sync_removals) = {
3036 let mut state = sync_state.write().await;
3037 let sync_removals =
3038 state.retain_sync_peers(&neighbor_set);
3039 let requeued = state.queue_priority_peers(neighbors);
3040 (requeued, sync_removals)
3041 };
3042 if sync_removals > 0 {
3043 debug!(
3044 "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3045 );
3046 }
3047 if requeued > 0 {
3048 debug!(
3049 "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3050 );
3051 sync_trigger.notify_one();
3052 }
3053 continue;
3054 }
3055 Err(RecvError::Closed) => {
3056 // A closed broadcast channel never yields again;
3057 // continuing would spin the select! loop forever.
3058 warn!(
3059 "DHT event stream closed on replication branch; stopping message handler"
3060 );
3061 break;
3062 }
3063 };
3064 match dht_event {
3065 DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3066 let old_peers = old
3067 .iter()
3068 .take(config.neighbor_sync_scope)
3069 .copied()
3070 .collect::<HashSet<_>>();
3071 let new_scoped = new
3072 .iter()
3073 .take(config.neighbor_sync_scope)
3074 .copied()
3075 .collect::<Vec<_>>();
3076 let new_peers =
3077 new_scoped.iter().copied().collect::<HashSet<_>>();
3078 let entrants = new_scoped
3079 .iter()
3080 .copied()
3081 .filter(|peer| !old_peers.contains(peer))
3082 .collect::<Vec<_>>();
3083 let entrant_count = entrants.len();
3084 let (priority_insertions, sync_removals) = {
3085 let mut state = sync_state.write().await;
3086 let sync_removals = state.retain_sync_peers(&new_peers);
3087 let priority_insertions = state.queue_priority_peers(entrants);
3088 (priority_insertions, sync_removals)
3089 };
3090 if priority_insertions > 0 {
3091 debug!(
3092 "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3093 );
3094 } else {
3095 debug!(
3096 "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3097 );
3098 }
3099 sync_trigger.notify_one();
3100 }
3101 DhtNetworkEvent::PeerRemoved { peer_id } => {
3102 sync_state.write().await.remove_peer(&peer_id);
3103 repair_proofs.write().await.remove_peer(&peer_id);
3104 update_bootstrap_after_peer_removed(
3105 &peer_id,
3106 &handler_context.bootstrap_state,
3107 &handler_context.queues,
3108 &handler_context.is_bootstrapping,
3109 &bootstrap_complete_notify,
3110 )
3111 .await;
3112 // v12: drop the commitment bytes and the
3113 // recent-prover credit so a churn / sybil
3114 // attacker cannot leave behind one
3115 // StorageCommitment per identity in
3116 // `last_commitment_by_peer`. Also drop the
3117 // sig-verify rate-limit timestamp.
3118 last_commitment_by_peer.write().await.remove(&peer_id);
3119 recent_provers.write().await.forget_peer(&peer_id);
3120 sig_verify_attempts.write().await.remove(&peer_id);
3121 // Same for the gossip-audit cooldown (ADR-0002)
3122 // and the lottery-attempt window.
3123 audit_on_gossip_cooldown.write().await.remove(&peer_id);
3124 gossip_lottery_attempts.write().await.remove(&peer_id);
3125 // The sticky `commitment_capable` flag is
3126 // preserved orthogonally via
3127 // `ever_capable_peers` — even after this
3128 // removal, a re-joining peer continues to
3129 // be treated as v12-capable rather than
3130 // legacy (§3 shield).
3131 }
3132 _ => {}
3133 }
3134 }
3135 }
3136 }
3137 debug!("Replication message handler shut down");
3138 });
3139 self.task_handles.push(handle);
3140 }
3141
3142 fn start_neighbor_sync_loop(&mut self) {
3143 let p2p = Arc::clone(&self.p2p_node);
3144 let storage = Arc::clone(&self.storage);
3145 let paid_list = Arc::clone(&self.paid_list);
3146 let queues = Arc::clone(&self.queues);
3147 let config = Arc::clone(&self.config);
3148 let shutdown = self.shutdown.clone();
3149 let sync_state = Arc::clone(&self.sync_state);
3150 let sync_history = Arc::clone(&self.sync_history);
3151 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3152 let repair_proofs = Arc::clone(&self.repair_proofs);
3153 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3154 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3155 let sync_trigger = Arc::clone(&self.sync_trigger);
3156 let commitment_state = Arc::clone(&self.commitment_state);
3157 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3158 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3159 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3160 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3161 let detached_task_tracker = self.detached_task_tracker.clone();
3162 // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3163 // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3164 // here too so a peer that only ever answers — never initiates sync —
3165 // is still audited; otherwise it could fully evade auditing.
3166 let gossip_audit = GossipAuditTrigger {
3167 p2p_node: Arc::clone(&p2p),
3168 config: Arc::clone(&config),
3169 recent_provers: Arc::clone(&self.recent_provers),
3170 sync_state: Arc::clone(&sync_state),
3171 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3172 detached_task_tracker,
3173 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3174 };
3175
3176 let handle = tokio::spawn(async move {
3177 loop {
3178 // Park for the periodic tick or an explicit trigger ONLY when no
3179 // priority (topology-change) peers are queued. `sync_trigger` is a
3180 // coalescing `Notify`, so a churn burst that queues many entrants
3181 // produces a single wakeup; parking after draining one batch would
3182 // leave the rest waiting up to a full periodic tick. `priority_order`
3183 // is the durable record of pending work, so drain it back-to-back —
3184 // each round removes the peers it selects (`select_next_sync_peer`),
3185 // so the drain terminates once the queue empties.
3186 if !sync_state.read().await.has_priority_peers() {
3187 let interval = config.random_neighbor_sync_interval();
3188 tokio::select! {
3189 () = shutdown.cancelled() => break,
3190 () = tokio::time::sleep(interval) => {}
3191 () = sync_trigger.notified() => {
3192 debug!("Neighbor sync triggered by topology change");
3193 }
3194 }
3195 }
3196 // Wrap the sync round in a select so shutdown cancels
3197 // in-progress network operations rather than waiting for
3198 // the full round to complete.
3199 tokio::select! {
3200 () = shutdown.cancelled() => break,
3201 () = run_neighbor_sync_round(
3202 &p2p,
3203 &storage,
3204 &paid_list,
3205 &queues,
3206 &config,
3207 &sync_state,
3208 &sync_history,
3209 &sync_cycle_epoch,
3210 &repair_proofs,
3211 &is_bootstrapping,
3212 &bootstrap_state,
3213 &commitment_state,
3214 &last_commitment_by_peer,
3215 &ever_capable_peers,
3216 &sig_verify_attempts,
3217 &audit_challenge_coordinator,
3218 &gossip_audit,
3219 ) => {}
3220 }
3221 }
3222 debug!("Neighbor sync loop shut down");
3223 });
3224 self.task_handles.push(handle);
3225 }
3226
3227 fn start_self_lookup_loop(&mut self) {
3228 let p2p = Arc::clone(&self.p2p_node);
3229 let config = Arc::clone(&self.config);
3230 let shutdown = self.shutdown.clone();
3231
3232 let handle = tokio::spawn(async move {
3233 loop {
3234 let interval = config.random_self_lookup_interval();
3235 tokio::select! {
3236 () = shutdown.cancelled() => break,
3237 () = tokio::time::sleep(interval) => {
3238 if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3239 debug!("Self-lookup failed: {e}");
3240 }
3241 }
3242 }
3243 }
3244 debug!("Self-lookup loop shut down");
3245 });
3246 self.task_handles.push(handle);
3247 }
3248
3249 /// Periodic responsible-chunk audit loop (audit #2): every
3250 /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3251 /// eligible close peer for the chunks it *should* be storing (by
3252 /// responsibility and prior repair hint), independent of the gossip-triggered
3253 /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3254 /// immediately and periodically thereafter.
3255 fn start_audit_loop(&mut self) {
3256 let p2p = Arc::clone(&self.p2p_node);
3257 let storage = Arc::clone(&self.storage);
3258 let config = Arc::clone(&self.config);
3259 let shutdown = self.shutdown.clone();
3260 let sync_history = Arc::clone(&self.sync_history);
3261 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3262 let repair_proofs = Arc::clone(&self.repair_proofs);
3263 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3264 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3265 let sync_state = Arc::clone(&self.sync_state);
3266 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3267
3268 let handle = tokio::spawn(async move {
3269 // Invariant 19: wait for bootstrap to drain before starting audits.
3270 loop {
3271 tokio::select! {
3272 () = shutdown.cancelled() => return,
3273 () = tokio::time::sleep(
3274 std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3275 ) => {
3276 if bootstrap_state.read().await.is_drained() {
3277 break;
3278 }
3279 }
3280 }
3281 }
3282
3283 // Run one audit tick immediately after bootstrap drain.
3284 {
3285 let bootstrapping = *is_bootstrapping.read().await;
3286 let result = {
3287 let history = sync_history.read().await;
3288 let current_sync_epoch = *sync_cycle_epoch.read().await;
3289 audit::audit_tick_with_repair_proofs(
3290 &p2p,
3291 &storage,
3292 &config,
3293 &history,
3294 &repair_proofs,
3295 &audit_challenge_coordinator,
3296 current_sync_epoch,
3297 bootstrapping,
3298 )
3299 .await
3300 };
3301 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3302 }
3303
3304 // Then run periodically.
3305 loop {
3306 let interval = config.random_audit_tick_interval();
3307 tokio::select! {
3308 () = shutdown.cancelled() => break,
3309 () = tokio::time::sleep(interval) => {
3310 let bootstrapping = *is_bootstrapping.read().await;
3311 let result = {
3312 let history = sync_history.read().await;
3313 let current_sync_epoch = *sync_cycle_epoch.read().await;
3314 audit::audit_tick_with_repair_proofs(
3315 &p2p,
3316 &storage,
3317 &config,
3318 &history,
3319 &repair_proofs,
3320 &audit_challenge_coordinator,
3321 current_sync_epoch,
3322 bootstrapping,
3323 )
3324 .await
3325 };
3326 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3327 }
3328 }
3329 }
3330 debug!("Audit loop shut down");
3331 });
3332 self.task_handles.push(handle);
3333 }
3334
3335 /// Periodically rebuild + sign + rotate the responder's storage
3336 /// commitment.
3337 ///
3338 /// Phase 3 of the v12 storage-bound audit. Once per
3339 /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3340 /// current LMDB key set, builds a Merkle tree (for content-addressed
3341 /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3342 /// the root with the node's `MlDsaSecretKey`, and rotates the result
3343 /// into `commitment_state`. Old `previous` slot is dropped by the
3344 /// rotate (per `ResponderCommitmentState::rotate`).
3345 ///
3346 /// Skips if the key set is empty (no commitment to make) — the
3347 /// auditor side falls back to the legacy plain-digest path for
3348 /// peers that have never gossiped a commitment.
3349 fn start_commitment_rotation_loop(&mut self) {
3350 let storage = Arc::clone(&self.storage);
3351 let identity = Arc::clone(&self.identity);
3352 let commitment_state = Arc::clone(&self.commitment_state);
3353 let shutdown = self.shutdown.clone();
3354 let p2p = Arc::clone(&self.p2p_node);
3355 let config = Arc::clone(&self.config);
3356 let sync_trigger = Arc::clone(&self.sync_trigger);
3357 let recent_provers = Arc::clone(&self.recent_provers);
3358
3359 let handle = tokio::spawn(async move {
3360 // Build the first commitment immediately on startup so a
3361 // restarted node can answer commitment-bound audits right
3362 // away — otherwise current() stays None for a full rotation
3363 // interval and audits silently fall back to legacy.
3364 //
3365 // After the first build, trigger an immediate neighbor-sync
3366 // round so the new commitment gossips out within seconds.
3367 // Without this, after a restart remote auditors keep pinning
3368 // the pre-restart (rotated-away) hash until their normal
3369 // sync cadence elapses — up to 1 h in the worst case,
3370 // during which time commitment-bound audits hit "unknown
3371 // commitment hash" -> Idle no-ops.
3372 // ML-DSA signatures are randomized so we cannot reproduce
3373 // the pre-restart hash; the only honest path to recovery
3374 // is fast re-gossip.
3375 // ADR-0004 A1: retention was reloaded in `new()` (before any task
3376 // spawned), so this initial rebuild no-ops when the key set is
3377 // unchanged — preserving the reloaded current pin; otherwise the
3378 // reloaded roots stay answerable as retained slots until their gossip
3379 // TTL lapses. Persistence is handled by the retention-persist loop.
3380 if let Err(e) =
3381 rebuild_and_rotate_commitment(&storage, &identity, &commitment_state, &p2p, &config)
3382 .await
3383 {
3384 warn!("Initial commitment build failed: {e}");
3385 } else {
3386 sync_trigger.notify_one();
3387 }
3388 loop {
3389 tokio::select! {
3390 () = shutdown.cancelled() => break,
3391 () = tokio::time::sleep(
3392 std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3393 ) => {
3394 if let Err(e) = rebuild_and_rotate_commitment(
3395 &storage,
3396 &identity,
3397 &commitment_state,
3398 &p2p,
3399 &config,
3400 ).await {
3401 warn!("Commitment rotation failed: {e}");
3402 }
3403 // Piggyback a sweep of expired recent_provers
3404 // entries on the rotation tick (same cadence,
3405 // 1 h). is_credited_holder already honours the
3406 // TTL on read, but the sweep reclaims memory
3407 // for entries we'll never re-read.
3408 let dropped = recent_provers.write().await.sweep_expired(
3409 std::time::Instant::now()
3410 );
3411 if dropped > 0 {
3412 debug!("recent_provers: swept {dropped} expired entries");
3413 }
3414 }
3415 }
3416 }
3417 debug!("Commitment rotation loop shut down");
3418 });
3419 self.task_handles.push(handle);
3420 }
3421
3422 /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3423 /// (write-on-change) so answerability — including gossip-stamp refreshes and
3424 /// rotations — survives a restart. Flushes once immediately, then every
3425 /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3426 fn start_retention_persist_loop(&mut self) {
3427 let commitment_state = Arc::clone(&self.commitment_state);
3428 let retention_path = self.retention_path.clone();
3429 let shutdown = self.shutdown.clone();
3430 let handle = tokio::spawn(async move {
3431 let mut last: Option<Vec<u8>> = None;
3432 persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3433 loop {
3434 tokio::select! {
3435 () = shutdown.cancelled() => {
3436 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3437 .await;
3438 break;
3439 }
3440 () = tokio::time::sleep(std::time::Duration::from_secs(
3441 RETENTION_PERSIST_INTERVAL_SECS,
3442 )) => {
3443 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3444 .await;
3445 }
3446 }
3447 }
3448 debug!("Commitment retention persist loop shut down");
3449 });
3450 self.task_handles.push(handle);
3451 }
3452
3453 /// Periodically emit the cumulative replication traffic summaries: the
3454 /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3455 /// (V2-684). Both read process-global counter tables maintained by the
3456 /// encode/decode and serve choke points in [`protocol`]; needs no engine
3457 /// state.
3458 fn start_traffic_summary_loop(&mut self) {
3459 let shutdown = self.shutdown.clone();
3460 let handle = tokio::spawn(async move {
3461 loop {
3462 tokio::select! {
3463 () = shutdown.cancelled() => break,
3464 () = tokio::time::sleep(std::time::Duration::from_secs(
3465 TRAFFIC_SUMMARY_INTERVAL_SECS,
3466 )) => {
3467 protocol::log_traffic_summary();
3468 protocol::log_served_peers_summary();
3469 protocol::log_audit_outcome_summary();
3470 audit_metrics::log_responder_admission_summary();
3471 }
3472 }
3473 }
3474 debug!("Replication traffic summary loop shut down");
3475 });
3476 self.task_handles.push(handle);
3477 }
3478
3479 /// Periodically expose the state that gates bootstrap completion and prune
3480 /// admission. The state counts are copied before reading `is_bootstrapping`
3481 /// so this diagnostic path never nests async locks.
3482 #[cfg(feature = "logging")]
3483 fn start_bootstrap_state_snapshot_loop(&mut self) {
3484 let shutdown = self.shutdown.clone();
3485 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3486 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3487 let started_at = Instant::now();
3488 let handle = tokio::spawn(async move {
3489 loop {
3490 tokio::select! {
3491 () = shutdown.cancelled() => break,
3492 () = tokio::time::sleep(Duration::from_secs(
3493 BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3494 )) => {
3495 let (
3496 drained,
3497 pending_peer_requests,
3498 pending_keys,
3499 capacity_rejected_sources,
3500 ) = {
3501 let state = bootstrap_state.read().await;
3502 (
3503 state.drained,
3504 state.pending_peer_requests,
3505 state.pending_keys.len(),
3506 state.capacity_rejected_sources.len(),
3507 )
3508 };
3509 let bootstrapping = *is_bootstrapping.read().await;
3510 let snapshot_state = if drained && !bootstrapping {
3511 "healthy"
3512 } else if drained {
3513 "drained_waiting_for_bootstrap_flag"
3514 } else {
3515 "pending"
3516 };
3517 info!(
3518 drained,
3519 pending_peer_requests,
3520 pending_keys,
3521 capacity_rejected_sources,
3522 is_bootstrapping = bootstrapping,
3523 snapshot_state,
3524 uptime_secs = started_at.elapsed().as_secs(),
3525 "Replication bootstrap state snapshot"
3526 );
3527 if drained && !bootstrapping {
3528 info!(
3529 "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3530 );
3531 break;
3532 }
3533 }
3534 }
3535 }
3536 debug!("Bootstrap state snapshot loop shut down");
3537 });
3538 self.task_handles.push(handle);
3539 }
3540
3541 /// Periodically rank remote peers using the shared audit responder pool and
3542 /// report handler-only versus end-to-end latency. Windowed values make a
3543 /// burst visible even after a long-running node has accumulated traffic.
3544 #[cfg(feature = "logging")]
3545 fn start_audit_responder_summary_loop(&mut self) {
3546 let shutdown = self.shutdown.clone();
3547 let metrics = Arc::clone(&self.audit_responder_metrics);
3548 let semaphore = Arc::clone(&self.audit_responder_semaphore);
3549 let handle = tokio::spawn(async move {
3550 let mut window_started = Instant::now();
3551 loop {
3552 tokio::select! {
3553 () = shutdown.cancelled() => {
3554 log_audit_responder_summary(
3555 &metrics,
3556 &semaphore,
3557 window_started.elapsed(),
3558 );
3559 break;
3560 }
3561 () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3562 log_audit_responder_summary(
3563 &metrics,
3564 &semaphore,
3565 window_started.elapsed(),
3566 );
3567 window_started = Instant::now();
3568 }
3569 }
3570 }
3571 debug!("Audit responder summary loop shut down");
3572 });
3573 self.task_handles.push(handle);
3574 }
3575
3576 #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3577 fn start_fetch_worker(&mut self) {
3578 let p2p = Arc::clone(&self.p2p_node);
3579 let storage = Arc::clone(&self.storage);
3580 let queues = Arc::clone(&self.queues);
3581 let config = Arc::clone(&self.config);
3582 let shutdown = self.shutdown.clone();
3583 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3584 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3585 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3586 let detached_task_tracker = self.detached_task_tracker.clone();
3587 let concurrency = max_parallel_fetch();
3588
3589 info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3590
3591 let handle = tokio::spawn(async move {
3592 // Each in-flight future yields (key, Option<FetchOutcome>) so we
3593 // always recover the key — even if the inner task panics.
3594 let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3595
3596 loop {
3597 // Fill up to `concurrency` slots from the queue.
3598 {
3599 let mut q = queues.write().await;
3600 while in_flight.len() < concurrency {
3601 let Some(candidate) = q.dequeue_fetch() else {
3602 break;
3603 };
3604 let fetch_key = candidate.key;
3605 let Some(&source) = candidate.sources.first() else {
3606 warn!(
3607 "Fetch candidate {} has no sources; requeueing for verification",
3608 hex::encode(fetch_key)
3609 );
3610 let _ = q.requeue_candidate_for_verification(
3611 candidate,
3612 config.verification_request_timeout,
3613 );
3614 continue;
3615 };
3616 q.start_dequeued_fetch(candidate, source);
3617
3618 let p2p = Arc::clone(&p2p);
3619 let storage = Arc::clone(&storage);
3620 let config = Arc::clone(&config);
3621 let token = shutdown.clone();
3622 let tracker = detached_task_tracker.clone();
3623 in_flight.push(Box::pin(async move {
3624 // Tracked so shutdown() still awaits the task if
3625 // this awaiter is dropped (e.g. the worker is
3626 // aborted): it holds Arc<ChunkStore> and must
3627 // not outlive the engine.
3628 let handle = tracker.spawn(async move {
3629 // Cancel-aware: abort when the engine shuts down.
3630 tokio::select! {
3631 () = token.cancelled() => FetchOutcome {
3632 key: fetch_key,
3633 result: FetchResult::SourceFailed,
3634 },
3635 outcome = execute_single_fetch(
3636 p2p, storage, config, fetch_key, source,
3637 ) => outcome,
3638 }
3639 });
3640 match handle.await {
3641 Ok(outcome) => (outcome.key, Some(outcome)),
3642 Err(e) => {
3643 error!(
3644 "Fetch task for {} panicked: {e}",
3645 hex::encode(fetch_key)
3646 );
3647 (fetch_key, None)
3648 }
3649 }
3650 }));
3651 }
3652 } // release queues write lock
3653
3654 if in_flight.is_empty() {
3655 // No work — wait for new items or shutdown.
3656 tokio::select! {
3657 () = shutdown.cancelled() => break,
3658 () = tokio::time::sleep(
3659 std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3660 ) => continue,
3661 }
3662 }
3663
3664 // Wait for the next fetch to complete and process the result.
3665 tokio::select! {
3666 () = shutdown.cancelled() => break,
3667 Some((key, maybe_outcome)) = in_flight.next() => {
3668 let mut q = queues.write().await;
3669 let terminal = if let Some(outcome) = maybe_outcome {
3670 match apply_fetch_result(
3671 &mut q,
3672 &key,
3673 &outcome.result,
3674 config.verification_request_timeout,
3675 ) {
3676 FetchFollowUp::Terminal => true,
3677 FetchFollowUp::RequeuedForVerification => false,
3678 FetchFollowUp::RetryFrom(next_peer) => {
3679 // Spawn a new fetch task for the next source.
3680 let p2p = Arc::clone(&p2p);
3681 let storage = Arc::clone(&storage);
3682 let config = Arc::clone(&config);
3683 let token = shutdown.clone();
3684 let tracker = detached_task_tracker.clone();
3685 let fetch_key = key;
3686 in_flight.push(Box::pin(async move {
3687 // Tracked for the same reason as the
3688 // initial fetch spawn above.
3689 let handle = tracker.spawn(async move {
3690 tokio::select! {
3691 () = token.cancelled() => FetchOutcome {
3692 key: fetch_key,
3693 result: FetchResult::SourceFailed,
3694 },
3695 outcome = execute_single_fetch(
3696 p2p, storage, config, fetch_key, next_peer,
3697 ) => outcome,
3698 }
3699 });
3700 match handle.await {
3701 Ok(outcome) => (outcome.key, Some(outcome)),
3702 Err(e) => {
3703 error!(
3704 "Fetch task for {} panicked: {e}",
3705 hex::encode(fetch_key)
3706 );
3707 (fetch_key, None)
3708 }
3709 }
3710 }));
3711 false
3712 }
3713 }
3714 } else {
3715 // Task panicked — retry verification when this was
3716 // a verified repair, otherwise reclaim the slot.
3717 !q.requeue_fetch_for_verification(
3718 &key,
3719 config.verification_request_timeout,
3720 )
3721 };
3722
3723 // Shrink bootstrap pending set on terminal exit.
3724 if terminal {
3725 drop(q); // release queues lock before acquiring bootstrap_state
3726 if !bootstrap_state.read().await.is_drained() {
3727 bootstrap_state.write().await.remove_key(&key);
3728 let q = queues.read().await;
3729 if bootstrap::check_bootstrap_drained(
3730 &bootstrap_state,
3731 &q,
3732 )
3733 .await
3734 {
3735 complete_bootstrap(
3736 &is_bootstrapping,
3737 &bootstrap_complete_notify,
3738 ).await;
3739 }
3740 }
3741 }
3742 }
3743 }
3744 }
3745
3746 // Cancel and drain remaining in-flight fetches on shutdown.
3747 // The CancellationToken is already cancelled by this point, so
3748 // spawned tasks will see cancellation via their select! branches.
3749 while in_flight.next().await.is_some() {}
3750 debug!("Fetch worker shut down");
3751 });
3752 self.task_handles.push(handle);
3753 }
3754
3755 fn start_verification_worker(&mut self) {
3756 let p2p = Arc::clone(&self.p2p_node);
3757 let storage = Arc::clone(&self.storage);
3758 let queues = Arc::clone(&self.queues);
3759 let paid_list = Arc::clone(&self.paid_list);
3760 let config = Arc::clone(&self.config);
3761 let shutdown = self.shutdown.clone();
3762 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3763 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3764 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3765 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3766 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3767 let recent_provers = Arc::clone(&self.recent_provers);
3768
3769 let handle = tokio::spawn(async move {
3770 loop {
3771 tokio::select! {
3772 () = shutdown.cancelled() => break,
3773 () = tokio::time::sleep(
3774 std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3775 ) => {
3776 let ctx = VerificationCycleContext {
3777 p2p_node: &p2p,
3778 paid_list: &paid_list,
3779 storage: &storage,
3780 queues: &queues,
3781 config: &config,
3782 bootstrap_state: &bootstrap_state,
3783 is_bootstrapping: &is_bootstrapping,
3784 bootstrap_complete_notify: &bootstrap_complete_notify,
3785 last_commitment_by_peer: &last_commitment_by_peer,
3786 ever_capable_peers: &ever_capable_peers,
3787 recent_provers: &recent_provers,
3788 };
3789 run_verification_cycle(ctx).await;
3790 }
3791 }
3792 }
3793 debug!("Verification worker shut down");
3794 });
3795 self.task_handles.push(handle);
3796 }
3797
3798 /// Gap 3: Run a one-shot bootstrap sync on startup.
3799 ///
3800 /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3801 /// (indicating the routing table is populated) before snapshotting
3802 /// close neighbors. Falls back after a timeout so bootstrap nodes
3803 /// (which have no peers and therefore never receive the event) still
3804 /// proceed.
3805 ///
3806 /// After the gate, finds close neighbors, syncs with each in
3807 /// round-robin batches, admits returned hints into the verification
3808 /// pipeline, and tracks discovered keys for bootstrap drain detection.
3809 #[allow(clippy::too_many_lines)]
3810 fn start_bootstrap_sync(
3811 &mut self,
3812 dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3813 ) {
3814 let p2p = Arc::clone(&self.p2p_node);
3815 let storage = Arc::clone(&self.storage);
3816 let paid_list = Arc::clone(&self.paid_list);
3817 let queues = Arc::clone(&self.queues);
3818 let config = Arc::clone(&self.config);
3819 let shutdown = self.shutdown.clone();
3820 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3821 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3822 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3823 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3824 let repair_proofs = Arc::clone(&self.repair_proofs);
3825 let my_commitment_state = Arc::clone(&self.commitment_state);
3826 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3827 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3828 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3829
3830 let handle = tokio::spawn(async move {
3831 // Wait for DHT bootstrap to complete before snapshotting
3832 // neighbors. The routing table is empty until saorsa-core
3833 // finishes its FIND_NODE rounds and bucket refreshes.
3834 let gate = bootstrap::wait_for_bootstrap_complete(
3835 dht_events,
3836 config.bootstrap_complete_timeout_secs,
3837 &shutdown,
3838 )
3839 .await;
3840
3841 if gate == bootstrap::BootstrapGateResult::Shutdown {
3842 return;
3843 }
3844
3845 let self_id = *p2p.peer_id();
3846 let neighbors =
3847 neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3848 .await;
3849
3850 if neighbors.is_empty() {
3851 info!("Bootstrap sync: no close neighbors found, marking drained");
3852 bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3853 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3854 return;
3855 }
3856
3857 let neighbor_count = neighbors.len();
3858 info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3859
3860 // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3861 for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3862 if shutdown.is_cancelled() {
3863 break;
3864 }
3865
3866 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3867 batch,
3868 &storage,
3869 &paid_list,
3870 &p2p,
3871 config.close_group_size,
3872 config.paid_list_close_group_size,
3873 )
3874 .await;
3875
3876 // Keep the batch outstanding until every response has been
3877 // admitted and bootstrap accounting is updated. The verification
3878 // worker uses this counter as a batch barrier, so it cannot race
3879 // the source aggregation below.
3880 bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3881 let bootstrapping = *is_bootstrapping.read().await;
3882
3883 let sync_futures = batch.iter().map(|peer| {
3884 let peer = *peer;
3885 let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3886 // Atomically snapshot + mark-gossiped for each emitted
3887 // bootstrap request so we remain answerable for it.
3888 let commitment = my_commitment_state
3889 .current_for_gossip()
3890 .map(|binding| binding.commitment().clone());
3891 let p2p = &p2p;
3892 let config = &config;
3893 async move {
3894 let outcome = neighbor_sync::sync_with_peer_with_hints(
3895 &peer,
3896 p2p,
3897 config,
3898 bootstrapping,
3899 hints,
3900 commitment,
3901 )
3902 .await;
3903 (peer, outcome)
3904 }
3905 });
3906 let completed = join_all(sync_futures).await;
3907
3908 // Process response metadata before exposing any of this batch's
3909 // hints to verification.
3910 for (peer, outcome) in &completed {
3911 if let Some(outcome) = outcome {
3912 // Ingest the peer's piggybacked commitment from the
3913 // response (same verification as the request path).
3914 // Bootstrap is the FIRST gossip we receive from most
3915 // peers, so this populates last_commitment_by_peer.
3916 //
3917 // We intentionally do NOT trigger a gossip-audit here:
3918 // during bootstrap this node may itself still be
3919 // bootstrapping (audits are gated on that), and the
3920 // close-group/RT view is not yet stable. The peer is
3921 // audited on the first STEADY-STATE neighbor-sync round
3922 // after bootstrap drains (request + response paths both
3923 // trigger), which is within one sync cycle — so caching
3924 // the commitment here is sufficient and there is no
3925 // coverage gap (ADR-0002).
3926 ingest_peer_commitment(
3927 peer,
3928 outcome.response.commitment.as_ref(),
3929 &p2p,
3930 &last_commitment_by_peer,
3931 &ever_capable_peers,
3932 &sig_verify_attempts,
3933 )
3934 .await; // sig_verify_attempts in scope from line ~1080
3935
3936 if !outcome.response.bootstrapping {
3937 record_sent_replica_hints(
3938 peer,
3939 &outcome.sent_replica_hints,
3940 &repair_proofs,
3941 &sync_cycle_epoch,
3942 )
3943 .await;
3944 }
3945 }
3946 }
3947
3948 let pending_keys: HashSet<XorName> = {
3949 let q = queues.read().await;
3950 q.pending_keys().into_iter().collect()
3951 };
3952 let admission_futures = completed.iter().map(|(_, outcome)| async {
3953 match outcome {
3954 Some(outcome) if !outcome.response.bootstrapping => Some(
3955 admission::admit_hints(
3956 &self_id,
3957 &outcome.response.replica_hints,
3958 &outcome.response.paid_hints,
3959 &p2p,
3960 &config,
3961 &storage,
3962 &paid_list,
3963 &pending_keys,
3964 )
3965 .await,
3966 ),
3967 _ => None,
3968 }
3969 });
3970 let admitted = join_all(admission_futures).await;
3971
3972 // Queue every peer's admitted hints under one write lock. Once
3973 // released, source-count ordering sees the complete batch.
3974 let (batch_outcomes, batch_discovered) = {
3975 let mut q = queues.write().await;
3976 let outcomes = completed
3977 .iter()
3978 .zip(admitted)
3979 .filter_map(|((peer, _), admitted)| {
3980 admitted.map(|admitted| {
3981 (
3982 *peer,
3983 queue_admitted_hints(peer, admitted, &storage, &mut q),
3984 )
3985 })
3986 })
3987 .collect::<Vec<_>>();
3988 let live_discovered = outcomes
3989 .iter()
3990 .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
3991 .filter(|key| q.contains_key(key))
3992 .collect::<HashSet<_>>();
3993 (outcomes, live_discovered)
3994 };
3995
3996 publish_bootstrap_admission_outcomes(
3997 &bootstrap_state,
3998 &batch_outcomes,
3999 &batch_discovered,
4000 )
4001 .await;
4002
4003 bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4004 }
4005
4006 // Check drain condition.
4007 {
4008 let q = queues.read().await;
4009 if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4010 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4011 }
4012 }
4013
4014 info!("Bootstrap sync completed");
4015 });
4016 self.task_handles.push(handle);
4017 }
4018}
4019
4020// ===========================================================================
4021// Free functions for background tasks
4022// ===========================================================================
4023
4024#[cfg(feature = "logging")]
4025fn log_audit_responder_summary(
4026 metrics: &AuditResponderMetrics,
4027 semaphore: &Semaphore,
4028 window: Duration,
4029) {
4030 let snapshot = metrics.take_snapshot();
4031 if snapshot.origins.is_empty() {
4032 return;
4033 }
4034
4035 let total = snapshot.total;
4036 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4037 total.received_by_class;
4038 let global_inflight =
4039 MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4040 info!(
4041 target: "ant_node::replication::audit_responder",
4042 window_ms = window.as_millis(),
4043 source_count = snapshot.origins.len(),
4044 received = total.received(),
4045 digest_received,
4046 subtree_received,
4047 byte_received,
4048 commitment_pin_received,
4049 admitted = total.admitted,
4050 global_pool_drops = total.global_pool_drops,
4051 per_peer_cap_drops = total.per_peer_cap_drops,
4052 serial_queue_drops = total.serial_queue_drops,
4053 completed = total.completed,
4054 send_failures = total.send_failures,
4055 processing_avg_ms = total.processing_avg_ms(),
4056 processing_max_ms = total.processing_max_ms,
4057 total_avg_ms = total.total_avg_ms(),
4058 total_max_ms = total.total_max_ms,
4059 global_inflight,
4060 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4061 peak_global_inflight = total.peak_global_inflight,
4062 "Audit responder summary"
4063 );
4064
4065 for (index, origin) in snapshot
4066 .origins
4067 .iter()
4068 .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4069 .enumerate()
4070 {
4071 let Some(source) = origin.source else {
4072 continue;
4073 };
4074 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4075 origin.received_by_class;
4076 info!(
4077 target: "ant_node::replication::audit_responder",
4078 rank = index + 1,
4079 source = %source,
4080 received = origin.received(),
4081 digest_received,
4082 subtree_received,
4083 byte_received,
4084 commitment_pin_received,
4085 admitted = origin.admitted,
4086 global_pool_drops = origin.global_pool_drops,
4087 per_peer_cap_drops = origin.per_peer_cap_drops,
4088 serial_queue_drops = origin.serial_queue_drops,
4089 completed = origin.completed,
4090 send_failures = origin.send_failures,
4091 processing_avg_ms = origin.processing_avg_ms(),
4092 processing_max_ms = origin.processing_max_ms,
4093 total_avg_ms = origin.total_avg_ms(),
4094 total_max_ms = origin.total_max_ms,
4095 peak_global_inflight = origin.peak_global_inflight,
4096 peak_peer_inflight = origin.peak_peer_inflight,
4097 "Audit responder top origin"
4098 );
4099 }
4100}
4101
4102/// Which ceiling rejected an audit-responder admission attempt.
4103///
4104/// Stable, machine-readable so a production log-scrape can bucket drops by
4105/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4106/// single opaque "capacity reached" line; this splits the two distinct causes
4107/// so the next such investigation can tell a global-pool exhaustion (the whole
4108/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4109/// without re-instrumenting.
4110///
4111/// This branch runs a SINGLE shared audit-responder pool for all challenge
4112/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4113/// pool to distinguish here — the `kind=` log field already separates the
4114/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4115/// dedicated slow pool is later split out, add its variants here.
4116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4117enum ResponderRejectReason {
4118 /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4119 /// free; the per-peer cap was not the binding constraint.
4120 GlobalPoolFull,
4121 /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4122 /// share, so the global permit was never attempted.
4123 PerPeerCapFull,
4124}
4125
4126impl ResponderRejectReason {
4127 /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4128 /// frozen — production log tooling greps for them.
4129 fn as_str(self) -> &'static str {
4130 match self {
4131 Self::GlobalPoolFull => "global_pool_full",
4132 Self::PerPeerCapFull => "per_peer_cap_full",
4133 }
4134 }
4135}
4136
4137impl From<ResponderRejectReason> for AuditResponderDropReason {
4138 fn from(reason: ResponderRejectReason) -> Self {
4139 match reason {
4140 ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4141 ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4142 }
4143 }
4144}
4145
4146impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4147 fn from(reason: ResponderRejectReason) -> Self {
4148 match reason {
4149 ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4150 ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4151 }
4152 }
4153}
4154
4155/// Cumulative fresh-offer admission refusals in this process.
4156///
4157/// **Expected value in healthy operation is zero.** A node that refuses a
4158/// legitimate fresh offer does not merely shed load: the sender transmits
4159/// offers one-way and never reads the refusal, so the chunk's absence
4160/// resurfaces at the sender's delayed possession check and is charged to the
4161/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4162/// means the node is either under-provisioned for its offered load or its
4163/// admission share is mis-sized — and is accruing unearned trust damage either
4164/// way. Operators should alarm on any sustained non-zero rate.
4165///
4166/// Process-global rather than per-engine, which is exactly right in production
4167/// (one node per process) and adequate in multi-node test harnesses, where the
4168/// useful assertion is that *no* node in the fleet refused.
4169#[must_use]
4170pub fn fresh_offer_admission_refusals() -> u64 {
4171 audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4172}
4173
4174/// Cumulative paid-list notification admission refusals in this process.
4175///
4176/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4177/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4178/// paid-list evidence outright rather than pushing work back onto a requester.
4179#[must_use]
4180pub fn paid_notify_admission_refusals() -> u64 {
4181 audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4182}
4183
4184/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4185///
4186/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4187/// different things: this one says the node was saturated across all sources
4188/// and is genuinely under-provisioned for its offered load.
4189#[must_use]
4190pub fn fresh_offer_refusals_global_pool() -> u64 {
4191 audit_metrics::responder_admission_drops_by_ceiling(
4192 ReplicationResponderClass::FreshOffer,
4193 ResponderAdmissionCeiling::GlobalPool,
4194 )
4195}
4196
4197/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4198///
4199/// For fresh offers this usually indicts the *share's size* rather than the
4200/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4201/// node handling a client's PUT and fanning it out — so a share sized for
4202/// request/response traffic will refuse ordinary uploads.
4203#[must_use]
4204pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4205 audit_metrics::responder_admission_drops_by_ceiling(
4206 ReplicationResponderClass::FreshOffer,
4207 ResponderAdmissionCeiling::PerPeerShare,
4208 )
4209}
4210
4211/// Why an audit-responder admission attempt failed, with the decision-time
4212/// capacity counters that let a drop be logged with full context.
4213///
4214/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4215/// decision was made (the two ceilings are read under different locks, so they
4216/// are not a single atomic view), but they are exact enough to tell a saturated
4217/// node from a single self-throttling flooder.
4218#[derive(Debug, Clone, Copy)]
4219struct ResponderAdmissionFailure {
4220 reason: ResponderRejectReason,
4221 /// Global permits in use across the whole engine at decision time.
4222 global_inflight: usize,
4223 /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4224 global_limit: usize,
4225 /// In-flight audit responders already held for `source` at decision time.
4226 peer_inflight: u32,
4227 /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4228 peer_limit: u32,
4229}
4230
4231impl fmt::Display for ResponderAdmissionFailure {
4232 /// Renders the stable `reason=... global_inflight=... global_limit=...
4233 /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4235 write!(
4236 f,
4237 "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4238 self.reason.as_str(),
4239 self.global_inflight,
4240 self.global_limit,
4241 self.peer_inflight,
4242 self.peer_limit,
4243 )
4244 }
4245}
4246
4247/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4248/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4249/// spawned task ties both bounds to the task's exact lifetime — no manual
4250/// decrement to forget on an early return or panic.
4251struct ResponderGuard {
4252 _permit: tokio::sync::OwnedSemaphorePermit,
4253 _peer_slot: PeerResponderSlot,
4254 global_inflight: usize,
4255 peer_inflight: u32,
4256}
4257
4258type AuditResponderGuard = ResponderGuard;
4259type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4260
4261/// Provisional or admitted per-peer responder slot.
4262///
4263/// The slot is claimed before the global permit is attempted. Keeping that
4264/// claim under RAII means cancellation while rolling a failed admission back
4265/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4266/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4267struct PeerResponderSlot {
4268 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4269 peer: PeerId,
4270}
4271
4272#[derive(Clone)]
4273struct ReplicationMessageHandlerContext {
4274 p2p_node: Arc<P2PNode>,
4275 storage: Arc<ChunkStore>,
4276 paid_list: Arc<PaidList>,
4277 payment_verifier: Arc<PaymentVerifier>,
4278 queues: Arc<RwLock<ReplicationQueues>>,
4279 config: Arc<ReplicationConfig>,
4280 is_bootstrapping: Arc<RwLock<bool>>,
4281 bootstrap_state: Arc<RwLock<BootstrapState>>,
4282 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4283 sync_cycle_epoch: Arc<RwLock<u64>>,
4284 repair_proofs: Arc<RwLock<RepairProofs>>,
4285 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4286 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4287 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4288 my_commitment_state: Arc<ResponderCommitmentState>,
4289 gossip_audit: GossipAuditTrigger,
4290 audit_responder_semaphore: Arc<Semaphore>,
4291 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4292 audit_responder_metrics: Arc<AuditResponderMetrics>,
4293 subtree_round1: SubtreeRound1Limiter,
4294 fetch_responder_worker_semaphore: Arc<Semaphore>,
4295 fetch_responder_admission_semaphore: Arc<Semaphore>,
4296 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4297 verification_responder_worker_semaphore: Arc<Semaphore>,
4298 verification_responder_admission_semaphore: Arc<Semaphore>,
4299 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4300 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4301 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4302 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4303 fresh_offer_worker_semaphore: Arc<Semaphore>,
4304 fresh_offer_admission_semaphore: Arc<Semaphore>,
4305 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4306 fresh_offer_in_flight: FreshOfferInFlight,
4307 paid_notify_worker_semaphore: Arc<Semaphore>,
4308 paid_notify_admission_semaphore: Arc<Semaphore>,
4309 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4310 /// The engine's shutdown token, for detached responder work.
4311 ///
4312 /// Workers on [`Self::detached_task_tracker`] race this around their
4313 /// *network* phase only — never around an LMDB `spawn_blocking` await,
4314 /// where dropping the awaiter would detach a live transaction. This is
4315 /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4316 /// terminate: the wait stays safe because it is now guaranteed finite.
4317 shutdown: CancellationToken,
4318 /// Shared tracker for detached work so `shutdown()` can await release of
4319 /// storage and P2P resources after all producer tasks have stopped.
4320 detached_task_tracker: TaskTracker,
4321}
4322
4323struct InboundReplicationMessage {
4324 source: PeerId,
4325 msg: ReplicationMessage,
4326 rr_message_id: Option<String>,
4327 received_at: Instant,
4328}
4329
4330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4331enum SerialQueueDropReason {
4332 Full,
4333 Closed,
4334}
4335
4336#[cfg(feature = "logging")]
4337impl SerialQueueDropReason {
4338 const fn as_str(self) -> &'static str {
4339 match self {
4340 Self::Full => "full",
4341 Self::Closed => "closed",
4342 }
4343 }
4344}
4345
4346#[derive(Debug, Clone, Copy)]
4347#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4348struct SerialQueueDrop {
4349 source: PeerId,
4350 message_class: &'static str,
4351 audit_responder_class: Option<AuditResponderClass>,
4352 queue_depth: usize,
4353 reason: SerialQueueDropReason,
4354}
4355
4356fn try_enqueue_serial_message(
4357 sender: &mpsc::Sender<InboundReplicationMessage>,
4358 inbound: InboundReplicationMessage,
4359) -> std::result::Result<(), SerialQueueDrop> {
4360 let source = inbound.source;
4361 let message_class = replication_message_class(&inbound.msg.body);
4362 let audit_responder_class = audit_responder_class(&inbound.msg.body);
4363 let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4364 sender.try_send(inbound).map_err(|error| {
4365 let (reason, dropped) = match error {
4366 mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4367 mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4368 };
4369 audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4370 SerialQueueDrop {
4371 source,
4372 message_class,
4373 audit_responder_class,
4374 queue_depth,
4375 reason,
4376 }
4377 })
4378}
4379
4380const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4381 match body {
4382 ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4383 ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4384 ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4385 ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4386 ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4387 ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4388 ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4389 ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4390 ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4391 ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4392 ReplicationMessageBody::AuditResponse(_) => "audit_response",
4393 ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4394 ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4395 ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4396 ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4397 ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4398 ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4399 }
4400}
4401
4402const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4403 match body {
4404 ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4405 ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4406 ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4407 ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4408 _ => None,
4409 }
4410}
4411
4412impl AuditResponderClass {
4413 const fn per_peer_limit(self) -> u32 {
4414 match self {
4415 Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4416 Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4417 }
4418 }
4419}
4420
4421fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4422 match error {
4423 RecvError::Lagged(missed) => {
4424 audit_metrics::record_replication_event_lagged(*missed);
4425 warn!(
4426 "Missed {missed} P2P events on replication branch (broadcast lag); \
4427 replication messages may have been dropped before dispatch"
4428 );
4429 ControlFlow::Continue(())
4430 }
4431 RecvError::Closed => {
4432 // A closed broadcast channel never yields again, so the branch
4433 // would otherwise be immediately ready on every select! iteration.
4434 warn!("P2P event stream closed on replication branch; stopping message handler");
4435 ControlFlow::Break(())
4436 }
4437 }
4438}
4439
4440fn replication_payload_from_event(
4441 event: P2PEvent,
4442) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4443 let P2PEvent::Message {
4444 topic,
4445 source: Some(source),
4446 data,
4447 ..
4448 } = event
4449 else {
4450 return None;
4451 };
4452
4453 let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4454 if !is_rr {
4455 return Some((source, data, matched_id, None));
4456 }
4457 if is_rr {
4458 return P2PNode::parse_request_envelope(&data)
4459 .filter(|(_, is_resp, _)| !is_resp)
4460 .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4461 }
4462 None
4463}
4464
4465impl Drop for PeerResponderSlot {
4466 fn drop(&mut self) {
4467 // Decrement (and prune to keep the map bounded) without blocking the
4468 // async runtime: a short lock on a tiny map.
4469 //
4470 // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4471 // with no spawn. Otherwise defer to a task — but only if a runtime is
4472 // actually current, so `Drop` during shutdown (no runtime) can never
4473 // panic. A missed decrement at shutdown is harmless: the whole map is
4474 // being dropped with the engine.
4475 let peer = self.peer;
4476 if let Ok(mut map) = self.inflight.try_write() {
4477 if let Some(n) = map.get_mut(&peer) {
4478 *n = n.saturating_sub(1);
4479 if *n == 0 {
4480 map.remove(&peer);
4481 }
4482 }
4483 return;
4484 }
4485 if let Ok(handle) = tokio::runtime::Handle::try_current() {
4486 let inflight = Arc::clone(&self.inflight);
4487 handle.spawn(async move {
4488 let mut map = inflight.write().await;
4489 if let Some(n) = map.get_mut(&peer) {
4490 *n = n.saturating_sub(1);
4491 if *n == 0 {
4492 map.remove(&peer);
4493 }
4494 }
4495 });
4496 }
4497 }
4498}
4499
4500/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4501/// and then a global permit. The limits are parameters so independent responder
4502/// classes can reuse the same flood-fair admission and cancellation semantics.
4503async fn admit_bounded_responder(
4504 semaphore: &Arc<Semaphore>,
4505 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4506 source: &PeerId,
4507 global_limit: usize,
4508 peer_limit: u32,
4509) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4510 let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4511
4512 let admitted_peer_inflight = {
4513 let mut map = inflight.write().await;
4514 let entry = map.entry(*source).or_insert(0);
4515 if *entry >= peer_limit {
4516 let peer_inflight = *entry;
4517 drop(map);
4518 return Err(ResponderAdmissionFailure {
4519 reason: ResponderRejectReason::PerPeerCapFull,
4520 global_inflight: global_inflight(semaphore),
4521 global_limit,
4522 peer_inflight,
4523 peer_limit,
4524 });
4525 }
4526 *entry += 1;
4527 *entry
4528 };
4529
4530 let peer_slot = PeerResponderSlot {
4531 inflight: Arc::clone(inflight),
4532 peer: *source,
4533 };
4534 let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4535 return Err(ResponderAdmissionFailure {
4536 reason: ResponderRejectReason::GlobalPoolFull,
4537 global_inflight: global_inflight(semaphore),
4538 global_limit,
4539 peer_inflight: admitted_peer_inflight.saturating_sub(1),
4540 peer_limit,
4541 });
4542 };
4543
4544 Ok(ResponderGuard {
4545 _permit: permit,
4546 _peer_slot: peer_slot,
4547 global_inflight: global_inflight(semaphore),
4548 peer_inflight: admitted_peer_inflight,
4549 })
4550}
4551
4552/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4553struct SubtreeSession {
4554 commitment_hash: [u8; 32],
4555 nonce: [u8; 32],
4556 inserted: Instant,
4557}
4558
4559/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4560/// read and hash, refilled continuously at
4561/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4562/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4563///
4564/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4565/// identity may ask, so it is refilled by acquiring more identities; this is
4566/// charged for work done regardless of who asked, so it is not.
4567///
4568/// Charged after the fact, with the bytes the proof actually covered: the cost
4569/// of a request is not known until the pinned commitment has been resolved and
4570/// its subtree selected, both of which happen inside the handler. Admission
4571/// therefore asks only whether the balance is positive, and a proof that costs
4572/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4573/// Carrying the debt is what makes the bound real: without it a maximal proof
4574/// would cost the same as a trivial one, since either way the next request only
4575/// has to wait for the balance to climb back above zero. With it, sustained
4576/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4577/// admitted proportionally less often.
4578struct Round1WorkBudget {
4579 /// Signed, so an over-large proof leaves debt to work off.
4580 balance: i64,
4581 last_refill: Instant,
4582}
4583
4584impl Round1WorkBudget {
4585 /// Deepest debt carried, so one huge proof cannot lock out honest audits
4586 /// for longer than the burst takes to refill.
4587 const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4588 /// Nanoseconds per second, for the sub-second part of a refill.
4589 const NANOS_PER_SEC: i64 = 1_000_000_000;
4590
4591 fn new() -> Self {
4592 Self {
4593 balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4594 last_refill: Instant::now(),
4595 }
4596 }
4597
4598 /// Add the tokens accrued since the last touch, capped at the burst size.
4599 fn refill(&mut self, now: Instant) {
4600 let elapsed = now.saturating_duration_since(self.last_refill);
4601 self.last_refill = now;
4602 let whole_secs = i64::try_from(elapsed.as_secs())
4603 .unwrap_or(i64::MAX)
4604 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4605 let sub_sec = i64::from(elapsed.subsec_nanos())
4606 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4607 / Self::NANOS_PER_SEC;
4608 self.balance = self
4609 .balance
4610 .saturating_add(whole_secs.saturating_add(sub_sec))
4611 .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4612 }
4613
4614 /// Whether budget remains for a new round-1 proof.
4615 fn has_budget(&mut self, now: Instant) -> bool {
4616 self.refill(now);
4617 self.balance > 0
4618 }
4619
4620 /// Charge `bytes` of completed proof work, carrying debt down to
4621 /// [`Self::MAX_DEBT`].
4622 fn charge(&mut self, bytes: i64, now: Instant) {
4623 self.refill(now);
4624 self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4625 }
4626}
4627
4628/// Resource controls for the HEAVY subtree-audit round 1: a tight
4629/// admission pool separate from the light responsible/slice audits, a per-peer
4630/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4631/// challenge is only served after a matching round 1.
4632///
4633/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4634/// bounds not keyed by peer identity, and so the only one that bounds sustained
4635/// work rather than concurrency or per-identity frequency.
4636#[derive(Clone)]
4637struct SubtreeRound1Limiter {
4638 semaphore: Arc<Semaphore>,
4639 /// Global ceiling on concurrent round-1 proofs (config-driven;
4640 /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4641 /// semaphore because the per-peer admission helper needs the same number.
4642 max_concurrent: usize,
4643 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4644 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4645 /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4646 /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4647 cooldown_interval: Duration,
4648 sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4649 /// Identity-independent ceiling on sustained round-1 work.
4650 work: Arc<RwLock<Round1WorkBudget>>,
4651}
4652
4653impl SubtreeRound1Limiter {
4654 /// `max_concurrent` of 0 would wedge the responder into refusing every
4655 /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4656 /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4657 /// rather than to off.
4658 fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4659 let max_concurrent = max_concurrent.max(1);
4660 Self {
4661 semaphore: Arc::new(Semaphore::new(max_concurrent)),
4662 max_concurrent,
4663 inflight: Arc::new(RwLock::new(HashMap::new())),
4664 cooldown: Arc::new(RwLock::new(HashMap::new())),
4665 cooldown_interval,
4666 sessions: Arc::new(RwLock::new(HashMap::new())),
4667 work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4668 }
4669 }
4670
4671 /// Charge completed round-1 proof work against the responder-wide budget.
4672 async fn charge_work(&self, content_bytes: i64) {
4673 self.work
4674 .write()
4675 .await
4676 .charge(content_bytes, Instant::now());
4677 }
4678
4679 /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4680 /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4681 /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4682 /// drops the challenge (the remote auditor applies its own graced-timeout
4683 /// policy).
4684 async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4685 let guard = admit_bounded_responder(
4686 &self.semaphore,
4687 &self.inflight,
4688 source,
4689 self.max_concurrent,
4690 MAX_SUBTREE_ROUND1_PER_PEER,
4691 )
4692 .await
4693 .ok()?;
4694 // Checked before the per-peer cooldown is stamped, so a peer refused for
4695 // want of budget is not also charged its next allowance.
4696 if !self.work.write().await.has_budget(Instant::now()) {
4697 return None; // guard drops here, releasing the permit + slot
4698 }
4699 let now = Instant::now();
4700 let mut cooldown = self.cooldown.write().await;
4701 if let Some(&last) = cooldown.get(source) {
4702 if now.duration_since(last) < self.cooldown_interval {
4703 return None; // guard drops here, releasing the permit + slot
4704 }
4705 }
4706 // Evict lapsed entries (their cooldown has expired, so they no longer
4707 // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4708 cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4709 if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4710 if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4711 cooldown.remove(&oldest);
4712 }
4713 }
4714 cooldown.insert(*source, now);
4715 Some(guard)
4716 }
4717
4718 /// Record a single-use session once a round-1 proof is built and about to be
4719 /// sent, so the matching round 2 is admitted exactly once.
4720 async fn open_session(
4721 &self,
4722 source: PeerId,
4723 challenge_id: u64,
4724 commitment_hash: [u8; 32],
4725 nonce: [u8; 32],
4726 ) {
4727 let now = Instant::now();
4728 let mut sessions = self.sessions.write().await;
4729 sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4730 if sessions.len() >= MAX_SUBTREE_SESSIONS {
4731 if let Some(oldest) = sessions
4732 .iter()
4733 .min_by_key(|(_, e)| e.inserted)
4734 .map(|(k, _)| *k)
4735 {
4736 sessions.remove(&oldest);
4737 }
4738 }
4739 sessions.insert(
4740 (source, challenge_id),
4741 SubtreeSession {
4742 commitment_hash,
4743 nonce,
4744 inserted: now,
4745 },
4746 );
4747 }
4748
4749 /// Atomically consume the round-2 session for this exchange. `true` iff a
4750 /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4751 /// existed (and is now removed); a miss silently drops round 2 to the graced
4752 /// timeout lane (sessions are ephemeral and can be lost across a restart).
4753 async fn consume_session(
4754 &self,
4755 source: &PeerId,
4756 challenge_id: u64,
4757 commitment_hash: &[u8; 32],
4758 nonce: &[u8; 32],
4759 ) -> bool {
4760 let mut sessions = self.sessions.write().await;
4761 let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4762 Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4763 && &e.commitment_hash == commitment_hash
4764 && &e.nonce == nonce
4765 });
4766 if matches {
4767 sessions.remove(&(*source, challenge_id));
4768 }
4769 matches
4770 }
4771}
4772
4773/// Outcome of admitting a round-2 slice challenge.
4774enum SliceAdmission {
4775 /// Admitted: the guard holds the global permit and the per-peer slot, and
4776 /// the single-use round-1 session has been consumed.
4777 Admitted(AuditResponderGuard),
4778 /// Refused at a responder ceiling. The round-1 session is left INTACT.
4779 Capacity(AuditResponderAdmissionFailure),
4780 /// No live round-1 session matched this challenge.
4781 NoSession,
4782}
4783
4784/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4785/// the single-use round-1 session.
4786///
4787/// The order is the point: a single-use token must not be spent on work that is
4788/// then refused. Consuming first and testing admission second leaves the session
4789/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4790/// even in principle.
4791///
4792/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4793/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4794/// auditor does not currently re-send round 2 within an audit. The preserved
4795/// session is therefore not yet *recovering* an audit — it keeps a refusal
4796/// truthful (temporary means temporary) and keeps the invariant available for a
4797/// retry, rather than baking "capacity drop is permanent" into the state
4798/// machine. If an application-level retry is ruled out for good, this ordering
4799/// still costs nothing over the alternative.
4800///
4801/// Cost of the ordering: the permit and per-peer slot are held across the
4802/// session probe, which is one in-memory map lookup and no chunk work. The
4803/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4804/// share it could already occupy with well-formed ones, so the admission
4805/// surface is unchanged.
4806async fn admit_slice_challenge(
4807 semaphore: &Arc<Semaphore>,
4808 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4809 round1: &SubtreeRound1Limiter,
4810 source: &PeerId,
4811 challenge: &protocol::SubtreeSliceChallenge,
4812) -> SliceAdmission {
4813 let guard =
4814 match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4815 Ok(guard) => guard,
4816 Err(failure) => return SliceAdmission::Capacity(failure),
4817 };
4818 if !round1
4819 .consume_session(
4820 source,
4821 challenge.challenge_id,
4822 &challenge.expected_commitment_hash,
4823 &challenge.nonce,
4824 )
4825 .await
4826 {
4827 // Release the permit and per-peer slot before the caller replies: no
4828 // chunk work follows, so holding them would shrink the pool for nothing.
4829 drop(guard);
4830 return SliceAdmission::NoSession;
4831 }
4832 SliceAdmission::Admitted(guard)
4833}
4834
4835/// Try to admit one audit-responder task for `source`: take a global permit AND
4836/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4837/// its decision-time counters (caller drops the challenge, leaving the remote
4838/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4839/// so one flooder can neither exhaust the global pool's effect on others nor
4840/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4841/// log exactly WHY the drop happened rather than a single opaque "capacity
4842/// reached".
4843async fn admit_audit_responder(
4844 semaphore: &Arc<Semaphore>,
4845 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4846 source: &PeerId,
4847 class: AuditResponderClass,
4848) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4849 let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4850 let peer_limit = class.per_peer_limit();
4851 admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4852}
4853
4854/// Handle an incoming replication protocol message.
4855///
4856/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4857/// request-response path and the response must be sent via `send_response`
4858/// so saorsa-core can route it back to the waiting `send_request` caller.
4859#[allow(clippy::too_many_lines)]
4860async fn handle_replication_message(
4861 source: &PeerId,
4862 msg: ReplicationMessage,
4863 ctx: &ReplicationMessageHandlerContext,
4864 received_at: Instant,
4865 rr_message_id: Option<&str>,
4866) -> Result<()> {
4867 match msg.body {
4868 ReplicationMessageBody::FreshReplicationOffer(offer) => {
4869 dispatch_fresh_offer(
4870 *source,
4871 offer,
4872 ctx,
4873 msg.request_id,
4874 received_at,
4875 rr_message_id,
4876 )
4877 .await
4878 }
4879 ReplicationMessageBody::PaidNotify(notify) => {
4880 dispatch_paid_notify(*source, notify, ctx, received_at).await
4881 }
4882 ReplicationMessageBody::NeighborSyncRequest(request) => {
4883 let bootstrapping = *ctx.is_bootstrapping.read().await;
4884 // Phase-3 storage-bound audit: store the sender's
4885 // commitment for use as `expected_commitment_hash` in
4886 // future audits. Verify signature before storing so a peer
4887 // cannot inject a forged commitment for someone else.
4888 if let Some(target) = ingest_peer_commitment(
4889 source,
4890 request.commitment.as_ref(),
4891 &ctx.p2p_node,
4892 &ctx.last_commitment_by_peer,
4893 &ctx.ever_capable_peers,
4894 &ctx.sig_verify_attempts,
4895 )
4896 .await
4897 {
4898 maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4899 }
4900 dispatch_neighbor_sync_request(
4901 *source,
4902 request,
4903 ctx,
4904 bootstrapping,
4905 // Atomically snapshot + mark-gossiped: emitted in the sync
4906 // response, so we must stay answerable for it (ADR-0002).
4907 ctx.my_commitment_state
4908 .current_for_gossip()
4909 .map(|b| b.commitment().clone()),
4910 msg.request_id,
4911 received_at,
4912 rr_message_id,
4913 )
4914 .await
4915 }
4916 ReplicationMessageBody::VerificationRequest(request) => {
4917 dispatch_verification_request(
4918 *source,
4919 request,
4920 ctx,
4921 msg.request_id,
4922 received_at,
4923 rr_message_id,
4924 )
4925 .await
4926 }
4927 ReplicationMessageBody::FetchRequest(request) => {
4928 dispatch_fetch_request(
4929 *source,
4930 request,
4931 ctx,
4932 msg.request_id,
4933 received_at,
4934 rr_message_id,
4935 )
4936 .await
4937 }
4938 ReplicationMessageBody::AuditChallenge(challenge) => {
4939 // Responsible-chunk audit (audit #2) responder: answer with per-key
4940 // possession digests. This same handler also answers the
4941 // prune-confirmation audit, which sends the same `AuditChallenge`
4942 // wire message.
4943 //
4944 // Answering digests the stored bytes of every challenged key, so —
4945 // like the subtree/byte audits below — run it on a detached task off
4946 // this serial message loop. Handling it inline lets one challenge
4947 // block all other replication traffic until its digests complete
4948 // (head-of-line blocking). The same flood-fair admission applies: a
4949 // global ceiling AND a per-peer cap, dropping the challenge if either
4950 // is hit. A dropped challenge reads as a penalised timeout to the
4951 // auditor, so the caps must remain high enough for honest audit load;
4952 // the per-peer share still prevents one flooder from starving others.
4953 let class = AuditResponderClass::Digest;
4954 let guard = match admit_audit_responder(
4955 &ctx.audit_responder_semaphore,
4956 &ctx.audit_responder_inflight,
4957 source,
4958 class,
4959 )
4960 .await
4961 {
4962 Ok(guard) => guard,
4963 Err(failure) => {
4964 protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
4965 audit_metrics::record_admission_drop(class);
4966 ctx.audit_responder_metrics
4967 .record_drop(*source, failure.reason.into());
4968 warn!(
4969 target: "ant_node::replication::audit_responder",
4970 event = "admission_dropped",
4971 kind = "responsible",
4972 responder_class = class.as_str(),
4973 source = %source,
4974 challenge_id = challenge.challenge_id,
4975 key_count = challenge.keys.len(),
4976 request_response = rr_message_id.is_some(),
4977 dispatch_ms = received_at.elapsed().as_millis(),
4978 reason = failure.reason.as_str(),
4979 global_inflight = failure.global_inflight,
4980 global_limit = failure.global_limit,
4981 peer_inflight = failure.peer_inflight,
4982 peer_limit = failure.peer_limit,
4983 "Audit responder admission dropped"
4984 );
4985 return Ok(());
4986 }
4987 };
4988 let admission_global_inflight = guard.global_inflight;
4989 let admission_peer_inflight = guard.peer_inflight;
4990 ctx.audit_responder_metrics.record_admitted(
4991 *source,
4992 admission_global_inflight,
4993 admission_peer_inflight,
4994 );
4995 info!(
4996 target: "ant_node::replication::audit_responder",
4997 event = "admitted",
4998 kind = "responsible",
4999 responder_class = class.as_str(),
5000 source = %source,
5001 challenge_id = challenge.challenge_id,
5002 key_count = challenge.keys.len(),
5003 request_response = rr_message_id.is_some(),
5004 dispatch_ms = received_at.elapsed().as_millis(),
5005 global_inflight = admission_global_inflight,
5006 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5007 peer_inflight = admission_peer_inflight,
5008 peer_limit = class.per_peer_limit(),
5009 "Audit responder request admitted"
5010 );
5011 let bootstrapping = *ctx.is_bootstrapping.read().await;
5012 let dispatch_latency = received_at.elapsed();
5013 audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5014 debug!(
5015 audit_type = "digest_responder",
5016 dispatch_latency_ms = dispatch_latency.as_millis(),
5017 source = %source,
5018 "Audit challenge dispatch latency measured"
5019 );
5020 let storage = Arc::clone(&ctx.storage);
5021 let p2p_node = Arc::clone(&ctx.p2p_node);
5022 let source = *source;
5023 let request_id = msg.request_id;
5024 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5025 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5026 ctx.detached_task_tracker.spawn(async move {
5027 let _guard = guard; // global permit + per-peer slot, held until done
5028 let worker_started = Instant::now();
5029 match handle_audit_challenge_msg(
5030 &source,
5031 &challenge,
5032 &storage,
5033 &p2p_node,
5034 bootstrapping,
5035 ReplyRoute {
5036 request_id,
5037 rr_message_id: rr_message_id.as_deref(),
5038 protocol: REPLICATION_PROTOCOL_ID,
5039 },
5040 )
5041 .await
5042 {
5043 Ok(completion) => log_audit_responder_completion(
5044 &responder_metrics,
5045 source,
5046 class,
5047 "responsible",
5048 challenge.challenge_id,
5049 challenge.keys.len(),
5050 completion.response_kind,
5051 completion.sent,
5052 received_at,
5053 worker_started,
5054 completion.processing,
5055 completion.response_send,
5056 ),
5057 Err(e) => debug!("Audit challenge from {source} error: {e}"),
5058 }
5059 });
5060 Ok(())
5061 }
5062 ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5063 // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5064 // responder rebuilds the WHOLE nonce-selected subtree, reading every
5065 // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5066 // detached task so this serial message loop is never blocked on disk
5067 // I/O — otherwise one audit stalls all replication traffic (§5).
5068 //
5069 // A bounded, flood-fair admission restores backpressure (codex#1 +
5070 // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5071 // we drop this challenge. Subtree auditors grace timeout
5072 // non-responses, so capacity drops throttle flooders without turning
5073 // into trust penalties (and one source cannot starve other peers,
5074 // since its share is capped per-peer).
5075 let class = AuditResponderClass::Subtree;
5076 info!(
5077 "Audit challenge received: kind=subtree source={source} request_response={}",
5078 rr_message_id.is_some(),
5079 );
5080 // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5081 // so it uses its own tight admission pool + per-peer rate cooldown,
5082 // separate from the light responsible/slice audits, and a miss silently
5083 // drops (subtree auditors grace timeouts).
5084 let Some(guard) = ctx.subtree_round1.admit(source).await else {
5085 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5086 warn!(
5087 target: "ant_node::replication::audit_responder",
5088 event = "admission_dropped",
5089 kind = "subtree",
5090 responder_class = class.as_str(),
5091 source = %source,
5092 challenge_id = challenge.challenge_id,
5093 request_response = rr_message_id.is_some(),
5094 dispatch_ms = received_at.elapsed().as_millis(),
5095 reason = "heavy_pool_cooldown_or_work_budget",
5096 "Audit responder admission dropped"
5097 );
5098 return Ok(());
5099 };
5100 let admission_global_inflight = guard.global_inflight;
5101 let admission_peer_inflight = guard.peer_inflight;
5102 ctx.audit_responder_metrics.record_admitted(
5103 *source,
5104 admission_global_inflight,
5105 admission_peer_inflight,
5106 );
5107 info!(
5108 target: "ant_node::replication::audit_responder",
5109 event = "admitted",
5110 kind = "subtree",
5111 responder_class = class.as_str(),
5112 source = %source,
5113 challenge_id = challenge.challenge_id,
5114 request_response = rr_message_id.is_some(),
5115 dispatch_ms = received_at.elapsed().as_millis(),
5116 global_inflight = admission_global_inflight,
5117 global_limit = ctx.subtree_round1.max_concurrent,
5118 peer_inflight = admission_peer_inflight,
5119 peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5120 "Audit responder request admitted"
5121 );
5122 let bootstrapping = *ctx.is_bootstrapping.read().await;
5123 let storage = Arc::clone(&ctx.storage);
5124 let p2p_node = Arc::clone(&ctx.p2p_node);
5125 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5126 let source = *source;
5127 let request_id = msg.request_id;
5128 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5129 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5130 let subtree_round1 = ctx.subtree_round1.clone();
5131 ctx.detached_task_tracker.spawn(async move {
5132 let _guard = guard; // global permit + per-peer slot, held until done
5133 let worker_started = Instant::now();
5134 let processing_started = Instant::now();
5135 let storage_commitment_audit::Round1Work {
5136 response,
5137 content_bytes,
5138 } = storage_commitment_audit::handle_subtree_challenge_measured(
5139 &challenge,
5140 &storage,
5141 p2p_node.peer_id(),
5142 bootstrapping,
5143 Some(&my_commitment_state),
5144 )
5145 .await;
5146 let processing = processing_started.elapsed();
5147 // Charge the work actually done, on EVERY outcome.
5148 //
5149 // This used to charge only the `Proof` arm, reasoning that the
5150 // rejecting paths either read nothing or reflected this node's
5151 // own broken storage. The second half of that was wrong: a
5152 // retained commitment containing one unreadable key still costs
5153 // a full run of reads and keyed-BLAKE3 passes over every leaf
5154 // before it, and then rejects. An attacker who finds such a
5155 // commitment could replay subtrees over it indefinitely for
5156 // free. The per-peer cooldown does not catch that either, since
5157 // it is escapable by rotating identity — the responder-wide
5158 // budget is the only bound that applies, so it has to see the
5159 // work. A zero charge is a no-op, so the untouched paths are
5160 // unaffected.
5161 subtree_round1.charge_work(content_bytes).await;
5162 // A round-1 proof authorizes exactly one matching round 2: open a
5163 // single-use session so a slice challenge cannot be served without
5164 // a live round-1 exchange.
5165 if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5166 {
5167 subtree_round1
5168 .open_session(
5169 source,
5170 challenge.challenge_id,
5171 challenge.expected_commitment_hash,
5172 challenge.nonce,
5173 )
5174 .await;
5175 }
5176 let response_kind = subtree_audit_response_kind(&response);
5177 let work_items = subtree_audit_response_work_items(&response);
5178 let response_send_started = Instant::now();
5179 let sent = send_replication_response_checked(
5180 &source,
5181 &p2p_node,
5182 request_id,
5183 ReplicationMessageBody::SubtreeAuditResponse(response),
5184 rr_message_id.as_deref(),
5185 None,
5186 )
5187 .await;
5188 let response_send = response_send_started.elapsed();
5189 log_audit_responder_completion(
5190 &responder_metrics,
5191 source,
5192 class,
5193 "subtree",
5194 challenge.challenge_id,
5195 work_items,
5196 response_kind,
5197 sent,
5198 received_at,
5199 worker_started,
5200 processing,
5201 response_send,
5202 );
5203 });
5204 Ok(())
5205 }
5206 ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5207 // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5208 // block of each auditor-selected spot-check key with a Bao verified
5209 // slice + nonced block-tree opening. Reads chunk bytes from disk to
5210 // build the proofs, so it runs off the serial loop under the light
5211 // audit pool's global and per-peer ceilings.
5212 let class = AuditResponderClass::Byte;
5213 info!(
5214 "Audit challenge received: kind=slice source={source} request_response={}",
5215 rr_message_id.is_some(),
5216 );
5217 let guard = match admit_slice_challenge(
5218 &ctx.audit_responder_semaphore,
5219 &ctx.audit_responder_inflight,
5220 &ctx.subtree_round1,
5221 source,
5222 &challenge,
5223 )
5224 .await
5225 {
5226 SliceAdmission::Admitted(guard) => guard,
5227 SliceAdmission::Capacity(failure) => {
5228 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5229 audit_metrics::record_admission_drop(class);
5230 ctx.audit_responder_metrics
5231 .record_drop(*source, failure.reason.into());
5232 warn!(
5233 target: "ant_node::replication::audit_responder",
5234 event = "admission_dropped",
5235 kind = "byte",
5236 responder_class = class.as_str(),
5237 source = %source,
5238 challenge_id = challenge.challenge_id,
5239 key_count = challenge.openings.len(),
5240 request_response = rr_message_id.is_some(),
5241 dispatch_ms = received_at.elapsed().as_millis(),
5242 reason = failure.reason.as_str(),
5243 global_inflight = failure.global_inflight,
5244 global_limit = failure.global_limit,
5245 peer_inflight = failure.peer_inflight,
5246 peer_limit = failure.peer_limit,
5247 "Audit responder admission dropped"
5248 );
5249 return Ok(());
5250 }
5251 // No live round-1 session: reply with a cheap `Transient` rejection
5252 // rather than dropping silently. Sessions are ephemeral (an honest
5253 // responder that restarts between rounds loses its session), and an
5254 // unanswered `send_request` would make saorsa-core record a
5255 // transport trust failure against that honest responder — an
5256 // ongoing effect, not just a rollout-window one. A `Transient`
5257 // reply routes the auditor to the graced timeout lane (no trust
5258 // penalty; the responder re-earns pinned credit on the next audit)
5259 // and does no chunk work, so it is not a DoS lever.
5260 SliceAdmission::NoSession => {
5261 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5262 debug!(
5263 "Slice challenge without a live round-1 session source={source} \
5264 challenge_id={} → Transient reject",
5265 challenge.challenge_id
5266 );
5267 send_replication_response_checked(
5268 source,
5269 &ctx.p2p_node,
5270 msg.request_id,
5271 ReplicationMessageBody::SubtreeSliceResponse(
5272 protocol::SubtreeSliceResponse::Rejected {
5273 challenge_id: challenge.challenge_id,
5274 kind: protocol::RejectKind::Transient,
5275 reason: "no live round-1 session".to_string(),
5276 },
5277 ),
5278 rr_message_id,
5279 None,
5280 )
5281 .await;
5282 return Ok(());
5283 }
5284 };
5285 let admission_global_inflight = guard.global_inflight;
5286 let admission_peer_inflight = guard.peer_inflight;
5287 ctx.audit_responder_metrics.record_admitted(
5288 *source,
5289 admission_global_inflight,
5290 admission_peer_inflight,
5291 );
5292 info!(
5293 target: "ant_node::replication::audit_responder",
5294 event = "admitted",
5295 kind = "byte",
5296 responder_class = class.as_str(),
5297 source = %source,
5298 challenge_id = challenge.challenge_id,
5299 key_count = challenge.openings.len(),
5300 request_response = rr_message_id.is_some(),
5301 dispatch_ms = received_at.elapsed().as_millis(),
5302 global_inflight = admission_global_inflight,
5303 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5304 peer_inflight = admission_peer_inflight,
5305 peer_limit = class.per_peer_limit(),
5306 "Audit responder request admitted"
5307 );
5308 let bootstrapping = *ctx.is_bootstrapping.read().await;
5309 let storage = Arc::clone(&ctx.storage);
5310 let p2p_node = Arc::clone(&ctx.p2p_node);
5311 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5312 let source = *source;
5313 let request_id = msg.request_id;
5314 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5315 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5316 ctx.detached_task_tracker.spawn(async move {
5317 let _guard = guard; // global permit + per-peer slot, held until done
5318 let worker_started = Instant::now();
5319 let processing_started = Instant::now();
5320 let response = storage_commitment_audit::handle_subtree_slice_challenge(
5321 &challenge,
5322 &storage,
5323 p2p_node.peer_id(),
5324 bootstrapping,
5325 Some(&my_commitment_state),
5326 )
5327 .await;
5328 let processing = processing_started.elapsed();
5329 let response_kind = subtree_slice_response_kind(&response);
5330 let response_send_started = Instant::now();
5331 let sent = send_replication_response_checked(
5332 &source,
5333 &p2p_node,
5334 request_id,
5335 ReplicationMessageBody::SubtreeSliceResponse(response),
5336 rr_message_id.as_deref(),
5337 None,
5338 )
5339 .await;
5340 let response_send = response_send_started.elapsed();
5341 log_audit_responder_completion(
5342 &responder_metrics,
5343 source,
5344 class,
5345 "byte",
5346 challenge.challenge_id,
5347 challenge.openings.len(),
5348 response_kind,
5349 sent,
5350 received_at,
5351 worker_started,
5352 processing,
5353 response_send,
5354 );
5355 });
5356 Ok(())
5357 }
5358 ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5359 // ADR-0004: answer a commitment-by-pin fetch from the retained set
5360 // only. `lookup_by_hash` is an allocation-light read over the
5361 // bounded slot set; it returns the live current commitment or any
5362 // still-answerable recently-gossiped/quoted one. A miss is reported
5363 // as `NotRetained` (graced, never confirmed) rather than an error,
5364 // so an aged-out pin can never brand an honest node.
5365 //
5366 // Reuse the audit-responder admission guard (global ceiling + per-peer
5367 // cap) so a flood of fetches cannot drive unbounded commitment
5368 // clone/encode/send work; over-limit is dropped, which the fetching
5369 // peer graces exactly like a missed audit response.
5370 let class = AuditResponderClass::CommitmentPin;
5371 let guard = match admit_audit_responder(
5372 &ctx.audit_responder_semaphore,
5373 &ctx.audit_responder_inflight,
5374 source,
5375 class,
5376 )
5377 .await
5378 {
5379 Ok(guard) => guard,
5380 Err(failure) => {
5381 audit_metrics::record_admission_drop(class);
5382 ctx.audit_responder_metrics
5383 .record_drop(*source, failure.reason.into());
5384 warn!(
5385 target: "ant_node::replication::audit_responder",
5386 event = "admission_dropped",
5387 kind = "commitment_pin",
5388 responder_class = class.as_str(),
5389 source = %source,
5390 challenge_id = msg.request_id,
5391 request_response = rr_message_id.is_some(),
5392 dispatch_ms = received_at.elapsed().as_millis(),
5393 reason = failure.reason.as_str(),
5394 global_inflight = failure.global_inflight,
5395 global_limit = failure.global_limit,
5396 peer_inflight = failure.peer_inflight,
5397 peer_limit = failure.peer_limit,
5398 "Audit responder admission dropped"
5399 );
5400 return Ok(());
5401 }
5402 };
5403 ctx.audit_responder_metrics.record_admitted(
5404 *source,
5405 guard.global_inflight,
5406 guard.peer_inflight,
5407 );
5408 info!(
5409 target: "ant_node::replication::audit_responder",
5410 event = "admitted",
5411 kind = "commitment_pin",
5412 responder_class = class.as_str(),
5413 source = %source,
5414 challenge_id = msg.request_id,
5415 request_response = rr_message_id.is_some(),
5416 dispatch_ms = received_at.elapsed().as_millis(),
5417 global_inflight = guard.global_inflight,
5418 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5419 peer_inflight = guard.peer_inflight,
5420 peer_limit = class.per_peer_limit(),
5421 "Audit responder request admitted"
5422 );
5423 let worker_started = Instant::now();
5424 let processing_started = Instant::now();
5425 let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5426 protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5427 |built| protocol::GetCommitmentByPinResponse::Found {
5428 commitment: built.commitment().clone(),
5429 },
5430 );
5431 let processing = processing_started.elapsed();
5432 let response_kind = commitment_pin_response_kind(&response);
5433 let response_send_started = Instant::now();
5434 let sent = send_replication_response_checked(
5435 source,
5436 &ctx.p2p_node,
5437 msg.request_id,
5438 ReplicationMessageBody::GetCommitmentByPinResponse(response),
5439 rr_message_id,
5440 None,
5441 )
5442 .await;
5443 let response_send = response_send_started.elapsed();
5444 log_audit_responder_completion(
5445 &ctx.audit_responder_metrics,
5446 *source,
5447 class,
5448 "commitment_pin",
5449 msg.request_id,
5450 1,
5451 response_kind,
5452 sent,
5453 received_at,
5454 worker_started,
5455 processing,
5456 response_send,
5457 );
5458 drop(guard);
5459 Ok(())
5460 }
5461 // Response messages are handled by their respective request initiators.
5462 ReplicationMessageBody::FreshReplicationResponse(_)
5463 | ReplicationMessageBody::NeighborSyncResponse(_)
5464 | ReplicationMessageBody::VerificationResponse(_)
5465 | ReplicationMessageBody::FetchResponse(_)
5466 | ReplicationMessageBody::AuditResponse(_)
5467 | ReplicationMessageBody::SubtreeAuditResponse(_)
5468 | ReplicationMessageBody::SubtreeSliceResponse(_)
5469 | ReplicationMessageBody::GetCommitmentByPinResponse(_) => Ok(()),
5470 }
5471}
5472
5473// ---------------------------------------------------------------------------
5474// Per-message-type handlers
5475// ---------------------------------------------------------------------------
5476
5477/// Verify a payment proof, yielding early if the engine is shutting down.
5478///
5479/// Returns `None` when shutdown won the race, meaning no verdict was reached
5480/// and the caller must abandon the message without storing or penalising.
5481///
5482/// Payment verification is pure network I/O — an EVM round trip and, on the
5483/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5484/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5485/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5486/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5487/// is guaranteed to end.
5488///
5489/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5490/// dropping its awaiter would detach a live LMDB transaction and break the
5491/// very contract the unbounded wait exists to uphold.
5492async fn verify_payment_until_shutdown(
5493 payment_verifier: &Arc<PaymentVerifier>,
5494 key: &XorName,
5495 proof_of_payment: &[u8],
5496 context: VerificationContext,
5497 shutdown: &CancellationToken,
5498) -> Option<Result<crate::payment::PaymentStatus>> {
5499 tokio::select! {
5500 () = shutdown.cancelled() => None,
5501 result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5502 Some(result)
5503 }
5504 }
5505}
5506
5507/// A fresh offer rejected on payload shape alone.
5508struct FreshOfferRejection {
5509 /// Wire-visible reason returned to the sender.
5510 reason: String,
5511 /// Whether the sender is charged for it. Reserved for offers no honest
5512 /// node would construct, so an ordinary capacity refusal stays free.
5513 penalise: bool,
5514}
5515
5516/// Reject a fresh offer on payload shape, or return `None` to admit it.
5517///
5518/// Pure and non-blocking by construction: these are the checks answerable from
5519/// the payload alone, run on the serial message loop *before* the in-flight
5520/// claim and the admission permit, so a malformed offer can neither lock an
5521/// honest offer out of its key nor occupy one of the scarce
5522/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5523/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5524/// verification — stays on the worker.
5525///
5526/// The content-address hash is deliberately included despite costing real CPU
5527/// on the loop: it is what makes the entry below *earned* rather than merely
5528/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5529/// arrive at link speed, so a flooder can never make this loop hash faster than
5530/// it can deliver the bytes, and delivering them already cost it more than the
5531/// hash costs us. The receive path has in any case already deserialised the
5532/// same buffer.
5533///
5534/// Every rejection here is penalised. These are the conditions no honest sender
5535/// can produce — an absent, undersized, oversized, or non-matching payload — as
5536/// distinct from a capacity refusal, which is this node's own state and stays
5537/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5538/// proof that fails to verify may simply have been read against a lagging chain
5539/// view, and penalising that would charge honest senders in correlated bursts.
5540fn fresh_offer_structural_rejection(
5541 key: &XorName,
5542 data: &[u8],
5543 proof_of_payment: &[u8],
5544) -> Option<FreshOfferRejection> {
5545 // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5546 // and an absent proof is the cheapest possible slot-filler, so this is the
5547 // first thing checked.
5548 if proof_of_payment.is_empty() {
5549 return Some(FreshOfferRejection {
5550 reason: "Missing proof of payment".to_string(),
5551 penalise: true,
5552 });
5553 }
5554
5555 // Bound the proof before it can be queued. The verifier applies the same
5556 // limits, but only once the offer reaches a worker — too late here, because
5557 // an entry retains a proof per queued sender, and a proof is capped on the
5558 // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5559 // a byte of data and a 10 MiB "proof" would be admitted, and
5560 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5561 // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5562 // admission bound exists to enforce.
5563 if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5564 return Some(FreshOfferRejection {
5565 reason: format!(
5566 "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5567 proof_of_payment.len(),
5568 ),
5569 penalise: true,
5570 });
5571 }
5572 if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5573 return Some(FreshOfferRejection {
5574 reason: format!(
5575 "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5576 proof_of_payment.len(),
5577 ),
5578 penalise: true,
5579 });
5580 }
5581
5582 // Enforce chunk size invariant: the normal PUT path rejects data larger
5583 // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5584 // prevent peers from pushing oversized records through replication.
5585 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5586 return Some(FreshOfferRejection {
5587 reason: format!(
5588 "Data size {} exceeds maximum chunk size {}",
5589 data.len(),
5590 crate::ant_protocol::MAX_CHUNK_SIZE,
5591 ),
5592 penalise: true,
5593 });
5594 }
5595
5596 // Mirror the normal PUT path: the advertised key must be the content
5597 // address of the supplied bytes. Ordered last so an oversized payload is
5598 // refused without being hashed.
5599 //
5600 // This is the check that makes the entry safe to open, and safe for later
5601 // offers to be folded into. Until it passes, the sender has only *asserted*
5602 // an association between the key and the bytes. Opening an entry on an
5603 // assertion would let any peer that knows a key — every recipient of its
5604 // `PaidNotify`, not just the close group — seize it with junk; folding a
5605 // later offer into an entry on an assertion would be worse still, since the
5606 // handler tries each queued proof against the *opener's* bytes and would be
5607 // storing bytes nobody offered for that proof.
5608 let computed_key = crate::client::compute_address(data);
5609 if computed_key != *key {
5610 return Some(FreshOfferRejection {
5611 reason: format!(
5612 "Content address mismatch: expected {}, computed {}",
5613 hex::encode(key),
5614 hex::encode(computed_key),
5615 ),
5616 penalise: true,
5617 });
5618 }
5619
5620 None
5621}
5622
5623/// Tell `source` its offer for `key` was not taken.
5624///
5625/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5626/// one-way `send_message`, so the refusal is observed only as a later absence by
5627/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5628async fn refuse_fresh_offer(
5629 source: &PeerId,
5630 key: XorName,
5631 reason: String,
5632 ctx: &ReplicationMessageHandlerContext,
5633 request_id: u64,
5634 rr_message_id: Option<&str>,
5635) {
5636 send_replication_response(
5637 source,
5638 &ctx.p2p_node,
5639 request_id,
5640 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5641 key,
5642 reason,
5643 }),
5644 rr_message_id,
5645 )
5646 .await;
5647}
5648
5649/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5650/// the sender when the defect is one no honest node could produce.
5651///
5652/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5653/// two say opposite things: this is the sender's fault, that one is ours.
5654async fn refuse_malformed_fresh_offer(
5655 source: &PeerId,
5656 key: XorName,
5657 rejection: FreshOfferRejection,
5658 ctx: &ReplicationMessageHandlerContext,
5659 request_id: u64,
5660 rr_message_id: Option<&str>,
5661) {
5662 if rejection.penalise {
5663 warn!(
5664 "Rejecting fresh offer for key {} from {source}: {}",
5665 hex::encode(key),
5666 rejection.reason
5667 );
5668 ctx.p2p_node
5669 .report_trust_event(
5670 source,
5671 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5672 )
5673 .await;
5674 } else {
5675 debug!(
5676 "Fresh offer for {} from {source} refused before admission: {}",
5677 hex::encode(key),
5678 rejection.reason
5679 );
5680 }
5681 refuse_fresh_offer(
5682 source,
5683 key,
5684 rejection.reason,
5685 ctx,
5686 request_id,
5687 rr_message_id,
5688 )
5689 .await;
5690}
5691
5692/// Tell senders whose proofs joined an entry that was torn down before a handler
5693/// ever ran for it.
5694///
5695/// Only reachable in the window between opening an entry and failing to take an
5696/// admission permit. Their proofs are answered rather than dropped with the
5697/// entry, so the refusal count reflects what actually happened.
5698async fn refuse_stranded_fresh_offers(
5699 key: XorName,
5700 stranded: Vec<FreshOfferAttempt>,
5701 ctx: &ReplicationMessageHandlerContext,
5702) {
5703 for attempt in stranded {
5704 refuse_fresh_offer(
5705 &attempt.source,
5706 key,
5707 "Receiver at fresh-offer capacity".to_string(),
5708 ctx,
5709 attempt.request_id,
5710 attempt.rr_message_id.as_deref(),
5711 )
5712 .await;
5713 }
5714}
5715
5716/// Admit a fresh offer for handling on a worker, or refuse it.
5717///
5718/// This runs on the serial non-audit message loop, so it must stay cheap: every
5719/// path here is a set insert, a permit try, or a small response send. The offer
5720/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5721/// runs on a tracked worker task, never inline, because stalling this loop backs
5722/// up the inbound queue and ultimately drops replication messages wholesale.
5723///
5724/// Admission is bounded **per source** as well as globally
5725/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5726/// hold every slot, and since a refusal is later read as absence by the
5727/// sender's delayed possession check, the resulting refusals land as
5728/// audit-severity penalties on this node rather than on the flooder.
5729///
5730/// The structurally-invalid checks run **before** the entry is opened and before
5731/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5732/// the duration of a payment verification.
5733///
5734/// Only the offer that *opens* an entry costs a permit and a worker. Later
5735/// offers for the same key contribute their proof and are answered by whatever
5736/// the opener's handler concludes, which is what keeps the routine
5737/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5738/// one verification per key.
5739async fn dispatch_fresh_offer(
5740 source: PeerId,
5741 offer: protocol::FreshReplicationOffer,
5742 ctx: &ReplicationMessageHandlerContext,
5743 request_id: u64,
5744 received_at: Instant,
5745 rr_message_id: Option<&str>,
5746) -> Result<()> {
5747 if let Some(rejection) =
5748 fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5749 {
5750 refuse_malformed_fresh_offer(
5751 &source,
5752 offer.key,
5753 rejection,
5754 ctx,
5755 request_id,
5756 rr_message_id,
5757 )
5758 .await;
5759 return Ok(());
5760 }
5761
5762 // Join the work already in flight for this key before taking an admission
5763 // permit, so the duplicates a single client PUT produces cost one permit
5764 // between them rather than one each.
5765 //
5766 // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5767 // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5768 // already held for the key. That is what lets its payload be dropped here
5769 // and only its proof retained: the handler will try that proof against the
5770 // bytes it already has.
5771 let key = offer.key;
5772 let admission_outcome = FreshOfferEntryGuard::admit(
5773 &ctx.fresh_offer_in_flight,
5774 offer,
5775 source,
5776 request_id,
5777 rr_message_id.map(ToOwned::to_owned),
5778 received_at,
5779 );
5780 let mut entry = match admission_outcome {
5781 FreshOfferAdmission::Opened(entry) => entry,
5782 FreshOfferAdmission::Joined => {
5783 // No response yet: this proof has not been judged. The handler that
5784 // owns the key answers every queued sender once it settles.
5785 debug!(
5786 "Fresh offer for {} from {source} queued behind the handler already \
5787 holding the key",
5788 hex::encode(key)
5789 );
5790 return Ok(());
5791 }
5792 // Surplus, not suspect: the proofs already queued are enough to place
5793 // the record, so neither case is charged as misbehaviour.
5794 surplus => {
5795 debug!(
5796 "Fresh offer for {} from {source} refused: {}",
5797 hex::encode(key),
5798 surplus.surplus_reason()
5799 );
5800 refuse_fresh_offer(
5801 &source,
5802 key,
5803 "Duplicate offer already in flight".to_string(),
5804 ctx,
5805 request_id,
5806 rr_message_id,
5807 )
5808 .await;
5809 return Ok(());
5810 }
5811 };
5812
5813 let admission = match admit_bounded_responder(
5814 &ctx.fresh_offer_admission_semaphore,
5815 &ctx.fresh_offer_responder_inflight,
5816 &source,
5817 FRESH_OFFER_MAX_OUTSTANDING,
5818 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5819 )
5820 .await
5821 {
5822 Ok(guard) => guard,
5823 Err(failure) => {
5824 audit_metrics::record_responder_admission_drop(
5825 ReplicationResponderClass::FreshOffer,
5826 failure.reason.into(),
5827 );
5828 // WARN, not DEBUG: a healthy node should never refuse a legitimate
5829 // fresh offer. The sender does not read this refusal, so it
5830 // resurfaces as a missing key at the delayed possession check and
5831 // is charged to US at audit severity. Log the binding ceiling
5832 // locally; the wire reason stays generic so a probing peer cannot
5833 // map out this node's live occupancy.
5834 warn!(
5835 responder_class = "fresh_offer",
5836 source = %source,
5837 key = %hex::encode(key),
5838 penalty_suspended = config::close_group_storage_penalty_suspended(),
5839 "Fresh offer refused at admission; the resulting absence is recorded \
5840 against this node, and penalised unless the release withholds it: \
5841 {failure}"
5842 );
5843 // Release the key explicitly rather than on drop, so the next offer
5844 // opens a fresh entry rather than queueing behind a handler that was
5845 // never spawned — and so any proof that joined in the window between
5846 // opening the entry and failing here is answered rather than
5847 // discarded with it.
5848 let stranded = entry.release();
5849 refuse_fresh_offer(
5850 &source,
5851 key,
5852 "Receiver at fresh-offer capacity".to_string(),
5853 ctx,
5854 request_id,
5855 rr_message_id,
5856 )
5857 .await;
5858 refuse_stranded_fresh_offers(key, stranded, ctx).await;
5859 return Ok(());
5860 }
5861 };
5862
5863 let ctx = ctx.clone();
5864 // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5865 // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
5866 // those references be released before the caller reopens the environment.
5867 ctx.detached_task_tracker
5868 .clone()
5869 .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5870 Ok(())
5871}
5872
5873/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5874///
5875/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5876/// A started handler is never cancelled: `storage.put()` awaits
5877/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5878/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5879/// and from `handle_fresh_offer` racing the token around payment verification.
5880///
5881/// Works down the key's queued proofs rather than judging the key on the first
5882/// one. A proof that fails to establish payment disqualifies its *sender*, not
5883/// the record: the bytes are content-addressed and identical across every offer,
5884/// so the next sender's proof is tried against the copy already in hand — no
5885/// second payload, no second permit, no refetch. Only when a failure is about
5886/// the key itself (not responsible, no capacity, shutting down) does rotating
5887/// become pointless, because every remaining proof would meet the same wall.
5888async fn run_fresh_offer_worker(
5889 key: XorName,
5890 mut entry: Box<FreshOfferEntryGuard>,
5891 ctx: ReplicationMessageHandlerContext,
5892 admission: ResponderGuard,
5893) {
5894 // The admission permit is released on completion, freeing the payload's
5895 // memory budget and the opening source's per-peer share. The entry releases
5896 // the key itself, either as the queue empties or on drop.
5897 let _admission = admission;
5898 let received_at = entry.received_at();
5899 // Wait for a worker slot here rather than in the caller. The worker bound
5900 // caps concurrent EVM and storage pressure; making the message loop wait on
5901 // it is what put that pressure back on the loop.
5902 //
5903 // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
5904 // path for offers still queued behind a worker when the engine stops — not
5905 // dead code.
5906 let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
5907 .acquire_owned()
5908 .await
5909 else {
5910 debug!(
5911 "Fresh offer for {} dropped: worker pool shut down",
5912 hex::encode(key)
5913 );
5914 return;
5915 };
5916 // Fresh offers are fire-and-forget (`send_message`), so there is no
5917 // requester deadline to honour and a late store is still genuinely useful.
5918 // The threshold is the point past which the offer has already cost us what
5919 // it was going to cost: the possession check (ADR-0003) has run by then and
5920 // charged the absence to this node, and it does not re-offer the key —
5921 // repair comes later from neighbor sync. Shedding here trades a copy that
5922 // would have arrived after the penalty for the multi-MiB payload it is
5923 // holding, and keeps a backlog from outliving its own admission bound.
5924 //
5925 // Note this is a memory-pressure decision, not a redundancy one: the copy
5926 // is late, not useless, so on a node with headroom finishing it would still
5927 // beat waiting for neighbor sync.
5928 if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
5929 debug!(
5930 responder_class = "fresh_offer",
5931 key = %hex::encode(key),
5932 request_age_ms = received_at.elapsed().as_millis(),
5933 "Superseded fresh offer shed at dequeue"
5934 );
5935 return;
5936 }
5937
5938 let mut verdict = FreshOfferOutcome::Abandoned;
5939 while let Some(attempt) = entry.next_attempt() {
5940 match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
5941 Ok(outcome) => {
5942 verdict = outcome;
5943 match outcome {
5944 // Settled: the record is down and every remaining sender
5945 // wanted exactly that. Abandoned: the key cannot be placed
5946 // by anyone right now, so the proofs behind this one would
5947 // fail identically. Either way there is nothing left to try.
5948 FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
5949 // This sender's claim to have paid did not hold up. Say so
5950 // to that sender alone and try the next proof.
5951 FreshOfferOutcome::ProofRejected => {}
5952 }
5953 }
5954 Err(e) => {
5955 debug!(
5956 "Fresh replication offer for {} from {} error: {e}",
5957 hex::encode(key),
5958 attempt.source
5959 );
5960 verdict = FreshOfferOutcome::Abandoned;
5961 break;
5962 }
5963 }
5964 }
5965
5966 // Answer the senders whose proofs were never reached. A stored record is
5967 // what they were asking for, so it is an acceptance even though their own
5968 // proof went untested.
5969 let unreached = entry.release();
5970 if unreached.is_empty() {
5971 return;
5972 }
5973 let response = match verdict {
5974 FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
5975 FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
5976 FreshReplicationResponse::Rejected {
5977 key,
5978 reason: "Record could not be stored from any offered proof".to_string(),
5979 }
5980 }
5981 };
5982 for attempt in unreached {
5983 send_replication_response(
5984 &attempt.source,
5985 &ctx.p2p_node,
5986 attempt.request_id,
5987 ReplicationMessageBody::FreshReplicationResponse(response.clone()),
5988 attempt.rr_message_id.as_deref(),
5989 )
5990 .await;
5991 }
5992}
5993
5994/// What one proof concluded, and whether another proof for the same key is worth
5995/// trying.
5996///
5997/// The distinction the worker acts on is *what the failure was about*. A
5998/// rejected proof is a statement about its sender; anything else is a statement
5999/// about the key or this node, which no other sender's proof can change.
6000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6001enum FreshOfferOutcome {
6002 /// The record is stored. The key is done.
6003 Settled,
6004 /// This proof did not establish payment. A different sender's proof for the
6005 /// same bytes may still succeed.
6006 ProofRejected,
6007 /// Nothing about this key can succeed right now — not responsible, no disk,
6008 /// shutting down, or a write that failed. Rotating repeats the failure.
6009 Abandoned,
6010}
6011
6012// A linear sequence of protocol steps — structural recheck, responsibility,
6013// capacity, payment, write — each with its own refusal response. Splitting it
6014// would scatter one decision across several functions.
6015#[allow(clippy::too_many_lines)]
6016async fn handle_fresh_offer(
6017 key: &XorName,
6018 data: &[u8],
6019 attempt: &FreshOfferAttempt,
6020 ctx: &ReplicationMessageHandlerContext,
6021) -> Result<FreshOfferOutcome> {
6022 let source = &attempt.source;
6023 let request_id = attempt.request_id;
6024 let rr_message_id = attempt.rr_message_id.as_deref();
6025 let p2p_node = &ctx.p2p_node;
6026 let config = &ctx.config;
6027 let self_id = *p2p_node.peer_id();
6028
6029 // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6030 // proof, bad proof size, oversized payload, content-address mismatch —
6031 // before opening the entry or taking an admission permit, so nothing
6032 // reaching a worker should trip them. Kept so the handler is correct in
6033 // isolation. Note this re-checks the *pairing* actually being used: these
6034 // bytes against this attempt's proof.
6035 if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6036 {
6037 if rejection.penalise {
6038 warn!(
6039 "Rejecting fresh offer for key {}: {}",
6040 hex::encode(key),
6041 rejection.reason
6042 );
6043 p2p_node
6044 .report_trust_event(
6045 source,
6046 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6047 )
6048 .await;
6049 }
6050 send_replication_response(
6051 source,
6052 p2p_node,
6053 request_id,
6054 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6055 key: *key,
6056 reason: rejection.reason,
6057 }),
6058 rr_message_id,
6059 )
6060 .await;
6061 // Structurally invalid is a fact about this attempt, not the key.
6062 return Ok(FreshOfferOutcome::ProofRejected);
6063 }
6064
6065 // Rule 7: check storage admission. Fresh chunk receivers accept across the
6066 // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6067 // the same width client PUTs use), not just the close group plus a small
6068 // margin (ADR-0003). During full-node shunning a healthy replica's routing
6069 // table may still list closer full nodes it hasn't evicted yet, ranking it
6070 // outside the narrow window in its own view; the wider accept window absorbs
6071 // that transient skew so the chunk still lands. Retention (pruning) stays at
6072 // `storage_admission_width`, so steady-state replication is unchanged.
6073 if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6074 {
6075 send_replication_response(
6076 source,
6077 p2p_node,
6078 request_id,
6079 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6080 key: *key,
6081 reason: "Not in storage-admission range for this key".to_string(),
6082 }),
6083 rr_message_id,
6084 )
6085 .await;
6086 // About the key and this node's place in the routing table, not about
6087 // the sender: every queued proof would be refused identically.
6088 return Ok(FreshOfferOutcome::Abandoned);
6089 }
6090
6091 // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6092 // never store this record, so reject it before the expensive payment
6093 // verification (EVM on-chain query / merkle pool work) rather than verifying
6094 // and only then failing at `storage.put` below. Reuses the cached capacity
6095 // check (passing results only, so freed space is detected promptly), and the
6096 // store path keeps its own check as defence-in-depth.
6097 if let Err(e) = ctx.storage.check_capacity() {
6098 info!(
6099 target: "ant_node::storage::disk_precheck",
6100 key = %hex::encode(key),
6101 "Rejecting fresh replication offer before payment verification: {e}"
6102 );
6103 send_replication_response(
6104 source,
6105 p2p_node,
6106 request_id,
6107 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6108 key: *key,
6109 reason: e.to_string(),
6110 }),
6111 rr_message_id,
6112 )
6113 .await;
6114 // A full disk is this node's condition, not the sender's.
6115 return Ok(FreshOfferOutcome::Abandoned);
6116 }
6117
6118 // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6119 // part of the immediate write fan-out: this receiver is about to store the
6120 // record as if the client had PUT it here directly. Storage admission
6121 // was checked above before proof work. FreshReplication verification is
6122 // identical to ClientPut — store-strength cache semantics, paid-quote
6123 // issuer K-closeness checks for single-node proofs, merkle candidate
6124 // closeness for merkle proofs, and the same price-floor policy — the
6125 // distinct context only labels price-floor telemetry.
6126 let Some(verification) = verify_payment_until_shutdown(
6127 &ctx.payment_verifier,
6128 key,
6129 &attempt.proof_of_payment,
6130 fresh_offer_payment_context(),
6131 &ctx.shutdown,
6132 )
6133 .await
6134 else {
6135 debug!(
6136 "Fresh offer for {} from {source} abandoned: engine shutting down \
6137 during payment verification",
6138 hex::encode(key)
6139 );
6140 return Ok(FreshOfferOutcome::Abandoned);
6141 };
6142 match verification {
6143 Ok(status) if status.can_store() => {
6144 debug!("PoP validated for fresh offer key {}", hex::encode(key));
6145 }
6146 // The chain has no record of this payment. That is a statement about
6147 // *this sender's* proof, so the key rotates to the next one rather than
6148 // being written off — the whole point of queueing them.
6149 //
6150 // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6151 // not "definitively unpaid", so a lagging or reorganising chain view
6152 // renders honest senders indistinguishable from forgers, and penalising
6153 // would land on the entire close group at once. The structural checks in
6154 // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6155 // because those cannot be produced by an honest sender at all.
6156 Ok(_) => {
6157 debug!(
6158 "Fresh offer for {} from {source}: no payment found for this proof",
6159 hex::encode(key)
6160 );
6161 send_replication_response(
6162 source,
6163 p2p_node,
6164 request_id,
6165 ReplicationMessageBody::FreshReplicationResponse(
6166 FreshReplicationResponse::Rejected {
6167 key: *key,
6168 reason: "Payment verification failed: payment required".to_string(),
6169 },
6170 ),
6171 rr_message_id,
6172 )
6173 .await;
6174 return Ok(FreshOfferOutcome::ProofRejected);
6175 }
6176 // A verification *error* is usually ours — an unreachable or failing EVM
6177 // endpoint — so it is neither penalised nor treated as this sender's
6178 // fault. Another proof still gets its turn, since the next call may well
6179 // succeed against a recovered endpoint.
6180 Err(e) => {
6181 warn!("PoP verification error for key {}: {e}", hex::encode(key));
6182 send_replication_response(
6183 source,
6184 p2p_node,
6185 request_id,
6186 ReplicationMessageBody::FreshReplicationResponse(
6187 FreshReplicationResponse::Rejected {
6188 key: *key,
6189 reason: format!("Payment verification error: {e}"),
6190 },
6191 ),
6192 rr_message_id,
6193 )
6194 .await;
6195 return Ok(FreshOfferOutcome::ProofRejected);
6196 }
6197 }
6198
6199 // Rule 6: add to PaidForList.
6200 if let Err(e) = ctx.paid_list.insert(key).await {
6201 warn!("Failed to add key to PaidForList: {e}");
6202 }
6203
6204 // Store the record.
6205 match ctx.storage.put(key, data).await {
6206 Ok(_) => {
6207 send_replication_response(
6208 source,
6209 p2p_node,
6210 request_id,
6211 ReplicationMessageBody::FreshReplicationResponse(
6212 FreshReplicationResponse::Accepted { key: *key },
6213 ),
6214 rr_message_id,
6215 )
6216 .await;
6217 Ok(FreshOfferOutcome::Settled)
6218 }
6219 Err(e) => {
6220 send_replication_response(
6221 source,
6222 p2p_node,
6223 request_id,
6224 ReplicationMessageBody::FreshReplicationResponse(
6225 FreshReplicationResponse::Rejected {
6226 key: *key,
6227 reason: e.to_string(),
6228 },
6229 ),
6230 rr_message_id,
6231 )
6232 .await;
6233 // The payment was good and the write still failed, so this is local
6234 // storage trouble that another proof cannot get around.
6235 Ok(FreshOfferOutcome::Abandoned)
6236 }
6237 }
6238}
6239
6240/// Admit a paid-list notification for handling on a worker, or drop it.
6241///
6242/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6243/// meant one message could park every other non-audit message behind a full
6244/// payment verification. That verification is not a bounded local computation:
6245/// on the merkle path it performs an iterative Kademlia lookup capped only by
6246/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6247/// the loop for minutes while the bounded inbound queue behind it overflowed
6248/// and dropped unrelated replication traffic wholesale.
6249///
6250/// It now follows the same detached-responder pattern as neighbor sync and
6251/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6252/// when stale, and run on a tracked worker.
6253///
6254/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6255/// refused notify is simply dropped. The sender's own paid-list convergence
6256/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6257/// the recovery path, exactly as for a notify lost in transit.
6258async fn dispatch_paid_notify(
6259 source: PeerId,
6260 notify: protocol::PaidNotify,
6261 ctx: &ReplicationMessageHandlerContext,
6262 received_at: Instant,
6263) -> Result<()> {
6264 let admission = match admit_bounded_responder(
6265 &ctx.paid_notify_admission_semaphore,
6266 &ctx.paid_notify_responder_inflight,
6267 &source,
6268 PAID_NOTIFY_MAX_OUTSTANDING,
6269 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6270 )
6271 .await
6272 {
6273 Ok(guard) => guard,
6274 Err(failure) => {
6275 audit_metrics::record_responder_admission_drop(
6276 ReplicationResponderClass::PaidNotify,
6277 failure.reason.into(),
6278 );
6279 // WARN for the same reason as fresh offers: PaidNotify is one-way,
6280 // so a refusal discards durable paid-list evidence outright rather
6281 // than pushing work back onto a requester.
6282 warn!(
6283 responder_class = "paid_notify",
6284 source = %source,
6285 key = %hex::encode(notify.key),
6286 "Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
6287 );
6288 return Ok(());
6289 }
6290 };
6291
6292 let ctx = ctx.clone();
6293 let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6294 // Deliberately NOT the verification request deadline used by the
6295 // request/response responders. Nobody is waiting on a notify, and shedding
6296 // one discards durable paid-list evidence rather than a reply a requester
6297 // has already given up on. The threshold is instead the point at which the
6298 // pull path would have learned the same fact anyway: one slow-cadence
6299 // neighbor-sync interval, after which the verification cycle's paid-list
6300 // quorum makes this notify genuinely redundant.
6301 let queue_max_age = ctx.config.neighbor_sync_interval_max;
6302 ctx.detached_task_tracker.clone().spawn(async move {
6303 let _admission = admission;
6304 // Closed by `shutdown()`, so this is the prompt exit path for notifies
6305 // still queued behind a worker when the engine stops.
6306 let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6307 debug!("Paid notify from {source} dropped: worker pool shut down");
6308 return;
6309 };
6310 if request_is_stale(received_at, queue_max_age) {
6311 debug!(
6312 responder_class = "paid_notify",
6313 source = %source,
6314 request_age_ms = received_at.elapsed().as_millis(),
6315 "Redundant paid notify shed at dequeue"
6316 );
6317 return;
6318 }
6319 if let Err(e) = handle_paid_notify(
6320 &source,
6321 ¬ify,
6322 &ctx.paid_list,
6323 &ctx.payment_verifier,
6324 &ctx.p2p_node,
6325 &ctx.config,
6326 &ctx.shutdown,
6327 )
6328 .await
6329 {
6330 debug!("Paid notify from {source} error: {e}");
6331 }
6332 });
6333
6334 Ok(())
6335}
6336
6337async fn handle_paid_notify(
6338 _source: &PeerId,
6339 notify: &protocol::PaidNotify,
6340 paid_list: &Arc<PaidList>,
6341 payment_verifier: &Arc<PaymentVerifier>,
6342 p2p_node: &Arc<P2PNode>,
6343 config: &ReplicationConfig,
6344 shutdown: &CancellationToken,
6345) -> Result<()> {
6346 let self_id = *p2p_node.peer_id();
6347
6348 // Rule 3: validate PoP presence before adding.
6349 if notify.proof_of_payment.is_empty() {
6350 return Ok(());
6351 }
6352
6353 // Check if we're in PaidCloseGroup for this key.
6354 if !admission::is_in_paid_close_group(
6355 &self_id,
6356 ¬ify.key,
6357 p2p_node,
6358 config.paid_list_close_group_size,
6359 )
6360 .await
6361 {
6362 return Ok(());
6363 }
6364
6365 // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6366 // paid-list metadata, so local paid-list close-group membership was checked
6367 // above before proof work. The verifier then runs the same payment proof
6368 // checks as ClientPut while writing a paid-list-strength cache entry.
6369 let Some(verification) = verify_payment_until_shutdown(
6370 payment_verifier,
6371 ¬ify.key,
6372 ¬ify.proof_of_payment,
6373 paid_notify_payment_context(),
6374 shutdown,
6375 )
6376 .await
6377 else {
6378 debug!(
6379 "Paid notify for {} abandoned: engine shutting down during payment \
6380 verification",
6381 hex::encode(notify.key)
6382 );
6383 return Ok(());
6384 };
6385 match verification {
6386 Ok(status) if status.can_store() => {
6387 debug!(
6388 "PoP validated for paid notify key {}",
6389 hex::encode(notify.key)
6390 );
6391 }
6392 Ok(_) => {
6393 warn!(
6394 "Paid notify rejected: payment required for key {}",
6395 hex::encode(notify.key)
6396 );
6397 return Ok(());
6398 }
6399 Err(e) => {
6400 warn!(
6401 "PoP verification error for paid notify key {}: {e}",
6402 hex::encode(notify.key)
6403 );
6404 return Ok(());
6405 }
6406 }
6407
6408 if let Err(e) = paid_list.insert(¬ify.key).await {
6409 warn!("Failed to add paid notify key to PaidForList: {e}");
6410 }
6411
6412 Ok(())
6413}
6414
6415#[allow(clippy::too_many_arguments)]
6416async fn dispatch_neighbor_sync_request(
6417 source: PeerId,
6418 request: protocol::NeighborSyncRequest,
6419 ctx: &ReplicationMessageHandlerContext,
6420 is_bootstrapping: bool,
6421 my_commitment: Option<StorageCommitment>,
6422 request_id: u64,
6423 received_at: Instant,
6424 rr_message_id: Option<&str>,
6425) -> Result<()> {
6426 let guard = match admit_bounded_responder(
6427 &ctx.neighbor_sync_responder_admission_semaphore,
6428 &ctx.neighbor_sync_responder_inflight,
6429 &source,
6430 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6431 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6432 )
6433 .await
6434 {
6435 Ok(guard) => guard,
6436 Err(failure) => {
6437 audit_metrics::record_responder_admission_drop(
6438 ReplicationResponderClass::NeighborSync,
6439 failure.reason.into(),
6440 );
6441 warn!(
6442 responder_class = "neighbor_sync",
6443 source = %source,
6444 "Neighbor-sync response dropped at admission: {failure}"
6445 );
6446 return Ok(());
6447 }
6448 };
6449
6450 let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6451 let p2p_node = Arc::clone(&ctx.p2p_node);
6452 let storage = Arc::clone(&ctx.storage);
6453 let paid_list = Arc::clone(&ctx.paid_list);
6454 let queues = Arc::clone(&ctx.queues);
6455 let config = Arc::clone(&ctx.config);
6456 let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6457 let sync_history = Arc::clone(&ctx.sync_history);
6458 let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6459 let repair_proofs = Arc::clone(&ctx.repair_proofs);
6460 let request_timeout = ctx.config.verification_request_timeout;
6461 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6462 ctx.detached_task_tracker.spawn(async move {
6463 let _guard = guard;
6464 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6465 debug!(
6466 responder_class = "neighbor_sync",
6467 source = %source,
6468 "Neighbor-sync responder worker pool closed before dequeue"
6469 );
6470 return;
6471 };
6472 if request_is_stale(received_at, request_timeout) {
6473 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6474 debug!(
6475 responder_class = "neighbor_sync",
6476 source = %source,
6477 request_age_ms = received_at.elapsed().as_millis(),
6478 "Stale neighbor-sync request shed at dequeue"
6479 );
6480 return;
6481 }
6482 if let Err(e) = handle_neighbor_sync_request(
6483 &source,
6484 &request,
6485 &p2p_node,
6486 &storage,
6487 &paid_list,
6488 &queues,
6489 &config,
6490 is_bootstrapping,
6491 &bootstrap_state,
6492 &sync_history,
6493 &sync_cycle_epoch,
6494 &repair_proofs,
6495 my_commitment,
6496 request_id,
6497 rr_message_id.as_deref(),
6498 )
6499 .await
6500 {
6501 debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6502 }
6503 });
6504
6505 Ok(())
6506}
6507
6508#[allow(clippy::too_many_arguments)]
6509async fn handle_neighbor_sync_request(
6510 source: &PeerId,
6511 request: &protocol::NeighborSyncRequest,
6512 p2p_node: &Arc<P2PNode>,
6513 storage: &Arc<ChunkStore>,
6514 paid_list: &Arc<PaidList>,
6515 queues: &Arc<RwLock<ReplicationQueues>>,
6516 config: &ReplicationConfig,
6517 is_bootstrapping: bool,
6518 bootstrap_state: &Arc<RwLock<BootstrapState>>,
6519 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6520 sync_cycle_epoch: &Arc<RwLock<u64>>,
6521 repair_proofs: &Arc<RwLock<RepairProofs>>,
6522 my_commitment: Option<StorageCommitment>,
6523 request_id: u64,
6524 rr_message_id: Option<&str>,
6525) -> Result<()> {
6526 let self_id = *p2p_node.peer_id();
6527
6528 // No per-request hint count limit: the wire message size limit
6529 // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6530 // challenges, sync hints don't drive expensive computation — they just
6531 // enter the verification queue. A per-request limit here would break
6532 // bootstrap replication for newly-joined nodes with 0 stored chunks.
6533
6534 // Build response (outbound hints).
6535 let (response, sent_replica_hints, sender_in_rt) =
6536 neighbor_sync::handle_sync_request_with_proofs(
6537 source,
6538 request,
6539 p2p_node,
6540 storage,
6541 paid_list,
6542 config,
6543 is_bootstrapping,
6544 my_commitment.clone(),
6545 )
6546 .await;
6547
6548 // Send response.
6549 let response_sent = send_replication_response_checked(
6550 source,
6551 p2p_node,
6552 request_id,
6553 ReplicationMessageBody::NeighborSyncResponse(response),
6554 rr_message_id,
6555 None,
6556 )
6557 .await;
6558
6559 // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6560 if !sender_in_rt {
6561 return Ok(());
6562 }
6563
6564 // Update sync history for this peer before recording repair proofs so a
6565 // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6566 {
6567 let mut history = sync_history.write().await;
6568 let record = history.entry(*source).or_insert(PeerSyncRecord {
6569 last_sync: None,
6570 cycles_since_sync: 0,
6571 });
6572 record.last_sync = Some(Instant::now());
6573 record.cycles_since_sync = 0;
6574 }
6575
6576 if response_sent && !request.bootstrapping {
6577 record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6578 .await;
6579 }
6580
6581 // Admit inbound hints and queue for verification.
6582 let outcome = admit_and_queue_hints(
6583 &self_id,
6584 source,
6585 &request.replica_hints,
6586 &request.paid_hints,
6587 p2p_node,
6588 config,
6589 storage,
6590 paid_list,
6591 queues,
6592 )
6593 .await;
6594
6595 // Track discovered keys for bootstrap drain detection so that hints
6596 // admitted via inbound sync requests are not missed. Capacity-rejected
6597 // hints keep this source on the "not yet drained" list until its next
6598 // sync re-admits them; a clean cycle clears the source.
6599 if is_bootstrapping {
6600 let live_discovered = outcome.discovered.clone();
6601 let outcomes = [(*source, outcome)];
6602 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6603 }
6604
6605 Ok(())
6606}
6607
6608/// Test-only record of who *sent* a verification request covering a watched key.
6609///
6610/// The capacity gate's entire effect is a request that is never sent, and a
6611/// request that was not sent leaves no production counter anywhere — not on the
6612/// sender, whose traffic counters are process-global and so cannot separate one
6613/// node of a single-process testnet from another, and not on the responder,
6614/// which simply never hears from it. Recording who asked is what lets a test
6615/// tell "held the key back" apart from "probed the close group, was refused at
6616/// the dial, and then held the key back", which are otherwise identical from the
6617/// queue's point of view.
6618///
6619/// Arming replaces the previous watch, so the outer map holds exactly the keys
6620/// the current test named, and each inner map holds at most one entry per node
6621/// in the process. Nothing is recorded until a test arms it, and the armed path
6622/// costs one read lock on the sending side.
6623///
6624/// Counting is per key because a node that cannot write legitimately keeps
6625/// sending verification requests for keys it has not yet authorized — that is
6626/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
6627/// would assert something untrue.
6628///
6629/// It counts *send attempts*, deliberately, recorded immediately before the wire
6630/// call. A responder sheds requests at admission and as stale, so a
6631/// receiver-side count would report zero for probes that were really sent, and
6632/// an assertion that this node asked nobody would pass on the strength of the
6633/// receiver dropping the question. It is not proof of delivery: a send that
6634/// fails immediately, with no route or during shutdown, is still counted.
6635///
6636/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
6637/// MSRV.
6638#[cfg(any(test, feature = "test-utils"))]
6639type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
6640
6641#[cfg(any(test, feature = "test-utils"))]
6642static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
6643 std::sync::OnceLock::new();
6644
6645#[cfg(any(test, feature = "test-utils"))]
6646fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
6647 VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
6648}
6649
6650/// Test-only: start counting verification requests for `keys`, from zero.
6651///
6652/// Replaces any previous watch rather than adding to it, so the map is bounded
6653/// by the keys of the test that armed it last and nothing accumulates across a
6654/// process running many tests.
6655#[cfg(any(test, feature = "test-utils"))]
6656pub fn watch_verification_requests_for_test(keys: &[XorName]) {
6657 if let Ok(mut watch) = verification_watch().write() {
6658 watch.clear();
6659 for key in keys {
6660 watch.insert(*key, HashMap::new());
6661 }
6662 }
6663}
6664
6665/// Record that `requester` sent a verification request covering `keys`, for
6666/// whichever of them are watched. A poisoned lock is ignored rather than
6667/// propagated: this is observation for tests and must never change behaviour.
6668#[cfg(any(test, feature = "test-utils"))]
6669pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
6670 // Fast path under a read lock: with nothing watched — every production
6671 // build, and every test that did not ask — this is all the sender pays.
6672 match verification_watch().read() {
6673 Ok(watch) if watch.is_empty() => return,
6674 Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
6675 Ok(_) => {}
6676 Err(_) => return,
6677 }
6678 if let Ok(mut watch) = verification_watch().write() {
6679 for key in keys {
6680 if let Some(by_peer) = watch.get_mut(key) {
6681 *by_peer.entry(*requester).or_insert(0) += 1;
6682 }
6683 }
6684 }
6685}
6686
6687/// Test-only: how many times `requester` has asked this process about `key`.
6688/// Zero unless the key was registered with `watch_verification_requests_for_test`.
6689#[cfg(any(test, feature = "test-utils"))]
6690#[must_use]
6691pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
6692 verification_watch().read().map_or(0, |watch| {
6693 watch
6694 .get(key)
6695 .and_then(|by_peer| by_peer.get(requester))
6696 .copied()
6697 .unwrap_or(0)
6698 })
6699}
6700
6701async fn handle_verification_request(
6702 source: &PeerId,
6703 request: &protocol::VerificationRequest,
6704 storage: &Arc<ChunkStore>,
6705 paid_list: &Arc<PaidList>,
6706 p2p_node: &Arc<P2PNode>,
6707 request_id: u64,
6708 rr_message_id: Option<&str>,
6709) -> Result<()> {
6710 #[derive(Clone, Copy)]
6711 enum CachedPaidLookup {
6712 NotChecked,
6713 Checked(Option<bool>),
6714 }
6715
6716 #[derive(Clone, Copy)]
6717 struct CachedVerificationLookup {
6718 present: Option<bool>,
6719 paid: CachedPaidLookup,
6720 }
6721
6722 if verification_request_exceeds_limit(request.keys.len()) {
6723 warn!(
6724 "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6725 request.keys.len(),
6726 );
6727 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6728 return Ok(());
6729 }
6730
6731 let requested_keys = request.keys.as_slice();
6732
6733 if request.paid_list_check_indices.len() > request.keys.len() {
6734 warn!(
6735 "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6736 request.paid_list_check_indices.len(),
6737 request.keys.len(),
6738 );
6739 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6740 return Ok(());
6741 }
6742
6743 let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6744 let paid_check_set: HashSet<u32> = request
6745 .paid_list_check_indices
6746 .iter()
6747 .copied()
6748 .filter(|&idx| {
6749 if idx >= keys_len {
6750 warn!(
6751 "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6752 requested_keys.len(),
6753 );
6754 false
6755 } else {
6756 true
6757 }
6758 })
6759 .collect();
6760
6761 let mut results = Vec::with_capacity(requested_keys.len());
6762 let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6763 for (i, key) in requested_keys.iter().enumerate() {
6764 let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6765 let cached = lookup_cache.entry(*key).or_insert_with(|| {
6766 let present = match storage.exists(key) {
6767 Ok(present) => Some(present),
6768 Err(e) => {
6769 warn!(
6770 "Verification request from {source}: failed to check storage for {}: {e}",
6771 hex::encode(key)
6772 );
6773 None
6774 }
6775 };
6776 CachedVerificationLookup {
6777 present,
6778 paid: CachedPaidLookup::NotChecked,
6779 }
6780 });
6781
6782 if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6783 cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6784 Ok(paid) => Some(paid),
6785 Err(e) => {
6786 warn!(
6787 "Verification request from {source}: failed to check paid-list for {}: {e}",
6788 hex::encode(key)
6789 );
6790 None
6791 }
6792 });
6793 }
6794
6795 let paid = if needs_paid {
6796 match cached.paid {
6797 CachedPaidLookup::Checked(paid) => paid,
6798 CachedPaidLookup::NotChecked => None,
6799 }
6800 } else {
6801 None
6802 };
6803
6804 if cached.present.is_none() && paid.is_none() {
6805 continue;
6806 }
6807
6808 results.push(protocol::KeyVerificationResult {
6809 key: *key,
6810 present: cached.present.unwrap_or(false),
6811 paid,
6812 });
6813 }
6814
6815 send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6816
6817 Ok(())
6818}
6819
6820async fn dispatch_verification_request(
6821 source: PeerId,
6822 request: protocol::VerificationRequest,
6823 ctx: &ReplicationMessageHandlerContext,
6824 request_id: u64,
6825 received_at: Instant,
6826 rr_message_id: Option<&str>,
6827) -> Result<()> {
6828 let guard = match admit_bounded_responder(
6829 &ctx.verification_responder_admission_semaphore,
6830 &ctx.verification_responder_inflight,
6831 &source,
6832 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6833 VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6834 )
6835 .await
6836 {
6837 Ok(guard) => guard,
6838 Err(failure) => {
6839 audit_metrics::record_responder_admission_drop(
6840 ReplicationResponderClass::Verification,
6841 failure.reason.into(),
6842 );
6843 warn!(
6844 responder_class = "verification",
6845 source = %source,
6846 "Verification response dropped at admission: {failure}"
6847 );
6848 return Ok(());
6849 }
6850 };
6851
6852 let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6853 let storage = Arc::clone(&ctx.storage);
6854 let paid_list = Arc::clone(&ctx.paid_list);
6855 let p2p_node = Arc::clone(&ctx.p2p_node);
6856 let request_timeout = ctx.config.verification_request_timeout;
6857 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6858 ctx.detached_task_tracker.spawn(async move {
6859 let _guard = guard;
6860 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6861 debug!(
6862 responder_class = "verification",
6863 source = %source,
6864 "Verification responder worker pool closed before dequeue"
6865 );
6866 return;
6867 };
6868 if request_is_stale(received_at, request_timeout) {
6869 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6870 debug!(
6871 responder_class = "verification",
6872 source = %source,
6873 request_age_ms = received_at.elapsed().as_millis(),
6874 "Stale verification request shed at dequeue"
6875 );
6876 return;
6877 }
6878 if let Err(e) = handle_verification_request(
6879 &source,
6880 &request,
6881 &storage,
6882 &paid_list,
6883 &p2p_node,
6884 request_id,
6885 rr_message_id.as_deref(),
6886 )
6887 .await
6888 {
6889 debug!(source = %source, "Verification request handling failed: {e}");
6890 }
6891 });
6892
6893 Ok(())
6894}
6895
6896const fn verification_request_exceeds_limit(key_count: usize) -> bool {
6897 key_count > MAX_INCOMING_VERIFICATION_KEYS
6898}
6899
6900async fn send_verification_results(
6901 source: &PeerId,
6902 p2p_node: &Arc<P2PNode>,
6903 request_id: u64,
6904 results: Vec<protocol::KeyVerificationResult>,
6905 rr_message_id: Option<&str>,
6906) {
6907 send_replication_response(
6908 source,
6909 p2p_node,
6910 request_id,
6911 ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
6912 rr_message_id,
6913 )
6914 .await;
6915}
6916
6917async fn dispatch_fetch_request(
6918 source: PeerId,
6919 request: protocol::FetchRequest,
6920 ctx: &ReplicationMessageHandlerContext,
6921 request_id: u64,
6922 received_at: Instant,
6923 rr_message_id: Option<&str>,
6924) -> Result<()> {
6925 let guard = match admit_bounded_responder(
6926 &ctx.fetch_responder_admission_semaphore,
6927 &ctx.fetch_responder_inflight,
6928 &source,
6929 FETCH_RESPONDER_MAX_OUTSTANDING,
6930 FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6931 )
6932 .await
6933 {
6934 Ok(guard) => guard,
6935 Err(failure) => {
6936 audit_metrics::record_responder_admission_drop(
6937 ReplicationResponderClass::Fetch,
6938 failure.reason.into(),
6939 );
6940 warn!(
6941 responder_class = "fetch",
6942 source = %source,
6943 "Fetch response dropped at admission: {failure}"
6944 );
6945 return Ok(());
6946 }
6947 };
6948
6949 let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
6950 let storage = Arc::clone(&ctx.storage);
6951 let p2p_node = Arc::clone(&ctx.p2p_node);
6952 let request_timeout = ctx.config.fetch_request_timeout;
6953 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6954 ctx.detached_task_tracker.spawn(async move {
6955 let _guard = guard;
6956 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6957 debug!(
6958 responder_class = "fetch",
6959 source = %source,
6960 "Fetch responder worker pool closed before dequeue"
6961 );
6962 return;
6963 };
6964 if request_is_stale(received_at, request_timeout) {
6965 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
6966 debug!(
6967 responder_class = "fetch",
6968 source = %source,
6969 request_age_ms = received_at.elapsed().as_millis(),
6970 "Stale fetch request shed at dequeue"
6971 );
6972 return;
6973 }
6974 if let Err(e) = handle_fetch_request(
6975 &source,
6976 &request,
6977 &storage,
6978 &p2p_node,
6979 request_id,
6980 rr_message_id.as_deref(),
6981 )
6982 .await
6983 {
6984 debug!(source = %source, "Fetch request handling failed: {e}");
6985 }
6986 });
6987
6988 Ok(())
6989}
6990
6991fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
6992 received_at.elapsed() >= timeout
6993}
6994
6995/// How a fetch responder's answer is charged against its reputation.
6996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6997enum FetchFault {
6998 /// The peer does not hold a chunk it was expected to hold.
6999 ///
7000 /// This is the lane the release withholds, because a node part-way through moving
7001 /// off the legacy store answers exactly this way about chunks it has legitimately
7002 /// given up.
7003 UnheldChunk,
7004 /// The peer's own storage failed, or served bytes that no longer hash to their
7005 /// address.
7006 ///
7007 /// Never withheld. `FetchResponse::Error` has one producer, and it is the responder's
7008 /// storage read returning an error: an I/O fault, an exhausted descriptor table, or a
7009 /// failed integrity check. A peer that merely does not hold the chunk answers
7010 /// `NotFound` instead, so nothing about the migration produces this.
7011 ResponderFault,
7012}
7013
7014/// Classify a fetch response that did not carry the chunk.
7015///
7016/// `Success` yields `None`. Every other answer is a fault of one kind or the other, and
7017/// which kind decides whether this release charges for it.
7018fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
7019 match response {
7020 protocol::FetchResponse::Success { .. } => None,
7021 protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
7022 protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
7023 }
7024}
7025
7026/// Charge a fetch fault to the responder.
7027///
7028/// The only place the two kinds are treated differently. An unheld chunk goes through the
7029/// release switch, which is currently withholding it; a responder fault is charged
7030/// directly and is not affected by the switch at all.
7031async fn charge_fetch_fault(
7032 p2p_node: &Arc<P2PNode>,
7033 source: &PeerId,
7034 fault: FetchFault,
7035 lane: &'static str,
7036) {
7037 match fault {
7038 FetchFault::UnheldChunk => {
7039 config::penalise_unheld_close_group_chunk(
7040 p2p_node,
7041 source,
7042 lane,
7043 REPLICATION_TRUST_WEIGHT,
7044 )
7045 .await;
7046 }
7047 FetchFault::ResponderFault => {
7048 p2p_node
7049 .report_trust_event(
7050 source,
7051 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7052 )
7053 .await;
7054 }
7055 }
7056}
7057
7058/// Turn the responder's storage read into the answer it sends back.
7059///
7060/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7061/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7062/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7063/// Nothing about a node giving chunks up produces the second.
7064fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7065 match read {
7066 Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7067 Ok(None) => protocol::FetchResponse::NotFound { key },
7068 Err(e) => protocol::FetchResponse::Error {
7069 key,
7070 reason: format!("{e}"),
7071 },
7072 }
7073}
7074
7075async fn handle_fetch_request(
7076 source: &PeerId,
7077 request: &protocol::FetchRequest,
7078 storage: &Arc<ChunkStore>,
7079 p2p_node: &Arc<P2PNode>,
7080 request_id: u64,
7081 rr_message_id: Option<&str>,
7082) -> Result<()> {
7083 let response = fetch_response_for(request.key, storage.get(&request.key).await);
7084
7085 send_replication_response(
7086 source,
7087 p2p_node,
7088 request_id,
7089 ReplicationMessageBody::FetchResponse(response),
7090 rr_message_id,
7091 )
7092 .await;
7093
7094 Ok(())
7095}
7096
7097/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7098/// the prune-confirmation audit, which reuses the same wire message): reply with
7099/// per-key possession digests.
7100struct AuditResponderCompletion {
7101 response_kind: &'static str,
7102 sent: bool,
7103 processing: Duration,
7104 response_send: Duration,
7105}
7106
7107async fn handle_audit_challenge_msg(
7108 source: &PeerId,
7109 challenge: &protocol::AuditChallenge,
7110 storage: &Arc<ChunkStore>,
7111 p2p_node: &Arc<P2PNode>,
7112 is_bootstrapping: bool,
7113 reply: ReplyRoute<'_>,
7114) -> Result<AuditResponderCompletion> {
7115 #[allow(clippy::cast_possible_truncation)]
7116 let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7117 info!(
7118 "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7119 challenge.keys.len(),
7120 is_bootstrapping,
7121 reply.rr_message_id.is_some(),
7122 );
7123
7124 let processing_started = Instant::now();
7125 let response = audit::handle_audit_challenge(
7126 challenge,
7127 storage,
7128 p2p_node.peer_id(),
7129 is_bootstrapping,
7130 stored_chunks,
7131 )
7132 .await;
7133 let processing = processing_started.elapsed();
7134 let response_kind = audit_response_kind(&response);
7135
7136 let response_send_started = Instant::now();
7137 let sent = send_replication_response_checked(
7138 source,
7139 p2p_node,
7140 reply.request_id,
7141 ReplicationMessageBody::AuditResponse(response),
7142 reply.rr_message_id,
7143 Some(reply.protocol),
7144 )
7145 .await;
7146 let response_send = response_send_started.elapsed();
7147
7148 Ok(AuditResponderCompletion {
7149 response_kind,
7150 sent,
7151 processing,
7152 response_send,
7153 })
7154}
7155
7156#[allow(clippy::too_many_arguments)]
7157fn log_audit_responder_completion(
7158 metrics: &AuditResponderMetrics,
7159 source: PeerId,
7160 class: AuditResponderClass,
7161 kind: &'static str,
7162 challenge_id: u64,
7163 work_items: usize,
7164 response_kind: &'static str,
7165 sent: bool,
7166 received_at: Instant,
7167 worker_started: Instant,
7168 processing: Duration,
7169 response_send: Duration,
7170) {
7171 let dispatch = worker_started.saturating_duration_since(received_at);
7172 let total = received_at.elapsed();
7173 metrics.record_completed(source, processing, total, sent);
7174 if sent {
7175 info!(
7176 target: "ant_node::replication::audit_responder",
7177 event = "completed",
7178 kind,
7179 responder_class = class.as_str(),
7180 source = %source,
7181 challenge_id,
7182 work_items,
7183 response = response_kind,
7184 sent,
7185 dispatch_ms = dispatch.as_millis(),
7186 processing_ms = processing.as_millis(),
7187 response_send_ms = response_send.as_millis(),
7188 total_ms = total.as_millis(),
7189 "Audit responder request completed"
7190 );
7191 } else {
7192 warn!(
7193 target: "ant_node::replication::audit_responder",
7194 event = "completed",
7195 kind,
7196 responder_class = class.as_str(),
7197 source = %source,
7198 challenge_id,
7199 work_items,
7200 response = response_kind,
7201 sent,
7202 dispatch_ms = dispatch.as_millis(),
7203 processing_ms = processing.as_millis(),
7204 response_send_ms = response_send.as_millis(),
7205 total_ms = total.as_millis(),
7206 "Audit responder request completed without sending a reply"
7207 );
7208 }
7209}
7210
7211/// Where a reply goes and how it is addressed.
7212///
7213/// Grouped because the audit responder needs all three together and one of them
7214/// is not derivable from the body: during the rollout window a possession reply
7215/// may have to go out on the core id rather than its family's own (see
7216/// [`is_legacy_possession_challenge`]).
7217struct ReplyRoute<'a> {
7218 /// Correlates the reply with the challenge, at the replication layer.
7219 request_id: u64,
7220 /// Present when the challenge arrived over request-response, in which case
7221 /// the reply rides the same exchange back.
7222 rr_message_id: Option<&'a str>,
7223 /// The protocol id to answer on.
7224 protocol: &'static str,
7225}
7226
7227fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7228 match response {
7229 protocol::AuditResponse::Digests { .. } => "digests",
7230 protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7231 protocol::AuditResponse::Rejected { .. } => "rejected",
7232 }
7233}
7234
7235fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7236 match response {
7237 protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7238 protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7239 protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7240 }
7241}
7242
7243fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7244 match response {
7245 protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7246 protocol::SubtreeAuditResponse::Bootstrapping { .. }
7247 | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7248 }
7249}
7250
7251fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7252 match response {
7253 protocol::SubtreeSliceResponse::Items { .. } => "items",
7254 protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7255 protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7256 }
7257}
7258
7259fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7260 match response {
7261 protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7262 protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7263 }
7264}
7265
7266// ---------------------------------------------------------------------------
7267// Message sending helper
7268// ---------------------------------------------------------------------------
7269
7270/// Send a replication response message as a best-effort reply.
7271///
7272/// Encode and send failures are logged by the checked helper. Most response
7273/// paths do not need to branch on send success, so this wrapper keeps those
7274/// call sites explicit about their best-effort behavior.
7275async fn send_replication_response(
7276 peer: &PeerId,
7277 p2p_node: &Arc<P2PNode>,
7278 request_id: u64,
7279 body: ReplicationMessageBody,
7280 rr_message_id: Option<&str>,
7281) {
7282 let _ =
7283 send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7284 .await;
7285}
7286
7287/// Send a replication response message and report whether it was accepted.
7288///
7289/// Returns `true` after the message is encoded and accepted by the P2P send
7290/// path. Returns `false` after logging an encode or send failure. Repair-proof
7291/// recording uses this to avoid trusting hints that were not actually sent.
7292///
7293/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7294/// request-response path so saorsa-core can route it back to the caller's
7295/// `send_request` future. Otherwise it is sent as a plain message.
7296///
7297/// `protocol` overrides the id the body would route on by family. Exactly one
7298/// caller needs it: a possession challenge from a peer that predates the family
7299/// split has to be answered where it was asked (see
7300/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7301/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7302async fn send_replication_response_checked(
7303 peer: &PeerId,
7304 p2p_node: &Arc<P2PNode>,
7305 request_id: u64,
7306 body: ReplicationMessageBody,
7307 rr_message_id: Option<&str>,
7308 protocol: Option<&'static str>,
7309) -> bool {
7310 let msg = ReplicationMessage { request_id, body };
7311 let encoded = match msg.encode() {
7312 Ok(data) => data,
7313 Err(e) => {
7314 warn!("Failed to encode replication response: {e}");
7315 return false;
7316 }
7317 };
7318 // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7319 // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7320 // included for completeness. Other response variants (verification/audit/
7321 // commitment) are intentionally excluded — the round-2 audit reply is now a
7322 // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7323 if matches!(
7324 msg.body,
7325 ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7326 ) {
7327 protocol::record_served(peer, encoded.len());
7328 }
7329 let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7330 let result = if let Some(msg_id) = rr_message_id {
7331 p2p_node
7332 .send_response(peer, protocol, msg_id, encoded)
7333 .await
7334 } else {
7335 p2p_node.send_message(peer, protocol, encoded, &[]).await
7336 };
7337 if let Err(e) = result {
7338 debug!("Failed to send replication response to {peer}: {e}");
7339 return false;
7340 }
7341 true
7342}
7343
7344async fn record_sent_replica_hints(
7345 peer: &PeerId,
7346 hints: &[neighbor_sync::SentReplicaHint],
7347 repair_proofs: &Arc<RwLock<RepairProofs>>,
7348 sync_cycle_epoch: &Arc<RwLock<u64>>,
7349) {
7350 if hints.is_empty() {
7351 return;
7352 }
7353
7354 let hinted_at_epoch = *sync_cycle_epoch.read().await;
7355 let mut proofs = repair_proofs.write().await;
7356 for hint in hints {
7357 if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7358 debug!(
7359 "Recorded repair hint proof for peer {peer} and key {}",
7360 hex::encode(hint.key)
7361 );
7362 }
7363 }
7364}
7365
7366// ---------------------------------------------------------------------------
7367// Neighbor sync round
7368// ---------------------------------------------------------------------------
7369
7370/// Run one neighbor sync round.
7371#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7372async fn run_neighbor_sync_round(
7373 p2p_node: &Arc<P2PNode>,
7374 storage: &Arc<ChunkStore>,
7375 paid_list: &Arc<PaidList>,
7376 queues: &Arc<RwLock<ReplicationQueues>>,
7377 config: &ReplicationConfig,
7378 sync_state: &Arc<RwLock<NeighborSyncState>>,
7379 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7380 sync_cycle_epoch: &Arc<RwLock<u64>>,
7381 repair_proofs: &Arc<RwLock<RepairProofs>>,
7382 is_bootstrapping: &Arc<RwLock<bool>>,
7383 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7384 commitment_state: &Arc<ResponderCommitmentState>,
7385 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7386 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7387 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7388 audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7389 gossip_audit: &GossipAuditTrigger,
7390) {
7391 let self_id = *p2p_node.peer_id();
7392 let bootstrapping = *is_bootstrapping.read().await;
7393
7394 // Check if cycle is complete; start new one if needed.
7395 // We check under a read lock, then release it before the expensive
7396 // prune pass and DHT snapshot so other tasks are not starved.
7397 let cycle_complete = sync_state.read().await.is_cycle_complete();
7398 if cycle_complete {
7399 // A completed local neighbor-sync cycle advances the epoch component
7400 // of repair-proof maturity. The per-key wall-clock minimum age is
7401 // checked when audits are selected.
7402 {
7403 let mut history = sync_history.write().await;
7404 for record in history.values_mut() {
7405 record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7406 }
7407 }
7408 {
7409 let mut epoch = sync_cycle_epoch.write().await;
7410 *epoch = epoch.saturating_add(1);
7411 }
7412
7413 // Post-cycle pruning (Section 11) — runs without holding sync_state.
7414 // Prune candidacy is unconditional once the hysteresis elapses;
7415 // bootstrap state only defers the remote prune-confirmation audits
7416 // until bootstrap has drained.
7417 let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7418 pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7419 self_id: &self_id,
7420 storage,
7421 paid_list,
7422 p2p_node,
7423 config,
7424 sync_state,
7425 repair_proofs,
7426 allow_remote_prune_audits,
7427 commitment_state: Some(commitment_state),
7428 audit_challenge_coordinator,
7429 })
7430 .await;
7431
7432 // Take fresh close-neighbor snapshot (DHT query, no lock held).
7433 let neighbors =
7434 neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7435 .await;
7436
7437 // Now re-acquire write lock and re-check before swapping cycle.
7438 let mut state = sync_state.write().await;
7439 if state.is_cycle_complete() {
7440 // Preserve cooldown and bootstrap-claim tracking across cycles.
7441 // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7442 // would reset the abuse detection timer every cycle.
7443 let old_sync_times = std::mem::take(&mut state.last_sync_times);
7444 let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7445 let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7446 let old_prune_cursor = state.prune_cursor;
7447 *state = NeighborSyncState::new_cycle(neighbors);
7448 state.last_sync_times = old_sync_times;
7449 state.bootstrap_claims = old_bootstrap_claims;
7450 state.bootstrap_claim_history = old_bootstrap_claim_history;
7451 state.prune_cursor = old_prune_cursor;
7452 }
7453 }
7454
7455 // Select batch of peers.
7456 let batch = {
7457 let mut state = sync_state.write().await;
7458 neighbor_sync::select_sync_batch(
7459 &mut state,
7460 config.neighbor_sync_peer_count,
7461 config.neighbor_sync_cooldown,
7462 )
7463 };
7464
7465 if batch.is_empty() {
7466 return;
7467 }
7468
7469 debug!("Neighbor sync: syncing with {} peers", batch.len());
7470
7471 // Snapshot our current commitment once per round so all peers in
7472 // this batch see the same thing (gossip is the responder's attestation;
7473 // same value across the batch is fine and reduces RwLock churn). Atomically
7474 // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7475 // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7476 let gossiped = commitment_state.current_for_gossip();
7477 // The hash actually put on the wire, captured with the payload. A rotation later in
7478 // the round must not let a reply be credited to a root the peer never saw.
7479 let gossiped_hash = gossiped.as_ref().map(|b| b.hash());
7480 let my_commitment = gossiped.map(|b| b.commitment().clone());
7481
7482 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7483 &batch,
7484 storage,
7485 paid_list,
7486 p2p_node,
7487 config.close_group_size,
7488 config.paid_list_close_group_size,
7489 )
7490 .await;
7491
7492 // Sync with each peer in the batch.
7493 for peer in &batch {
7494 let hints = hints_by_peer.remove(peer).unwrap_or_default();
7495 let outcome = neighbor_sync::sync_with_peer_with_hints(
7496 peer,
7497 p2p_node,
7498 config,
7499 bootstrapping,
7500 hints,
7501 my_commitment.clone(),
7502 )
7503 .await;
7504
7505 if let Some(outcome) = outcome {
7506 // The peer answered, so the request that carried our commitment root arrived.
7507 // That is proof of delivery rather than proof of emission, and the storage
7508 // migration will not let a node give anything up until its close group has
7509 // actually seen the reduced root.
7510 if let Some(hash) = gossiped_hash {
7511 commitment_state.note_commitment_delivered(*peer, hash);
7512 }
7513 handle_sync_response(
7514 &self_id,
7515 peer,
7516 &outcome.response,
7517 &outcome.sent_replica_hints,
7518 p2p_node,
7519 config,
7520 bootstrapping,
7521 bootstrap_state,
7522 storage,
7523 paid_list,
7524 queues,
7525 sync_state,
7526 sync_history,
7527 sync_cycle_epoch,
7528 repair_proofs,
7529 last_commitment_by_peer,
7530 ever_capable_peers,
7531 sig_verify_attempts,
7532 gossip_audit,
7533 )
7534 .await;
7535 } else {
7536 // Sync failed -- remove peer and try to fill slot.
7537 let replacement = {
7538 let mut state = sync_state.write().await;
7539 neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7540 };
7541
7542 // Attempt sync with the replacement peer (if one was found).
7543 if let Some(replacement_peer) = replacement {
7544 let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7545 std::slice::from_ref(&replacement_peer),
7546 storage,
7547 paid_list,
7548 p2p_node,
7549 config.close_group_size,
7550 config.paid_list_close_group_size,
7551 )
7552 .await;
7553 let hints = replacement_hints
7554 .remove(&replacement_peer)
7555 .unwrap_or_default();
7556 let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7557 &replacement_peer,
7558 p2p_node,
7559 config,
7560 bootstrapping,
7561 hints,
7562 my_commitment.clone(),
7563 )
7564 .await;
7565
7566 if let Some(outcome) = replacement_outcome {
7567 // Same payload, same round trip, same proof: a reply can only come
7568 // back if the request carrying the root reached this peer. Omitting it
7569 // here made the counter under-report on any node whose primary syncs
7570 // often fall through to a replacement, which is exactly the node most
7571 // likely to be short of disk, and stalled its migration indefinitely.
7572 if let Some(hash) = gossiped_hash {
7573 commitment_state.note_commitment_delivered(replacement_peer, hash);
7574 }
7575 handle_sync_response(
7576 &self_id,
7577 &replacement_peer,
7578 &outcome.response,
7579 &outcome.sent_replica_hints,
7580 p2p_node,
7581 config,
7582 bootstrapping,
7583 bootstrap_state,
7584 storage,
7585 paid_list,
7586 queues,
7587 sync_state,
7588 sync_history,
7589 sync_cycle_epoch,
7590 repair_proofs,
7591 last_commitment_by_peer,
7592 ever_capable_peers,
7593 sig_verify_attempts,
7594 gossip_audit,
7595 )
7596 .await;
7597 }
7598 }
7599 }
7600 }
7601}
7602
7603/// Process a successful neighbor sync response: record the sync, check for
7604/// bootstrap claim abuse, and admit inbound hints.
7605#[allow(clippy::too_many_arguments)]
7606async fn handle_sync_response(
7607 self_id: &PeerId,
7608 peer: &PeerId,
7609 resp: &NeighborSyncResponse,
7610 sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7611 p2p_node: &Arc<P2PNode>,
7612 config: &ReplicationConfig,
7613 bootstrapping: bool,
7614 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7615 storage: &Arc<ChunkStore>,
7616 paid_list: &Arc<PaidList>,
7617 queues: &Arc<RwLock<ReplicationQueues>>,
7618 sync_state: &Arc<RwLock<NeighborSyncState>>,
7619 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7620 sync_cycle_epoch: &Arc<RwLock<u64>>,
7621 repair_proofs: &Arc<RwLock<RepairProofs>>,
7622 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7623 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7624 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7625 gossip_audit: &GossipAuditTrigger,
7626) {
7627 // Ingest the peer's commitment if they piggybacked one on the response.
7628 // Same verification as the request path (peer-id binding + signature);
7629 // forged commitments are dropped at the edge. A *changed* commitment here
7630 // is a gossip-audit trigger just like on the request path — so a peer that
7631 // only ever answers sync (never initiates) is still audited (ADR-0002).
7632 if let Some(target) = ingest_peer_commitment(
7633 peer,
7634 resp.commitment.as_ref(),
7635 p2p_node,
7636 last_commitment_by_peer,
7637 ever_capable_peers,
7638 sig_verify_attempts,
7639 )
7640 .await
7641 {
7642 maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7643 }
7644
7645 // Record successful sync.
7646 {
7647 let mut state = sync_state.write().await;
7648 neighbor_sync::record_successful_sync(&mut state, peer);
7649 }
7650 {
7651 let mut history = sync_history.write().await;
7652 let record = history.entry(*peer).or_insert(PeerSyncRecord {
7653 last_sync: None,
7654 cycles_since_sync: 0,
7655 });
7656 record.last_sync = Some(Instant::now());
7657 record.cycles_since_sync = 0;
7658 }
7659
7660 // Process inbound hints from response (skip if peer is bootstrapping).
7661 if resp.bootstrapping {
7662 // Gap 6: BootstrapClaimAbuse grace period enforcement.
7663 // Separate state mutation from network I/O to avoid holding the
7664 // write lock across report_trust_event.
7665 let should_report = {
7666 let now = Instant::now();
7667 let mut state = sync_state.write().await;
7668 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7669 BootstrapClaimObservation::WithinGrace { .. } => false,
7670 BootstrapClaimObservation::PastGrace { first_seen } => {
7671 warn!(
7672 "Peer {peer} has been claiming bootstrap for {:?}, \
7673 exceeding grace period of {:?} — reporting abuse",
7674 now.duration_since(first_seen),
7675 config.bootstrap_claim_grace_period,
7676 );
7677 true
7678 }
7679 BootstrapClaimObservation::Repeated { first_seen } => {
7680 warn!(
7681 "Peer {peer} repeated bootstrap claim after previously stopping; \
7682 first claim was {:?} ago — reporting abuse",
7683 now.duration_since(first_seen),
7684 );
7685 true
7686 }
7687 }
7688 };
7689 if should_report {
7690 p2p_node
7691 .report_trust_event(
7692 peer,
7693 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7694 )
7695 .await;
7696 }
7697 } else {
7698 // Peer is not claiming bootstrap; clear active claim while retaining
7699 // history so the peer cannot start a second grace window later.
7700 {
7701 let mut state = sync_state.write().await;
7702 state.clear_active_bootstrap_claim(peer);
7703 }
7704 record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7705 let outcome = admit_and_queue_hints(
7706 self_id,
7707 peer,
7708 &resp.replica_hints,
7709 &resp.paid_hints,
7710 p2p_node,
7711 config,
7712 storage,
7713 paid_list,
7714 queues,
7715 )
7716 .await;
7717
7718 // Track discovered keys for bootstrap drain detection so that hints
7719 // admitted via regular neighbor sync are not missed. Capacity-
7720 // rejected hints keep this source on the "not yet drained" list
7721 // until its next sync replays them; a clean cycle clears it.
7722 if bootstrapping {
7723 let live_discovered = outcome.discovered.clone();
7724 let outcomes = [(*peer, outcome)];
7725 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7726 .await;
7727 }
7728 }
7729}
7730
7731/// Admit hints and queue them for verification, returning newly-discovered keys.
7732///
7733/// Shared by neighbor-sync request handling, response handling, and bootstrap
7734/// sync so that admission + queueing logic lives in one place.
7735#[allow(clippy::too_many_arguments)]
7736/// Outcome of [`admit_and_queue_hints`].
7737///
7738/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7739/// available; that source is kept outstanding until it re-hints. `displaced`
7740/// tracks older borrowed hints reclaimed for another sender; only the key is
7741/// dropped from bootstrap tracking — the former owner's standing is untouched
7742/// (see [`publish_bootstrap_admission_outcomes`]).
7743struct AdmissionOutcome {
7744 discovered: HashSet<XorName>,
7745 capacity_rejected_count: usize,
7746 displaced: Vec<CapacityDisplacement>,
7747}
7748
7749/// Publish one atomic admission unit into bootstrap drain accounting.
7750///
7751/// Only sources that were themselves capacity-rejected are kept outstanding.
7752/// A fairness displacement forfeits the displaced *key* but never stamps its
7753/// former owner: reclaiming a borrowed slot is this node's own fairness
7754/// decision, so charging it to the victim would let a sustained flooder wedge
7755/// our bootstrap drain open through an unrelated honest peer. Clean sources
7756/// are cleared only after every outcome in the unit is known, so peer
7757/// iteration order cannot falsely clear a rejection recorded later in the same
7758/// bootstrap batch.
7759async fn publish_bootstrap_admission_outcomes(
7760 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7761 outcomes: &[(PeerId, AdmissionOutcome)],
7762 live_discovered: &HashSet<XorName>,
7763) {
7764 let mut rejected_sources = HashSet::new();
7765 let mut clean_sources = HashSet::new();
7766 let mut displaced_keys = HashSet::new();
7767
7768 for (source, outcome) in outcomes {
7769 if outcome.capacity_rejected_count > 0 {
7770 rejected_sources.insert(*source);
7771 } else {
7772 clean_sources.insert(*source);
7773 }
7774 // Only the *key* of a fairness displacement is forfeited here, never
7775 // its owner's standing. Reclaiming a borrowed slot is our own fairness
7776 // decision, not a failure by the peer that held it: stamping the victim
7777 // would let a sustained flooder block our bootstrap drain through an
7778 // unrelated honest peer that never overflowed us. The displaced key
7779 // falls to the same post-bootstrap neighbor-sync and audit/repair
7780 // recovery path that TTL expiry already relies on.
7781 for displacement in &outcome.displaced {
7782 displaced_keys.insert(displacement.key);
7783 }
7784 }
7785 clean_sources.retain(|source| !rejected_sources.contains(source));
7786
7787 let now = Instant::now();
7788 let mut state = bootstrap_state.write().await;
7789 for key in displaced_keys {
7790 state.remove_key(&key);
7791 }
7792 state.pending_keys.extend(live_discovered);
7793 for source in clean_sources {
7794 state.capacity_rejected_sources.remove(&source);
7795 }
7796 for source in rejected_sources {
7797 // First-seen: a source that keeps overflowing us must not keep its own
7798 // record fresh, or bootstrap never drains and auditing stays off.
7799 state.note_capacity_rejected(source, now);
7800 }
7801}
7802
7803#[allow(clippy::too_many_arguments)]
7804async fn admit_and_queue_hints(
7805 self_id: &PeerId,
7806 source_peer: &PeerId,
7807 replica_hints: &[XorName],
7808 paid_hints: &[XorName],
7809 p2p_node: &Arc<P2PNode>,
7810 config: &ReplicationConfig,
7811 storage: &Arc<ChunkStore>,
7812 paid_list: &Arc<PaidList>,
7813 queues: &Arc<RwLock<ReplicationQueues>>,
7814) -> AdmissionOutcome {
7815 let pending_keys: HashSet<XorName> = {
7816 let q = queues.read().await;
7817 q.pending_keys().into_iter().collect()
7818 };
7819
7820 let admitted = admission::admit_hints(
7821 self_id,
7822 replica_hints,
7823 paid_hints,
7824 p2p_node,
7825 config,
7826 storage,
7827 paid_list,
7828 &pending_keys,
7829 )
7830 .await;
7831
7832 let mut q = queues.write().await;
7833 queue_admitted_hints(source_peer, admitted, storage, &mut q)
7834}
7835
7836fn queue_admitted_hints(
7837 source_peer: &PeerId,
7838 admitted: admission::AdmissionResult,
7839 storage: &ChunkStore,
7840 q: &mut ReplicationQueues,
7841) -> AdmissionOutcome {
7842 let mut discovered = HashSet::new();
7843 let mut capacity_rejected_count: usize = 0;
7844 let mut displaced = Vec::new();
7845 let now = Instant::now();
7846
7847 for key in admitted.replica_keys {
7848 if !storage.exists(&key).unwrap_or(false) {
7849 let result = q.add_pending_verify(
7850 key,
7851 VerificationEntry {
7852 state: VerificationState::PendingVerify,
7853 verified_sources: Vec::new(),
7854 tried_sources: HashSet::new(),
7855 created_at: now,
7856 next_verify_at: now,
7857 hint_sources: HashSet::from([*source_peer]),
7858 // Non-empty: this peer claimed possession, so it is a
7859 // fetch-source candidate. Derives HintPipeline::Replica.
7860 replica_hint_sources: HashSet::from([*source_peer]),
7861 unresolved_retries: 0,
7862 no_holder_reported: false,
7863 },
7864 );
7865 match result {
7866 crate::replication::scheduling::AdmissionResult::Admitted => {
7867 discovered.insert(key);
7868 }
7869 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7870 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7871 capacity_rejected_count += 1;
7872 }
7873 }
7874 }
7875 }
7876
7877 for key in admitted.paid_only_keys {
7878 let result = q.add_pending_verify(
7879 key,
7880 VerificationEntry {
7881 state: VerificationState::PendingVerify,
7882 verified_sources: Vec::new(),
7883 tried_sources: HashSet::new(),
7884 created_at: now,
7885 next_verify_at: now,
7886 hint_sources: HashSet::from([*source_peer]),
7887 // Empty: a paid hint makes no possession claim, so this peer is
7888 // not a fetch source. Derives HintPipeline::PaidOnly.
7889 replica_hint_sources: HashSet::new(),
7890 unresolved_retries: 0,
7891 no_holder_reported: false,
7892 },
7893 );
7894 match result {
7895 crate::replication::scheduling::AdmissionResult::Admitted => {
7896 discovered.insert(key);
7897 }
7898 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7899 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7900 capacity_rejected_count += 1;
7901 }
7902 }
7903 }
7904
7905 if capacity_rejected_count > 0 {
7906 debug!(
7907 "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
7908 rejected at queue capacity; source will need to re-hint after pending_verify drains"
7909 );
7910 }
7911
7912 displaced.extend(q.take_capacity_displacements());
7913
7914 AdmissionOutcome {
7915 discovered,
7916 capacity_rejected_count,
7917 displaced,
7918 }
7919}
7920
7921// ---------------------------------------------------------------------------
7922// Verification cycle
7923// ---------------------------------------------------------------------------
7924
7925/// Run one verification cycle: process pending keys through quorum checks.
7926#[allow(clippy::too_many_lines)]
7927async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
7928 let cycle_started = Instant::now();
7929 let VerificationCycleContext {
7930 p2p_node,
7931 paid_list,
7932 storage,
7933 queues,
7934 config,
7935 bootstrap_state,
7936 is_bootstrapping,
7937 bootstrap_complete_notify,
7938 last_commitment_by_peer,
7939 ever_capable_peers,
7940 recent_provers,
7941 } = ctx;
7942
7943 // Self-heal the bootstrap drain before any early-return below: abandoned
7944 // capacity-rejection records must expire, and a drain condition that
7945 // became true without a triggering event must still be observed. Pending
7946 // peer requests legitimately block the drain check itself, but not this.
7947 expire_and_recheck_bootstrap_drain(
7948 bootstrap_state,
7949 queues,
7950 is_bootstrapping,
7951 bootstrap_complete_notify,
7952 config.capacity_rejected_max_age(),
7953 )
7954 .await;
7955
7956 // Bootstrap admits one concurrent neighbor batch as an atomic source
7957 // aggregation unit. Do not select newly queued keys until that batch's
7958 // hints and drain accounting have both been published.
7959 if bootstrap_state.read().await.pending_peer_requests > 0 {
7960 return;
7961 }
7962
7963 // Evict stale entries that have been pending too long (e.g. unreachable
7964 // verification targets during a network partition).
7965 let stale_pending_keys = {
7966 let mut q = queues.write().await;
7967 q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
7968 };
7969 if !stale_pending_keys.is_empty() {
7970 update_bootstrap_after_verification(
7971 &stale_pending_keys,
7972 bootstrap_state,
7973 queues,
7974 is_bootstrapping,
7975 bootstrap_complete_notify,
7976 )
7977 .await;
7978 }
7979
7980 let pending_keys = {
7981 let mut q = queues.write().await;
7982 // Re-check while holding the queue write lock used by fair selection.
7983 // This closes the race
7984 // where a bootstrap batch starts after the early check: the batch
7985 // cannot publish its hints under the queue write lock until this
7986 // selection either returns or declines to run.
7987 if bootstrap_state.read().await.pending_peer_requests > 0 {
7988 return;
7989 }
7990 q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
7991 };
7992
7993 if pending_keys.is_empty() {
7994 return;
7995 }
7996 let initial_pending_count = pending_keys.len();
7997
7998 // Capacity verdict for this cycle — the same pre-check the PUT handler and
7999 // the fresh-offer path already run (V2-411), read once and reused below.
8000 //
8001 // It gates only the two steps that exist to enable a fetch: the presence
8002 // probe that discovers holders, and the promotion that queues the download.
8003 // Everything a cycle does that does not need a local write still runs on a
8004 // full node — the local paid-list fast path, `PaidForList` convergence
8005 // through the quorum round, and the terminal checks that retire a key this
8006 // node already holds or is no longer admitted for. Gating earlier than this
8007 // would stop a full node learning which of its keys were paid for, and
8008 // would strand keys that should have retired, which keeps bootstrap drain
8009 // pending and audits disabled until stale eviction.
8010 // Only a *full* disk is a standing condition worth minutes of backoff. A
8011 // failed `statvfs` says nothing about available space and may have cleared
8012 // by the next cycle, so it is treated as writable here and left to the
8013 // pre-check at the dial, which queries again and may well permit the write.
8014 let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8015 // Counted per gate rather than combined. `local_paid_probe` below counts
8016 // probes actually sent, so it reads zero once the first gate fires; keeping
8017 // the two deferral counts apart is what lets an operator see which branch a
8018 // full node's keys are taking without adding a code path to find out.
8019 let mut capacity_deferred_probe = 0usize;
8020 let mut capacity_deferred_promote = 0usize;
8021
8022 let self_id = *p2p_node.peer_id();
8023
8024 // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8025 // step 4). Paid-list membership settles *validity* — the key is known-paid,
8026 // so no quorum round is needed. It says nothing about whether we must hold
8027 // the bytes; that is decided below.
8028 let mut local_paid_keys = Vec::new();
8029 let mut keys_needing_network = Vec::new();
8030 let mut terminal_keys: Vec<XorName> = Vec::new();
8031 {
8032 let mut q = queues.write().await;
8033 for key in &pending_keys {
8034 if paid_list.contains(key).unwrap_or(false) {
8035 if q.set_pending_state(key, VerificationState::PaidListVerified) {
8036 local_paid_keys.push(*key);
8037 }
8038 } else {
8039 keys_needing_network.push(*key);
8040 }
8041 }
8042 }
8043
8044 // Storage responsibility is a live routing question, decided identically
8045 // for every known-paid key regardless of how the advertising peer labelled
8046 // its hint — a replica hint is a possession *claim* by the sender, never
8047 // permission for us to store. Held outside the queue lock: `is_responsible`
8048 // awaits into the DHT manager.
8049 let mut local_paid_presence_probe_keys = Vec::new();
8050 if !local_paid_keys.is_empty() {
8051 let mut terminal_paid = Vec::new();
8052 for key in local_paid_keys {
8053 if storage.exists(&key).unwrap_or(false) {
8054 terminal_paid.push(key);
8055 } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8056 // We carry storage responsibility and lack the bytes. The
8057 // presence probe below discovers holders to fetch from; it is
8058 // source discovery, not re-verification.
8059 local_paid_presence_probe_keys.push(key);
8060 } else {
8061 terminal_paid.push(key);
8062 }
8063 }
8064
8065 if !terminal_paid.is_empty() {
8066 let mut q = queues.write().await;
8067 for key in terminal_paid {
8068 q.remove_pending(&key);
8069 terminal_keys.push(key);
8070 }
8071 }
8072
8073 // Capacity gate, first of two. Everything above this point has already
8074 // run: authorization succeeded via the local `PaidForList` hit, and the
8075 // keys that should retire (already held, or no longer storage-admitted)
8076 // have retired. What is left is a probe whose only purpose is finding a
8077 // holder to download from, and this node cannot write what it would
8078 // download.
8079 if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8080 let mut q = queues.write().await;
8081 for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8082 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8083 capacity_deferred_probe += 1;
8084 }
8085 }
8086 }
8087 }
8088
8089 let local_paid_probe_count = local_paid_presence_probe_keys.len();
8090 let keys_needing_network_count = keys_needing_network.len();
8091 // Keys this cycle put back because no peer claimed possession. Reported in
8092 // aggregate below; the per-key line is warned once per entry, not per retry.
8093 let mut no_holder_deferrals = 0usize;
8094
8095 // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8096 // step 4, authorization succeeds immediately; run a presence-only probe
8097 // to find any holder we can fetch from.
8098 if !local_paid_presence_probe_keys.is_empty() {
8099 let targets = quorum::compute_presence_targets(
8100 &local_paid_presence_probe_keys,
8101 p2p_node,
8102 config,
8103 &self_id,
8104 )
8105 .await;
8106 let evidence = quorum::run_verification_round(
8107 &local_paid_presence_probe_keys,
8108 &targets,
8109 p2p_node,
8110 config,
8111 )
8112 .await;
8113
8114 let mut q = queues.write().await;
8115 for key in local_paid_presence_probe_keys {
8116 if storage.exists(&key).unwrap_or(false) {
8117 q.remove_pending(&key);
8118 terminal_keys.push(key);
8119 continue;
8120 }
8121 let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8122 quorum::present_sources_for_key(&key, ev, &targets)
8123 });
8124 if let Some(entry) = q.get_pending(&key) {
8125 add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8126 }
8127 if sources.is_empty() {
8128 no_holder_deferrals += 1;
8129 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8130 let first_report = q.claim_no_holder_report(&key);
8131 report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8132 } else {
8133 // A holder answered, so whatever came before is not a run of
8134 // consecutive failures any more. Clear before promoting: if the
8135 // fetch queue is full the entry stays pending, and it must not
8136 // carry the old backoff.
8137 q.clear_unresolved(&key);
8138 let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8139 // Atomic remove+enqueue: if fetch_queue is at capacity, the
8140 // pending entry is preserved and retried next cycle (no
8141 // silent drop of verified replica-repair work).
8142 let _ = q.promote_pending_to_fetch(key, distance, sources);
8143 }
8144 }
8145 }
8146
8147 // Steps 2-5: Network verification (skipped if all keys resolved locally).
8148 if !keys_needing_network.is_empty() {
8149 // Step 2: Compute targets and run network verification round.
8150 let targets =
8151 quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8152 .await;
8153
8154 let evidence =
8155 quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8156
8157 // Step 3: Evaluate results — collect outcomes without holding the write
8158 // lock across paid-list I/O.
8159 //
8160 // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8161 // table and recent_provers cache up front so the synchronous
8162 // evaluate_key_evidence_with_holder_check predicate can consult
8163 // them without awaiting. The predicate downgrades a Present
8164 // claim to Unresolved unless the peer is credited for that key.
8165 // Snapshot per-peer commitment data. We need two views:
8166 // - `commitment_by_peer_snapshot`: peers that currently have
8167 // a verified commitment record on file (used to look up
8168 // their current hash).
8169 // - `capable_peer_snapshot`: the sticky "ever v12-capable"
8170 // set. Sourced from a separate set rather than the
8171 // commitment map so eviction (PeerRemoved cleanup, sybil
8172 // cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8173 // a previously-v12 peer to "legacy" credit-unconditionally.
8174 // Legacy / pre-v12 peers that have never sent a commitment
8175 // remain absent from the set and are credited via the
8176 // legacy path so mixed-version networks stay live.
8177 let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8178 let map = last_commitment_by_peer.read().await;
8179 map.iter()
8180 // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8181 // of every peer's ~5 KiB commitment.
8182 .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8183 .collect()
8184 };
8185 let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8186 // Take a full snapshot of recent_provers under the read lock,
8187 // then release. The cache is bounded (16/key × keys), so the
8188 // clone is cheap.
8189 let provers_snapshot = recent_provers.read().await.clone();
8190 // For the replica-fetch path, we need to know whether THIS
8191 // node already holds the key being verified. The v12 §6
8192 // holder-credit gate is meant to prevent uncredited Present
8193 // claims from contributing to paid-list / reward quorum for
8194 // keys we DO hold (and could audit ourselves). For keys we
8195 // are trying to FETCH (i.e. not in local storage), there is
8196 // no possible local audit credit, and gating the presence
8197 // quorum on credit would deadlock replica-repair in a
8198 // fully v12-capable close group.
8199 let mut locally_held: HashSet<XorName> = HashSet::new();
8200 for key in &keys_needing_network {
8201 if storage.exists(key).unwrap_or(false) {
8202 locally_held.insert(*key);
8203 }
8204 }
8205 let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8206 if !locally_held.contains(key) {
8207 // Replica-fetch path: we don't hold this key, so we
8208 // cannot have collected audit credit for it. Trust
8209 // Present claims to drive fetch-source promotion;
8210 // chunk-PUT payment_verifier is the security backstop
8211 // when the bytes actually arrive.
8212 return true;
8213 }
8214 if !capable_peer_snapshot.contains(peer) {
8215 // Pre-v12 / legacy peer that has never gossiped a
8216 // commitment. The v12 §6 holder-eligibility check
8217 // doesn't apply: their Present evidence comes through
8218 // the legacy path and we credit it unconditionally
8219 // so a mixed-version network stays live during
8220 // transition.
8221 return true;
8222 }
8223 let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8224 // Peer is commitment_capable (sticky) but currently
8225 // has no live commitment record on file (e.g. their
8226 // last gossip was evicted from the LRU cache, or it
8227 // failed verification). Withhold credit until they
8228 // re-prove storage under a fresh commitment.
8229 return false;
8230 };
8231 provers_snapshot.is_credited_holder(key, peer, hash)
8232 };
8233
8234 let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8235 {
8236 let q = queues.read().await;
8237 for key in &keys_needing_network {
8238 let Some(ev) = evidence.get(key) else {
8239 continue;
8240 };
8241 if q.get_pending(key).is_none() {
8242 continue;
8243 }
8244 let outcome = quorum::evaluate_key_evidence_with_holder_check(
8245 key,
8246 ev,
8247 &targets,
8248 config,
8249 holder_credit,
8250 );
8251 evaluated.push((*key, outcome));
8252 }
8253 } // read lock released
8254
8255 // Step 4: Insert verified keys into PaidForList (no lock held).
8256 let mut paid_insert_keys: Vec<XorName> = Vec::new();
8257 for (key, outcome) in &evaluated {
8258 if matches!(
8259 outcome,
8260 KeyVerificationOutcome::QuorumVerified { .. }
8261 | KeyVerificationOutcome::PaidListVerified { .. }
8262 ) {
8263 paid_insert_keys.push(*key);
8264 }
8265 }
8266 for key in &paid_insert_keys {
8267 if let Err(e) = paid_list.insert(key).await {
8268 warn!("Failed to add verified key to PaidForList: {e}");
8269 }
8270 }
8271
8272 // Verification established validity; the paid-list insert above records
8273 // it. Downloading the bytes is a separate duty, owed only by the
8274 // storage-admission group, asked on the same terms for every verified
8275 // key — the advertising peer's replica/paid labelling is a claim about
8276 // itself and carries no authority over what we store. This check is a
8277 // cheap pre-filter that keeps never-responsible keys out of the fetch
8278 // queue entirely; the authoritative gate is the per-attempt recheck in
8279 // `execute_single_fetch`, because a key can wait in the nearest-first
8280 // fetch queue long enough for this promotion-time answer to go stale.
8281 let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8282 for (key, outcome) in &evaluated {
8283 if matches!(
8284 outcome,
8285 KeyVerificationOutcome::QuorumVerified { .. }
8286 | KeyVerificationOutcome::PaidListVerified { .. }
8287 ) && !storage.exists(key).unwrap_or(false)
8288 && is_storage_admitted(&self_id, key, p2p_node, config).await
8289 {
8290 fetch_allowed_keys.insert(*key);
8291 }
8292 }
8293
8294 // Step 5: Update queues with the evaluated outcomes.
8295 let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
8296 let mut q = queues.write().await;
8297 for (key, outcome) in evaluated {
8298 let replica_hint_sources = q
8299 .get_pending(&key)
8300 .map(|entry| entry.replica_hint_sources.clone())
8301 .unwrap_or_default();
8302 if let Some(ev) = evidence.get(&key) {
8303 if let Some(source) =
8304 punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8305 {
8306 *bad_singleton_hints.entry(source).or_insert(0) += 1;
8307 }
8308 }
8309 match outcome {
8310 KeyVerificationOutcome::QuorumVerified { sources }
8311 | KeyVerificationOutcome::PaidListVerified { sources } => {
8312 let mut fetch_sources = sources;
8313 add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8314 let fetch_eligible = fetch_allowed_keys.contains(&key);
8315 if fetch_eligible && write_blocked {
8316 // Capacity gate, second of two, and deliberately after
8317 // Step 4: the key is now recorded in `PaidForList` and
8318 // its verification stands. Only the download is held,
8319 // because `execute_single_fetch` would refuse it and
8320 // hand the key straight back here.
8321 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8322 capacity_deferred_promote += 1;
8323 }
8324 } else if fetch_eligible && !fetch_sources.is_empty() {
8325 // A holder answered; see the matching clear on the
8326 // local-paid path.
8327 q.clear_unresolved(&key);
8328 let distance =
8329 crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8330 // Atomic remove+enqueue: on fetch_queue capacity miss
8331 // the pending entry is preserved so this verified key
8332 // is retried on the next cycle (no silent drop).
8333 let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8334 // Not terminal — either moved to fetch queue, or
8335 // retained as pending until queue drains.
8336 } else if fetch_eligible && fetch_sources.is_empty() {
8337 no_holder_deferrals += 1;
8338 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8339 let first_report = q.claim_no_holder_report(&key);
8340 report_unresolved_deferral(
8341 "Verified storage-admitted key",
8342 &key,
8343 outcome,
8344 first_report,
8345 );
8346 } else {
8347 q.remove_pending(&key);
8348 terminal_keys.push(key);
8349 }
8350 }
8351 KeyVerificationOutcome::QuorumFailed => {
8352 q.remove_pending(&key);
8353 terminal_keys.push(key);
8354 }
8355 KeyVerificationOutcome::QuorumInconclusive => {
8356 q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8357 // Backed off like any other unresolved round, but it does
8358 // NOT claim the no-holder report: nothing yet says this key
8359 // has no holder, so the first round that does say so must
8360 // still be the one that warns.
8361 let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8362 }
8363 }
8364 }
8365 drop(q);
8366
8367 for ((peer, fault), bad_hint_count) in bad_singleton_hints {
8368 let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8369 warn!(
8370 "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8371 sole-source replica hints ({fault:?}); \
8372 reporting {reports} bounded trust failure(s)"
8373 );
8374 for _ in 0..reports {
8375 match fault {
8376 // A claim about a key that does not exist. Punishable whatever the
8377 // sender's disk is doing.
8378 SingletonHintFault::RejectedByCloseGroup => {
8379 p2p_node
8380 .report_trust_event(
8381 &peer,
8382 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8383 )
8384 .await;
8385 }
8386 // "I advertised it and no longer have it." That is the one statement a
8387 // node short of disk cannot avoid making while it moves its chunks, so
8388 // it goes through the release switch.
8389 SingletonHintFault::DeniedPossession => {
8390 config::penalise_unheld_close_group_chunk(
8391 p2p_node,
8392 &peer,
8393 "replica_hint_denied_possession",
8394 REPLICATION_TRUST_WEIGHT,
8395 )
8396 .await;
8397 }
8398 }
8399 }
8400 }
8401 }
8402
8403 // Step 6: Remove terminal keys from bootstrap pending set and re-check
8404 // the drain condition.
8405 update_bootstrap_after_verification(
8406 &terminal_keys,
8407 bootstrap_state,
8408 queues,
8409 is_bootstrapping,
8410 bootstrap_complete_notify,
8411 )
8412 .await;
8413
8414 let (pending_after, fetch_after, in_flight_after) = {
8415 let q = queues.read().await;
8416 (
8417 q.pending_count(),
8418 q.fetch_queue_count(),
8419 q.in_flight_count(),
8420 )
8421 };
8422 let terminal_key_count = terminal_keys.len();
8423 let elapsed_ms = cycle_started.elapsed().as_millis();
8424
8425 if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8426 info!(
8427 target: "ant_node::replication::verification",
8428 "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}",
8429 );
8430 } else {
8431 debug!(
8432 target: "ant_node::replication::verification",
8433 "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}",
8434 );
8435 }
8436}
8437
8438/// Report a verification round that left a key without a usable holder.
8439///
8440/// Warns once per entry — the first failure is news, and by the hundredth the
8441/// node is re-asking peers it has already exhausted. Later failures stay at
8442/// `debug`, and the per-cycle count is carried in the cycle summary so the
8443/// scale of a backlog is still visible without a line per key per retry.
8444///
8445/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8446/// number: a round may advance the count without producing a no-holder result,
8447/// and such a round must not consume the warning.
8448///
8449/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8450/// a holder clears it, so a later relapse warns again: "once per episode", not
8451/// "once ever".
8452fn report_unresolved_deferral(
8453 what: &str,
8454 key: &XorName,
8455 outcome: Option<DeferralOutcome>,
8456 first_report: bool,
8457) {
8458 let Some(outcome) = outcome else {
8459 // The entry left `pending_verify` under the same lock; nothing deferred.
8460 return;
8461 };
8462 if first_report {
8463 warn!(
8464 "{what} {} has no responding holders yet; deferring retry",
8465 hex::encode(key)
8466 );
8467 } else {
8468 debug!(
8469 "{what} {} still has no responding holders after {} attempts; \
8470 retrying in {}s",
8471 hex::encode(key),
8472 outcome.attempt,
8473 outcome.retry_after.as_secs()
8474 );
8475 }
8476}
8477
8478/// Add peers that claimed possession as fallback fetch sources.
8479///
8480/// Paid-only advertisers make no possession claim and are absent from
8481/// `replica_hint_sources` by construction, so they are never added.
8482fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8483 for source in replica_hint_sources {
8484 if !sources.contains(source) {
8485 sources.push(*source);
8486 }
8487 }
8488}
8489
8490/// Why a sole-source replica hint is punishable.
8491///
8492/// The two cases look alike and are not. A hint the close group rejects outright is a
8493/// claim about a key that does not exist, which is a bad hint however the sender's disk is
8494/// doing. A sender that advertised a key and then answers `Absent` for it is making a
8495/// statement about its own storage, and that is the one thing a node short of disk cannot
8496/// avoid saying while it moves its chunks out of a store that will not give the space back.
8497#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8498enum SingletonHintFault {
8499 /// The close group says the key does not exist.
8500 RejectedByCloseGroup,
8501 /// The sender advertised the key and then denied holding it.
8502 DeniedPossession,
8503}
8504
8505/// Return the sole replica advertiser when either the close group definitively
8506/// rejects the key or the advertiser explicitly denies possessing it, and say which.
8507/// Paid-only advertisements, corroborated replica hints, and inconclusive
8508/// rounds without that direct contradiction are deliberately non-penalizing.
8509fn punishable_singleton_replica_hint_source(
8510 replica_hint_sources: &HashSet<PeerId>,
8511 outcome: &KeyVerificationOutcome,
8512 evidence: &crate::replication::types::KeyVerificationEvidence,
8513) -> Option<(PeerId, SingletonHintFault)> {
8514 // A paid-only advertiser leaves this set empty, so the sole-source lane is
8515 // reserved for peers that actually claimed possession.
8516 if replica_hint_sources.len() != 1 {
8517 return None;
8518 }
8519 let source = *replica_hint_sources.iter().next()?;
8520 if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
8521 return Some((source, SingletonHintFault::RejectedByCloseGroup));
8522 }
8523 if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
8524 return Some((source, SingletonHintFault::DeniedPossession));
8525 }
8526 None
8527}
8528
8529/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8530/// bootstrap pending set and transition out of bootstrapping when drained.
8531async fn update_bootstrap_after_verification(
8532 terminal_keys: &[XorName],
8533 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8534 queues: &Arc<RwLock<ReplicationQueues>>,
8535 is_bootstrapping: &Arc<RwLock<bool>>,
8536 bootstrap_complete_notify: &Arc<Notify>,
8537) {
8538 if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8539 return;
8540 }
8541 {
8542 let mut bs = bootstrap_state.write().await;
8543 for key in terminal_keys {
8544 bs.remove_key(key);
8545 }
8546 }
8547 let q = queues.read().await;
8548 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8549 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8550 }
8551}
8552
8553/// Retire bootstrap work owed by a peer that permanently left the routing
8554/// table, then immediately re-check drain so this removal can complete
8555/// bootstrap without waiting for an unrelated pipeline event.
8556async fn update_bootstrap_after_peer_removed(
8557 peer: &PeerId,
8558 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8559 queues: &Arc<RwLock<ReplicationQueues>>,
8560 is_bootstrapping: &Arc<RwLock<bool>>,
8561 bootstrap_complete_notify: &Arc<Notify>,
8562) {
8563 let orphaned_keys = queues.write().await.remove_hint_source(peer);
8564 let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8565
8566 if !orphaned_keys.is_empty() {
8567 let mut state = bootstrap_state.write().await;
8568 for key in &orphaned_keys {
8569 state.remove_key(key);
8570 }
8571 }
8572
8573 if orphaned_keys.is_empty() && !cleared_rejection {
8574 return;
8575 }
8576 let q = queues.read().await;
8577 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8578 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8579 }
8580}
8581
8582/// Periodic bootstrap-drain self-healing, run on every verification worker
8583/// tick until bootstrap drains.
8584///
8585/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8586/// recording of a capacity rejection leaves an entry no future event can
8587/// clear — `max_age` expiry is its only exit. And a clean-cycle
8588/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8589/// quiet node the drain condition can become true with nothing left to
8590/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8591/// drain itself, so this is invoked before `run_verification_cycle`'s
8592/// early-returns.
8593async fn expire_and_recheck_bootstrap_drain(
8594 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8595 queues: &Arc<RwLock<ReplicationQueues>>,
8596 is_bootstrapping: &Arc<RwLock<bool>>,
8597 bootstrap_complete_notify: &Arc<Notify>,
8598 max_age: Duration,
8599) {
8600 if bootstrap_state.read().await.is_drained() {
8601 return;
8602 }
8603 bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8604 let q = queues.read().await;
8605 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8606 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8607 }
8608}
8609
8610/// Set `is_bootstrapping` to `false` and wake all waiters.
8611async fn complete_bootstrap(
8612 is_bootstrapping: &Arc<RwLock<bool>>,
8613 bootstrap_complete_notify: &Arc<Notify>,
8614) {
8615 *is_bootstrapping.write().await = false;
8616 bootstrap_complete_notify.notify_waiters();
8617 info!("Replication bootstrap complete");
8618}
8619
8620// ---------------------------------------------------------------------------
8621// Fetch types and single-fetch executor
8622// ---------------------------------------------------------------------------
8623
8624/// Result classification for a single fetch attempt.
8625enum FetchResult {
8626 /// Data fetched, integrity-checked, and stored successfully.
8627 Stored,
8628 /// Content-address integrity check failed — do not retry.
8629 IntegrityFailed,
8630 /// Source failed (network error or non-success response) — retryable.
8631 SourceFailed,
8632 /// This node could not write the chunk locally: the capacity pre-check
8633 /// refused before the dial, or `put` failed after the bytes arrived.
8634 ///
8635 /// Distinct from [`Self::SourceFailed`] because nothing about the source
8636 /// is implicated, and because the remedy is the opposite one. A source
8637 /// failure should move on to the next holder; a local write failure must
8638 /// not — every remaining source would send the same chunk into the same
8639 /// full disk. The key returns to verification instead, so a later cycle
8640 /// retries it once local capacity allows. That is a retry path, not a
8641 /// liveness guarantee: `evict_stale` still expires the entry at
8642 /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8643 /// which re-acquisition depends on a fresh hint.
8644 LocalWriteFailed,
8645 /// This node already holds the key, so there is nothing to fetch —
8646 /// terminal, exactly like [`Self::Stored`], because the duty is already
8647 /// discharged.
8648 ///
8649 /// Responsibility is rechecked at download time; possession has to be too.
8650 /// The earlier gates already drop held keys out of the fetch pipeline —
8651 /// `queue_admitted_hints` skips them, and the promotion-time
8652 /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8653 /// them. (`is_relevant` is not one of them: possession there makes a key
8654 /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8655 /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8656 /// client PUT, or another source landing first. The nearest-first fetch
8657 /// queue is deep enough for that window to be real.
8658 ///
8659 /// This check must also precede the capacity pre-check below, because
8660 /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
8661 /// it, a full node would decline a key it already holds, which `put` would
8662 /// have accepted as a duplicate.
8663 AlreadyHeld,
8664 /// Live routing state no longer places this node in the storage-admission
8665 /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8666 /// the fetch was serving has lapsed, so no alternate source is tried and
8667 /// no trust event is reported: the source did nothing wrong.
8668 NoLongerResponsible,
8669}
8670
8671/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8672/// worker loop to update queue state.
8673struct FetchOutcome {
8674 key: XorName,
8675 result: FetchResult,
8676}
8677
8678/// What the fetch worker must do next for a key whose fetch attempt resolved.
8679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8680enum FetchFollowUp {
8681 /// The key terminally left the fetch pipeline (its in-flight entry is
8682 /// removed and any verification retry-slot reservation released); the
8683 /// caller must run bootstrap accounting for it.
8684 Terminal,
8685 /// The key returned to `pending_verify` for a later verification round.
8686 RequeuedForVerification,
8687 /// Retry immediately from this next untried verified source.
8688 RetryFrom(PeerId),
8689}
8690
8691/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8692///
8693/// Split out of the fetch-worker loop so the per-variant queue transitions
8694/// are unit-testable without a live network. The caller holds the queues
8695/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8696/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8697/// retry-slot reservation, and the caller's terminal handling shrinks the
8698/// bootstrap pending set — dropping the key without that accounting would
8699/// stall bootstrap drain forever.
8700///
8701/// The nursery `option_if_let_else` rewrite is impossible here: both
8702/// `map_or_else` closures would need `&mut *q` simultaneously.
8703#[allow(clippy::option_if_let_else)]
8704fn apply_fetch_result(
8705 q: &mut ReplicationQueues,
8706 key: &XorName,
8707 result: &FetchResult,
8708 verification_retry_after: Duration,
8709) -> FetchFollowUp {
8710 match result {
8711 FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8712 q.complete_fetch(key);
8713 FetchFollowUp::Terminal
8714 }
8715 FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8716 if let Some(next_peer) = q.retry_fetch(key) {
8717 FetchFollowUp::RetryFrom(next_peer)
8718 } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8719 FetchFollowUp::RequeuedForVerification
8720 } else {
8721 FetchFollowUp::Terminal
8722 }
8723 }
8724 // No `retry_fetch`: the local write is what failed, so every other
8725 // source would be asked to send the same chunk into the same full
8726 // disk. Requeueing for verification is what keeps the key from being
8727 // stranded — it comes back once capacity allows — and the fallthrough
8728 // to `Terminal` when there is no retry metadata is what keeps
8729 // bootstrap drain accounting correct, exactly as for a source failure.
8730 //
8731 // The ordinary requeue delay, deliberately. A standing capacity block
8732 // does not need a longer one here: the key returns to pending, and the
8733 // gate at the head of the next cycle defers it for minutes. A separate
8734 // backoff on this path would duplicate that to save one 15 s round, on
8735 // a race the gate already makes rare.
8736 FetchResult::LocalWriteFailed => {
8737 if q.requeue_fetch_for_verification(key, verification_retry_after) {
8738 FetchFollowUp::RequeuedForVerification
8739 } else {
8740 FetchFollowUp::Terminal
8741 }
8742 }
8743 }
8744}
8745
8746/// Whether this node currently sits inside the storage-admission group for
8747/// `key`, per live local routing state.
8748///
8749/// This is the one question every storage decision in this module asks; see
8750/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8751/// network I/O — but it awaits into the DHT manager, so callers must not
8752/// hold the queues lock across it.
8753async fn is_storage_admitted(
8754 self_id: &PeerId,
8755 key: &XorName,
8756 p2p_node: &Arc<P2PNode>,
8757 config: &ReplicationConfig,
8758) -> bool {
8759 admission::is_responsible(
8760 self_id,
8761 key,
8762 p2p_node,
8763 storage_admission_width(config.close_group_size),
8764 )
8765 .await
8766}
8767
8768#[allow(clippy::too_many_lines)]
8769/// Execute a single fetch request against `source` for `key`.
8770///
8771/// Handles encoding, network I/O, integrity checking, storage, and trust
8772/// event reporting. Returns a [`FetchOutcome`] so the caller can update
8773/// queue state without holding any locks during the network round-trip.
8774///
8775/// This is the authoritative storage-responsibility gate: each attempt —
8776/// including every per-source retry, which re-enters here — rechecks live
8777/// routing state before spending bandwidth, and once more before writing
8778/// bytes that arrived after a round-trip. The verification-time check that
8779/// promoted the key into the fetch queue is only a pre-filter; the queue is
8780/// nearest-first and deep, so a promotion decision can go stale under
8781/// topology churn before the key is ever dequeued.
8782async fn execute_single_fetch(
8783 p2p_node: Arc<P2PNode>,
8784 storage: Arc<ChunkStore>,
8785 config: Arc<ReplicationConfig>,
8786 key: XorName,
8787 source: PeerId,
8788) -> FetchOutcome {
8789 let self_id = *p2p_node.peer_id();
8790 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8791 debug!(
8792 "Skipping fetch for {}: no longer in the storage-admission group",
8793 hex::encode(key)
8794 );
8795 return FetchOutcome {
8796 key,
8797 result: FetchResult::NoLongerResponsible,
8798 };
8799 }
8800
8801 // Possession, then capacity — both before the dial, and in that order.
8802 //
8803 // `ChunkStore::put` tests `exists` before it tests disk space, so a full
8804 // node still accepts a key it already holds. Checking possession first is
8805 // what keeps this pair of gates from declining work `put` would have
8806 // taken.
8807 if storage.exists(&key).unwrap_or(false) {
8808 debug!(
8809 "Skipping fetch for {}: already held locally",
8810 hex::encode(key)
8811 );
8812 return FetchOutcome {
8813 key,
8814 result: FetchResult::AlreadyHeld,
8815 };
8816 }
8817
8818 // Capacity is checked before the dial rather than after the bytes arrive.
8819 // `put` runs this same check on every write of a key it does not already
8820 // hold, so this reaches the same verdict `put` would reach *at this
8821 // instant*. It is not a guarantee about the later write: both answers can
8822 // change across the round trip. Space freed in between would have let a
8823 // post-download `put` succeed, so a refusal here can cost a fleeting
8824 // acquisition and one retry cycle of delay; space lost in between is why
8825 // the check inside `put` still has to stay.
8826 //
8827 // What it buys is that the refusal costs no bandwidth. Without it a
8828 // disk-full node pulls the whole chunk over the network first, and the
8829 // failure is then classified as the source's — no trust event, but the
8830 // worker walks to every remaining holder, and each re-uploads the same
8831 // chunk into the same full disk.
8832 if let Err(e) = storage.check_capacity() {
8833 debug!(
8834 "Skipping fetch for {}: local storage cannot accept a write: {e}",
8835 hex::encode(key)
8836 );
8837 return FetchOutcome {
8838 key,
8839 result: FetchResult::LocalWriteFailed,
8840 };
8841 }
8842
8843 let request = protocol::FetchRequest { key };
8844 let msg = ReplicationMessage {
8845 request_id: rand::thread_rng().gen::<u64>(),
8846 body: ReplicationMessageBody::FetchRequest(request),
8847 };
8848
8849 let encoded = match msg.encode() {
8850 Ok(data) => data,
8851 Err(e) => {
8852 warn!("Failed to encode fetch request: {e}");
8853 return FetchOutcome {
8854 key,
8855 result: FetchResult::SourceFailed,
8856 };
8857 }
8858 };
8859
8860 let result = p2p_node
8861 .send_request(
8862 &source,
8863 REPLICATION_PROTOCOL_ID,
8864 encoded,
8865 config.fetch_request_timeout,
8866 )
8867 .await;
8868
8869 match result {
8870 Ok(response) => {
8871 let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
8872 p2p_node
8873 .report_trust_event(
8874 &source,
8875 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8876 )
8877 .await;
8878 return FetchOutcome {
8879 key,
8880 result: FetchResult::SourceFailed,
8881 };
8882 };
8883
8884 match resp_msg.body {
8885 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
8886 key: resp_key,
8887 data,
8888 }) => {
8889 // Validate the response key matches the requested key.
8890 // A malicious peer could serve valid data for a different
8891 // key, passing integrity checks while the requested key
8892 // is falsely marked as fetched.
8893 if resp_key != key {
8894 warn!(
8895 "Fetch response key mismatch: requested {}, got {}",
8896 hex::encode(key),
8897 hex::encode(resp_key)
8898 );
8899 p2p_node
8900 .report_trust_event(
8901 &source,
8902 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8903 )
8904 .await;
8905 return FetchOutcome {
8906 key,
8907 result: FetchResult::IntegrityFailed,
8908 };
8909 }
8910
8911 // Enforce chunk size invariant on fetched data.
8912 // Checked before the content-address hash to avoid
8913 // hashing up to 10 MiB of oversized junk data.
8914 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
8915 warn!(
8916 "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
8917 hex::encode(resp_key),
8918 data.len(),
8919 crate::ant_protocol::MAX_CHUNK_SIZE,
8920 );
8921 p2p_node
8922 .report_trust_event(
8923 &source,
8924 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8925 )
8926 .await;
8927 return FetchOutcome {
8928 key,
8929 result: FetchResult::IntegrityFailed,
8930 };
8931 }
8932
8933 // Content-address integrity check.
8934 let computed = crate::client::compute_address(&data);
8935 if computed != resp_key {
8936 warn!(
8937 "Fetched record integrity check failed: expected {}, got {}",
8938 hex::encode(resp_key),
8939 hex::encode(computed)
8940 );
8941 p2p_node
8942 .report_trust_event(
8943 &source,
8944 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8945 )
8946 .await;
8947 return FetchOutcome {
8948 key,
8949 result: FetchResult::IntegrityFailed,
8950 };
8951 }
8952
8953 // Responsibility can lapse during the network round-trip.
8954 // The bandwidth is already spent; declining the write is
8955 // what still avoids the disk write and the later
8956 // fetch→store→prune churn. Edge flapping is dampened by
8957 // the margin `storage_admission_width` adds over
8958 // `close_group_size`.
8959 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8960 debug!(
8961 "Fetched {} but responsibility lapsed in transit; not storing",
8962 hex::encode(key)
8963 );
8964 return FetchOutcome {
8965 key,
8966 result: FetchResult::NoLongerResponsible,
8967 };
8968 }
8969
8970 if let Err(e) = storage.put(&resp_key, &data).await {
8971 // The bytes arrived and passed the content-address
8972 // check, so the source did its job; the failure is
8973 // entirely local (disk-full, or an LMDB error). Any
8974 // valid source must serve identical content, so trying
8975 // the next one cannot cure a local error — it only
8976 // re-downloads the same chunk into the same store.
8977 warn!(
8978 "Failed to store fetched record {}: {e}",
8979 hex::encode(resp_key)
8980 );
8981 return FetchOutcome {
8982 key,
8983 result: FetchResult::LocalWriteFailed,
8984 };
8985 }
8986
8987 FetchOutcome {
8988 key,
8989 result: FetchResult::Stored,
8990 }
8991 }
8992 ReplicationMessageBody::FetchResponse(
8993 ref response @ (protocol::FetchResponse::NotFound { .. }
8994 | protocol::FetchResponse::Error { .. }),
8995 ) => {
8996 // This peer was selected as a fetch source because it recently
8997 // answered `Present` during verification, so either answer is
8998 // evidence of something. Which one decides what it is charged: a peer
8999 // that does not hold the chunk is the lane this release withholds, a
9000 // peer whose own read failed is not.
9001 if let protocol::FetchResponse::Error { reason, .. } = response {
9002 warn!(
9003 "Fetch: peer {source} returned error for {}: {reason}",
9004 hex::encode(key)
9005 );
9006 } else {
9007 warn!(
9008 "Fetch: verified source {source} returned NotFound for {}",
9009 hex::encode(key)
9010 );
9011 }
9012 if let Some(fault) = fetch_fault_for(response) {
9013 let lane = match fault {
9014 FetchFault::UnheldChunk => "fetch_not_found",
9015 FetchFault::ResponderFault => "fetch_error",
9016 };
9017 charge_fetch_fault(&p2p_node, &source, fault, lane).await;
9018 }
9019 FetchOutcome {
9020 key,
9021 result: FetchResult::SourceFailed,
9022 }
9023 }
9024 _ => {
9025 // Unexpected message type — treat as malformed.
9026 p2p_node
9027 .report_trust_event(
9028 &source,
9029 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9030 )
9031 .await;
9032 FetchOutcome {
9033 key,
9034 result: FetchResult::SourceFailed,
9035 }
9036 }
9037 }
9038 }
9039 Err(e) => {
9040 debug!("Fetch request to {source} failed: {e}");
9041 // No ApplicationFailure here — P2PNode::send_request() already
9042 // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9043 FetchOutcome {
9044 key,
9045 result: FetchResult::SourceFailed,
9046 }
9047 }
9048 }
9049}
9050
9051// ---------------------------------------------------------------------------
9052// Audit result handler
9053// ---------------------------------------------------------------------------
9054
9055/// Format the first confirmed-failed key as a 16-hex-char label.
9056///
9057/// Pairs with `challenged_peer` to form a stable cross-host correlation
9058/// handle in the audit-failure log line, e.g.
9059///
9060/// ```text
9061/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9062/// ```
9063///
9064/// Falls back to `"0x"` when the list is empty so the log line never
9065/// contains a misleading default.
9066fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9067 confirmed_failed_keys.first().map_or_else(
9068 || "0x".to_string(),
9069 |k| format!("0x{}", hex::encode(&k[..8])),
9070 )
9071}
9072
9073/// Execute the side effects for a subtree storage-commitment audit failure.
9074///
9075/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9076/// legitimately time out on slow or loaded honest peers, so it never touches the
9077/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9078/// failures still penalise immediately and revoke holder credit.
9079async fn handle_subtree_failed_audit(
9080 challenged_peer: &PeerId,
9081 confirmed_failed_key_count: usize,
9082 reason: &AuditFailureReason,
9083 p2p_node: &Arc<P2PNode>,
9084 sync_state: &Arc<RwLock<NeighborSyncState>>,
9085 recent_provers: &Arc<RwLock<RecentProvers>>,
9086) {
9087 if matches!(reason, AuditFailureReason::Timeout) {
9088 debug!(
9089 "Audit timeout for {challenged_peer} fully graced \
9090 (subtree audit does not evict on timeout)"
9091 );
9092 return;
9093 }
9094
9095 // The caller already logged the rich failure line with reason + per-category
9096 // summary; avoid a redundant second error log here.
9097 let _ = confirmed_failed_key_count;
9098 {
9099 let mut state = sync_state.write().await;
9100 state.clear_active_bootstrap_claim(challenged_peer);
9101 }
9102 {
9103 let mut provers_guard = recent_provers.write().await;
9104 apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9105 }
9106 // Deliberately NOT routed through the release switch. This is the commitment-bound
9107 // subtree audit: the peer published a signed claim to hold these keys and could not
9108 // answer for them. That contract is enforced in every release, including the one that
9109 // withholds the penalty for merely not holding a close-group chunk, because the whole
9110 // migration depends on a node's reduced commitment still meaning something.
9111 p2p_node
9112 .report_trust_event(
9113 challenged_peer,
9114 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9115 )
9116 .await;
9117}
9118
9119/// Handle audit result: log findings and emit trust events.
9120async fn handle_subtree_audit_result(
9121 result: &AuditTickResult,
9122 p2p_node: &Arc<P2PNode>,
9123 sync_state: &Arc<RwLock<NeighborSyncState>>,
9124 recent_provers: &Arc<RwLock<RecentProvers>>,
9125 config: &ReplicationConfig,
9126) {
9127 match result {
9128 AuditTickResult::Passed {
9129 challenged_peer,
9130 keys_checked,
9131 } => {
9132 protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9133 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9134 // Peer responded normally — clear the active bootstrap claim while
9135 // retaining history so a later claim is treated as repeated abuse.
9136 {
9137 let mut state = sync_state.write().await;
9138 state.clear_active_bootstrap_claim(challenged_peer);
9139 }
9140 p2p_node
9141 .report_trust_event(
9142 challenged_peer,
9143 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9144 )
9145 .await;
9146 }
9147 AuditTickResult::Failed {
9148 evidence,
9149 no_response_class,
9150 } => {
9151 if let FailureEvidence::AuditFailure {
9152 challenged_peer,
9153 confirmed_failed_keys,
9154 summary,
9155 reason,
9156 ..
9157 } = evidence
9158 {
9159 protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9160 // Rich diagnostics (from main's audit-failure logging) + the
9161 // first-failed-key correlation handle.
9162 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9163 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9164 error!(
9165 "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}",
9166 audit_failure_class,
9167 confirmed_failed_keys.len(),
9168 summary.challenged_keys,
9169 summary.absent_keys,
9170 summary.digest_mismatch_keys,
9171 );
9172 // Route the side effects through the subtree-only failure path.
9173 // Responsible-chunk `AuditChallenge` handling intentionally uses
9174 // its own old immediate-penalty handler below.
9175 handle_subtree_failed_audit(
9176 challenged_peer,
9177 confirmed_failed_keys.len(),
9178 reason,
9179 p2p_node,
9180 sync_state,
9181 recent_provers,
9182 )
9183 .await;
9184 }
9185 }
9186 AuditTickResult::BootstrapClaim { peer } => {
9187 // Gap 6: BootstrapClaimAbuse grace period in audit path.
9188 // Separate state mutation from network I/O to avoid holding the
9189 // write lock across report_trust_event.
9190 let should_report = {
9191 let now = Instant::now();
9192 let mut state = sync_state.write().await;
9193 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9194 {
9195 BootstrapClaimObservation::WithinGrace { .. } => {
9196 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9197 false
9198 }
9199 BootstrapClaimObservation::PastGrace { first_seen } => {
9200 warn!(
9201 "Audit: peer {peer} claiming bootstrap past grace period \
9202 ({:?} > {:?}), reporting abuse",
9203 now.duration_since(first_seen),
9204 config.bootstrap_claim_grace_period,
9205 );
9206 true
9207 }
9208 BootstrapClaimObservation::Repeated { first_seen } => {
9209 warn!(
9210 "Audit: peer {peer} repeated bootstrap claim after previously \
9211 stopping; first claim was {:?} ago, reporting abuse",
9212 now.duration_since(first_seen),
9213 );
9214 true
9215 }
9216 }
9217 };
9218 if should_report {
9219 p2p_node
9220 .report_trust_event(
9221 peer,
9222 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9223 )
9224 .await;
9225 }
9226 }
9227 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9228 }
9229}
9230
9231/// Whether a confirmed audit failure with this reason clears the peer's active
9232/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9233/// bootstrapping); every confirmed storage-integrity reason does.
9234///
9235/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9236/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9237/// still reports the normal audit trust penalty.
9238fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9239 !matches!(reason, AuditFailureReason::Timeout)
9240}
9241
9242/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9243/// events and manage bootstrap-claim state.
9244///
9245/// This is intentionally separate from the subtree audit result handler. A
9246/// responsible-chunk `AuditChallenge` `Failed` result reports
9247/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9248/// restoring the pre-ADR-0002 behaviour.
9249#[allow(clippy::too_many_lines)]
9250async fn handle_audit_result(
9251 result: &AuditTickResult,
9252 p2p_node: &Arc<P2PNode>,
9253 sync_state: &Arc<RwLock<NeighborSyncState>>,
9254 config: &ReplicationConfig,
9255) {
9256 match result {
9257 AuditTickResult::Passed {
9258 challenged_peer,
9259 keys_checked,
9260 } => {
9261 protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9262 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9263 {
9264 let mut state = sync_state.write().await;
9265 state.clear_active_bootstrap_claim(challenged_peer);
9266 }
9267 p2p_node
9268 .report_trust_event(
9269 challenged_peer,
9270 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9271 )
9272 .await;
9273 }
9274 AuditTickResult::Failed {
9275 evidence,
9276 no_response_class,
9277 } => {
9278 if let FailureEvidence::AuditFailure {
9279 challenged_peer,
9280 confirmed_failed_keys,
9281 summary,
9282 reason,
9283 ..
9284 } = evidence
9285 {
9286 protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9287 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9288 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9289 error!(
9290 "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}",
9291 audit_failure_class,
9292 confirmed_failed_keys.len(),
9293 summary.challenged_keys,
9294 summary.absent_keys,
9295 summary.digest_mismatch_keys,
9296 );
9297 if audit_failure_clears_bootstrap_claim(reason) {
9298 let mut state = sync_state.write().await;
9299 state.clear_active_bootstrap_claim(challenged_peer);
9300 } else {
9301 debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9302 }
9303 config::penalise_unheld_close_group_chunk(
9304 p2p_node,
9305 challenged_peer,
9306 crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
9307 config::AUDIT_FAILURE_TRUST_WEIGHT,
9308 )
9309 .await;
9310 }
9311 }
9312 AuditTickResult::BootstrapClaim { peer } => {
9313 let should_report = {
9314 let now = Instant::now();
9315 let mut state = sync_state.write().await;
9316 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9317 {
9318 BootstrapClaimObservation::WithinGrace { .. } => {
9319 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9320 false
9321 }
9322 BootstrapClaimObservation::PastGrace { first_seen } => {
9323 warn!(
9324 "Audit: peer {peer} claiming bootstrap past grace period \
9325 ({:?} > {:?}), reporting abuse",
9326 now.duration_since(first_seen),
9327 config.bootstrap_claim_grace_period,
9328 );
9329 true
9330 }
9331 BootstrapClaimObservation::Repeated { first_seen } => {
9332 warn!(
9333 "Audit: peer {peer} repeated bootstrap claim after previously \
9334 stopping; first claim was {:?} ago, reporting abuse",
9335 now.duration_since(first_seen),
9336 );
9337 true
9338 }
9339 }
9340 };
9341 if should_report {
9342 p2p_node
9343 .report_trust_event(
9344 peer,
9345 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9346 )
9347 .await;
9348 }
9349 }
9350 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9351 }
9352}
9353
9354/// Whether a confirmed audit failure with this reason should revoke the
9355/// peer's `recent_provers` holder credit immediately (v12 §6).
9356///
9357/// `true` for any reason where the peer actually answered (or admitted
9358/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9359/// bytes for committed key"), `MalformedResponse` — these prove the
9360/// peer no longer holds what it committed to, so it must not keep
9361/// holder credit for the proof TTL. `false` for `Timeout`: a single
9362/// dropped packet must not strip an honest peer; the 40-min TTL is the
9363/// deliberate liveness cushion there.
9364fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9365 !matches!(reason, AuditFailureReason::Timeout)
9366}
9367
9368/// Apply the holder-credit revocation decision for a confirmed audit
9369/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9370/// testable without a live `P2PNode`: the production `Failed` arm of
9371/// `handle_subtree_audit_result` calls exactly this.
9372fn apply_audit_failure_credit_revocation(
9373 provers: &mut RecentProvers,
9374 challenged_peer: &PeerId,
9375 reason: &AuditFailureReason,
9376) {
9377 if audit_failure_revokes_holder_credit(reason) {
9378 provers.forget_peer(challenged_peer);
9379 }
9380}
9381
9382// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9383
9384// ---------------------------------------------------------------------------
9385// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9386// ---------------------------------------------------------------------------
9387
9388/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9389/// message handler passes one value instead of a long argument list; all
9390/// fields are cheap `Arc` clones.
9391#[derive(Clone)]
9392struct GossipAuditTrigger {
9393 p2p_node: Arc<P2PNode>,
9394 config: Arc<ReplicationConfig>,
9395 recent_provers: Arc<RwLock<RecentProvers>>,
9396 sync_state: Arc<RwLock<NeighborSyncState>>,
9397 /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9398 /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9399 /// only when a real audit is about to be sent — never by a losing lottery
9400 /// ticket — so gossip traffic alone can never suppress a paid first audit.
9401 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9402 detached_task_tracker: TaskTracker,
9403 /// Gossip-private lottery attempt window: stamped on every roll (win or
9404 /// lose) so a gossip flood cannot re-roll the lottery within the window.
9405 /// The first-audit scheduler never reads this map.
9406 lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9407}
9408
9409/// What a gossip ingest yields for the audit trigger: the commitment hash to
9410/// pin and the `key_count` needed to size the response deadline from the actual
9411/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9412/// or not) so a stable-keyset node stays auditable — not just on its first
9413/// commitment.
9414#[derive(Debug, Clone, Copy)]
9415struct AuditTarget {
9416 pin_hash: [u8; 32],
9417 key_count: u32,
9418}
9419
9420/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9421/// verifier's cross-check so it can receive a **deterministic first audit**.
9422///
9423/// Sent from the verifier to the replication engine's first-audit drainer. The
9424/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9425/// audits of the same peer revert to the gossip lottery), orders most-recently-
9426/// monetized first, and runs the same `run_subtree_audit` under the same
9427/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9428#[derive(Debug, Clone, Copy)]
9429pub struct MonetizedPinEvent {
9430 /// The peer whose commitment backed the payment.
9431 pub peer: PeerId,
9432 /// The pinned commitment hash.
9433 pub pin: [u8; 32],
9434 /// The committed key count (sizes the audit deadline).
9435 pub key_count: u32,
9436 /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9437 /// pin whose quote is older than the answerability window (ADR-0004 A1
9438 /// guardrail A): with grace removed, challenging an aged-out pin would
9439 /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9440 pub quote_ts: SystemTime,
9441}
9442
9443/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9444/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9445/// stamps `now`), `false` if it was audited within
9446/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9447/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9448/// without a live node: a burst of gossips from one peer yields at most one
9449/// `true` per cooldown window.
9450fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9451 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9452 let known = match map.get(peer) {
9453 Some(&last) => {
9454 if now.saturating_duration_since(last) < cooldown {
9455 return false;
9456 }
9457 true
9458 }
9459 None => false,
9460 };
9461 // Bound the map under churn like its siblings (drop the oldest stamp) before
9462 // admitting a brand-new peer.
9463 if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9464 if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9465 map.remove(&victim);
9466 }
9467 }
9468 map.insert(*peer, now);
9469 true
9470}
9471
9472/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9473/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9474/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9475/// already covered; the authoritative check-and-stamp still runs at promotion,
9476/// so this is only an optimization and never the security boundary.
9477fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9478 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9479 map.get(peer).map_or(true, |&last| {
9480 now.saturating_duration_since(last) >= cooldown
9481 })
9482}
9483
9484/// The gossip-audit launch decision in ONE place so the ordering is shared
9485/// between production and its test (ADR-0002 "occasional surprise exams").
9486///
9487/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9488/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9489/// sampled first, a gossip flood would re-roll it on every message until one
9490/// won, multiplying audits, so each peer gets at most one lottery roll per
9491/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9492/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9493/// also consults — only after a WIN, i.e. only when a real audit is about to be
9494/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9495/// wire, so it must not defer a paid first audit (repeatable losses could
9496/// otherwise hold a monetized pin past its answerability window). Production
9497/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9498/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9499/// here fails the test.
9500fn audit_launch_decision(
9501 attempts: &mut HashMap<PeerId, Instant>,
9502 launched: &mut HashMap<PeerId, Instant>,
9503 peer: &PeerId,
9504 now: Instant,
9505 lottery_wins: bool,
9506) -> bool {
9507 // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9508 // window even on a loss; private to the gossip path).
9509 if !cooldown_allows_audit(attempts, peer, now) {
9510 return false;
9511 }
9512 // Gate 2: the probability lottery. A loss stops here and stamps nothing
9513 // shared.
9514 if !lottery_wins {
9515 return false;
9516 }
9517 // Gate 3: the shared actual-audit cooldown (a recent real audit from
9518 // either path still suppresses this launch), stamped only on launch.
9519 cooldown_allows_audit(launched, peer, now)
9520}
9521
9522/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9523/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9524/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9525/// handling is never blocked on a network round-trip.
9526async fn maybe_trigger_gossip_audit(
9527 trigger: &GossipAuditTrigger,
9528 peer: &PeerId,
9529 target: AuditTarget,
9530) {
9531 // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9532 // lives in the pure `audit_launch_decision` so the ordering is shared with
9533 // its test. Sample the lottery here, then let the helper apply the gates.
9534 let now = Instant::now();
9535 let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9536 {
9537 // Lock order: attempts before the shared cooldown; this is the only
9538 // place both are held together.
9539 let mut attempts = trigger.lottery_attempts.write().await;
9540 let mut launched = trigger.cooldown.write().await;
9541 if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9542 return;
9543 }
9544 }
9545
9546 let detached_task_tracker = trigger.detached_task_tracker.clone();
9547 let trigger = trigger.clone();
9548 let peer = *peer;
9549 detached_task_tracker.spawn(async move {
9550 let credit = storage_commitment_audit::AuditCredit {
9551 recent_provers: &trigger.recent_provers,
9552 };
9553 let result = storage_commitment_audit::run_subtree_audit_with_origin(
9554 &trigger.p2p_node,
9555 &trigger.config,
9556 &peer,
9557 target.pin_hash,
9558 target.key_count,
9559 Some(&credit),
9560 storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9561 )
9562 .await;
9563 handle_subtree_audit_result(
9564 &result,
9565 &trigger.p2p_node,
9566 &trigger.sync_state,
9567 &trigger.recent_provers,
9568 &trigger.config,
9569 )
9570 .await;
9571 });
9572}
9573
9574/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9575///
9576/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9577/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9578/// of its last attempt. Holds one write lock across the decision so two
9579/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9580/// caller's expensive verify so a slow/failed verify still rate-limits the next
9581/// message. Bounds the map under a flood of distinct peer ids.
9582async fn sig_verify_rate_limit_ok(
9583 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9584 source: &PeerId,
9585 now: Instant,
9586) -> bool {
9587 let mut attempts = sig_verify_attempts.write().await;
9588 if let Some(&last) = attempts.get(source) {
9589 if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9590 return false;
9591 }
9592 }
9593 if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9594 if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9595 attempts.remove(&victim);
9596 }
9597 }
9598 attempts.insert(*source, now);
9599 true
9600}
9601
9602/// Verify + store an inbound commitment from a gossip peer.
9603///
9604/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9605/// the bootstrap-sync loop. Drops the commitment unless all five gates
9606/// pass:
9607/// 1. `source` is in our DHT routing table (sybil/churn cap).
9608/// 2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9609/// binding to the authenticated transport peer).
9610/// 3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9611/// (the embedded pubkey actually belongs to the claimed identity —
9612/// saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9613/// 4. `verify_commitment_signature(commitment)` succeeds against the
9614/// embedded public key. The signed payload binds the pubkey, so an
9615/// adversary cannot swap the key while keeping the body.
9616/// 5. The cache has room or this is an update for an existing entry
9617/// (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9618///
9619/// On all-pass, the commitment is stored as the auditor's per-peer
9620/// "last known commitment" for use as `expected_commitment_hash` in
9621/// future audits.
9622///
9623/// Failures (no commitment / mismatched peer id / bad signature) are
9624/// silent drops — gossip is best-effort and a malformed commitment from
9625/// one peer should not affect anything else.
9626///
9627/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9628/// or not its root changed), so the caller can run a probabilistic,
9629/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9630/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9631/// being auditable, so it cannot pass one audit and then delete data while
9632/// re-gossiping the same root forever. The cooldown + probability bound the
9633/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9634/// gate) or there is nothing to pin.
9635///
9636/// Handle a capable peer gossiping `None` (a commitment downgrade).
9637///
9638/// A capable peer that previously gossiped a commitment but now gossips `None`
9639/// is trying to drop off the audit path. Within the answerability window we keep
9640/// the cached commitment pinned AND return it as an audit target so this gossip
9641/// still schedules a subtree audit against the peer's last known commitment — if
9642/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9643/// the trigger MUST fire here or the downgrade is never re-challenged).
9644///
9645/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9646/// honours for its own retired commitment: once that elapses since we last
9647/// received the peer's commitment, an honest peer has legitimately retired that
9648/// root (its responder side `retire_current`s and lets it age out) and can no
9649/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9650/// failure, so we then forget the cached commitment (keeping the sticky
9651/// `commitment_capable` bit) and stop pinning it.
9652async fn handle_commitment_downgrade(
9653 source: &PeerId,
9654 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9655) -> Option<AuditTarget> {
9656 let now = Instant::now();
9657 let cached = {
9658 let map = last_commitment_by_peer.read().await;
9659 map.get(source).and_then(|rec| {
9660 if !rec.commitment_capable {
9661 return None;
9662 }
9663 let last = rec.last_commitment()?;
9664 let pin = rec.commitment_hash()?;
9665 let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9666 Some((pin, last.key_count, fresh))
9667 })
9668 };
9669 match cached {
9670 Some((pin, key_count, true)) => {
9671 warn!(
9672 "ingest_peer_commitment: commitment-capable peer {source} sent None \
9673 (downgrade attempt); auditing against its last cached commitment"
9674 );
9675 Some(AuditTarget {
9676 pin_hash: pin,
9677 key_count,
9678 })
9679 }
9680 Some((_, _, false)) => {
9681 // Cached commitment has aged past the answerability window — forget
9682 // it so we stop pinning a root the peer is no longer obliged to
9683 // answer. Keep `commitment_capable` (sticky). Re-check freshness
9684 // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9685 // from this peer may have refreshed `received_at` in the gap between
9686 // our read and write locks; if so, leave its fresh commitment intact.
9687 if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9688 let still_stale =
9689 now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9690 if still_stale {
9691 rec.clear_commitment();
9692 debug!(
9693 "ingest_peer_commitment: capable peer {source} sent None and its cached \
9694 commitment aged past the answerability TTL; forgetting it"
9695 );
9696 }
9697 }
9698 None
9699 }
9700 None => None,
9701 }
9702}
9703
9704async fn ingest_peer_commitment(
9705 source: &PeerId,
9706 commitment: Option<&StorageCommitment>,
9707 p2p_node: &Arc<P2PNode>,
9708 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9709 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9710 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9711) -> Option<AuditTarget> {
9712 let Some(c) = commitment else {
9713 return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9714 };
9715 // RT-membership gate: only accept commitments from peers in our
9716 // routing table. Off-RT senders (sybils, drive-by relays) cannot
9717 // populate the cache, which closes the hole where a flood of
9718 // off-RT identities could fill the cap and evict honest
9719 // peers. The neighbor-sync request handler applies the same gate
9720 // before admitting inbound replication hints (see neighbor_sync.rs
9721 // `sender_in_rt`); we mirror that policy here for the commitment
9722 // piggyback.
9723 if !p2p_node.dht_manager().is_in_routing_table(source).await {
9724 debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9725 return None;
9726 }
9727 // Peer-id binding: the commitment's claimed sender must match the
9728 // authenticated transport peer (`source`). Defeats relay/replay
9729 // and also pins which embedded public key we are about to verify
9730 // against — the verify itself trusts the embedded key, so the
9731 // peer-id binding is the link to a real identity.
9732 if &c.sender_peer_id != source.as_bytes() {
9733 warn!(
9734 "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9735 (dropped, possible relay attempt)"
9736 );
9737 return None;
9738 }
9739 // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9740 // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9741 // with a throwaway key they own and lie about which identity it
9742 // belongs to (the embedded-key signature would verify trivially).
9743 let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9744 if derived_peer_id != c.sender_peer_id {
9745 warn!(
9746 "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9747 {source} (dropped, throwaway-key attack)"
9748 );
9749 return None;
9750 }
9751 // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9752 // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9753 // sybil/RT-membership-bypassing peer that flooded valid-looking
9754 // gossip would otherwise burn CPU on every message. The rate
9755 // limit is checked AFTER cheap structural gates (RT, peer-id
9756 // binding, pubkey-binding) and BEFORE the expensive sig verify.
9757 //
9758 // Tracked in `sig_verify_attempts` (separate from
9759 // last_commitment_by_peer) so EVERY attempt — successful or not —
9760 // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9761 // would skip the cap for peers we've never successfully verified,
9762 // letting a flood of invalid-but-structurally-plausible gossips
9763 // burn CPU.
9764 let now = Instant::now();
9765 if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9766 debug!(
9767 "ingest_peer_commitment: rate-limited sig verify from {source} \
9768 (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9769 );
9770 return None;
9771 }
9772 // Signature verify, using the public key embedded in the commitment
9773 // itself. The pubkey is bound by the signature payload (see
9774 // commitment_signed_payload) so an adversary cannot keep the body
9775 // and swap the key to one they hold the secret for.
9776 if !crate::replication::commitment::verify_commitment_signature(c) {
9777 warn!(
9778 "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9779 (dropped, forged commitment)"
9780 );
9781 return None;
9782 }
9783 // The new commitment's hash, used to store and to pin for the audit target.
9784 let new_hash = commitment_hash(c);
9785 let mut map = last_commitment_by_peer.write().await;
9786 // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9787 // evict an arbitrary existing entry to make room. Updates for peers
9788 // already in the map are always accepted (they replace, not grow).
9789 if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9790 // Drop one arbitrary entry. HashMap iter order is random which
9791 // is fine — over time PeerRemoved cleanup keeps the working set
9792 // anchored on the real RT membership; this cap only fires under
9793 // active flooding attempts.
9794 if let Some(victim) = map.keys().next().copied() {
9795 map.remove(&victim);
9796 warn!(
9797 "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9798 evicted {victim} to admit {source}"
9799 );
9800 }
9801 }
9802 // Preserve sticky commitment_capable across updates — once true,
9803 // always true. New entries start with capable = true (we just
9804 // verified a valid commitment from this peer).
9805 map.entry(*source)
9806 .and_modify(|r| {
9807 // set_commitment refreshes the cached hash (§13) alongside the
9808 // commitment + received_at so they never drift.
9809 r.set_commitment(c.clone(), now);
9810 r.last_sig_verify_at = now;
9811 r.commitment_capable = true; // sticky-redundant but explicit
9812 })
9813 .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9814 drop(map);
9815 // Record the sticky "ever v12-capable" bit in a set independent of
9816 // `last_commitment_by_peer` (whose entries can be evicted by
9817 // `PeerRemoved` and the sybil cap). This is what the §3 audit
9818 // shield and the §6 holder-eligibility closure consult to decide
9819 // whether the peer is expected to speak v12.
9820 //
9821 // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9822 // identity-rotation attacks: once full, new entries are refused.
9823 // Refusal degrades over-cap peers to the behaviour before this set
9824 // existed (treated as legacy on rejoin), which is not a security
9825 // regression and preserves the historic set stable.
9826 {
9827 let mut set = ever_capable_peers.write().await;
9828 if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9829 set.insert(*source);
9830 } else {
9831 warn!(
9832 "ingest_peer_commitment: ever_capable_peers at cap \
9833 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9834 );
9835 }
9836 }
9837 // Return an audit target for EVERY valid stored commitment (changed or
9838 // not), so the caller's cooldown+probability-gated trigger keeps a
9839 // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9840 // failure (new_hash == None, unreachable for a real commitment) yields None.
9841 new_hash.map(|pin_hash| AuditTarget {
9842 pin_hash,
9843 key_count: c.key_count,
9844 })
9845}
9846
9847// ---------------------------------------------------------------------------
9848// Storage-bound audit (v12) — responder commitment rotation
9849// ---------------------------------------------------------------------------
9850
9851/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9852/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9853/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9854async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9855 let bytes = match tokio::fs::read(path).await {
9856 Ok(b) => b,
9857 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9858 debug!(
9859 "Commitment retention: no snapshot at {} (fresh start)",
9860 path.display()
9861 );
9862 return;
9863 }
9864 Err(e) => {
9865 warn!(
9866 "Commitment retention: failed to read {}: {e}",
9867 path.display()
9868 );
9869 return;
9870 }
9871 };
9872 if let Some(persisted) = PersistedRetention::from_bytes(&bytes) {
9873 state.restore(&persisted);
9874 info!(
9875 "Commitment retention: reloaded {} slot(s) from {}",
9876 state.retained_slot_count(),
9877 path.display()
9878 );
9879 } else {
9880 warn!(
9881 "Commitment retention: corrupt snapshot at {}; starting with empty retention",
9882 path.display()
9883 );
9884 }
9885}
9886
9887/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
9888/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
9889/// needless disk writes on idle nodes. On success updates `last` to the bytes
9890/// written; on a serialization/write error the existing on-disk snapshot is left
9891/// intact (never truncated).
9892async fn persist_retention_if_changed(
9893 state: &ResponderCommitmentState,
9894 path: &Path,
9895 last: &mut Option<Vec<u8>>,
9896) {
9897 let Some(bytes) = state.snapshot().to_bytes() else {
9898 warn!("Commitment retention: serialization failed; keeping previous snapshot");
9899 return;
9900 };
9901 if last.as_deref() == Some(bytes.as_slice()) {
9902 return;
9903 }
9904 if write_retention_atomic(path, bytes.clone()).await {
9905 *last = Some(bytes);
9906 }
9907}
9908
9909/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
9910/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
9911/// success. Only the retention-persist loop writes this path, so a fixed temp
9912/// name is safe.
9913async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
9914 let path = path.to_path_buf();
9915 let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
9916 let tmp = path.with_extension("tmp");
9917 std::fs::write(&tmp, &bytes)?;
9918 std::fs::File::open(&tmp)?.sync_all()?;
9919 std::fs::rename(&tmp, &path)?;
9920 // Fsync the directory so the rename (the durable-commit point) is not
9921 // lost on a crash right after it. An empty parent (relative filename)
9922 // means the current directory.
9923 let dir = path
9924 .parent()
9925 .filter(|p| !p.as_os_str().is_empty())
9926 .unwrap_or_else(|| Path::new("."));
9927 std::fs::File::open(dir)?.sync_all()?;
9928 Ok(())
9929 })
9930 .await;
9931 match res {
9932 Ok(Ok(())) => true,
9933 Ok(Err(e)) => {
9934 warn!("Commitment retention: persist failed: {e}");
9935 false
9936 }
9937 Err(e) => {
9938 warn!("Commitment retention: persist task join failed: {e}");
9939 false
9940 }
9941 }
9942}
9943
9944/// Read the current LMDB key set, build + sign a fresh
9945/// `StorageCommitment`, and rotate it into `state` as the new `current`.
9946/// The prior `current` is demoted to `previous`; the prior `previous` is
9947/// dropped (per `ResponderCommitmentState::rotate`).
9948///
9949/// For content-addressed chunks (Autonomi's chunk store), `address ==
9950/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
9951/// re-read each chunk's bytes to compute the leaf hash.
9952///
9953/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
9954/// rotate. The auditor side handles "no commitment for this peer" by
9955/// falling back to the legacy plain-digest audit path.
9956async fn rebuild_and_rotate_commitment(
9957 storage: &Arc<ChunkStore>,
9958 identity: &Arc<NodeIdentity>,
9959 state: &Arc<ResponderCommitmentState>,
9960 p2p: &Arc<P2PNode>,
9961 config: &Arc<ReplicationConfig>,
9962) -> Result<()> {
9963 // Not `all_keys()`. While the node is bridging off the legacy store these are the
9964 // same thing, but once it has settled on what it can hold this narrows to the
9965 // file-backed set, which is what stops it claiming keys it is about to give up. It is
9966 // also what lets `is_held` eventually go false for those keys, which is the gate on
9967 // removing the legacy environment at all.
9968 let stored_keys = storage
9969 .committable_keys()
9970 .await
9971 .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
9972
9973 // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
9974 // everything currently on disk ("hold"). This is the half of the retention
9975 // contract that lets out-of-range chunks age out: a key that has left our
9976 // close group is excluded from the NEXT commitment, so once its last gossip
9977 // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
9978 // set, `ResponderCommitmentState::is_held` goes false,
9979 // and the pruner (which until then vetoes its deletion) reclaims it. Without
9980 // this filter the pruner's reprieve would keep re-committing stale keys
9981 // forever (the rebuild reads all_keys, so a retained-on-disk key would be
9982 // re-committed and re-gossiped every rotation — a permanent pin).
9983 let self_id = *p2p.peer_id();
9984 let mut keys = Vec::with_capacity(stored_keys.len());
9985 for k in stored_keys {
9986 if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
9987 keys.push(k);
9988 }
9989 }
9990
9991 if keys.is_empty() {
9992 // There used to be a second branch here that dropped every retained root outright
9993 // when the node looked empty. It is gone, and the reason is worth keeping.
9994 //
9995 // "Empty" was decided from key counts, and every version of that test was wrong in
9996 // the same direction. It read the committable set, which narrows to the file-backed
9997 // keys once the migration settles, so a node whose disk filled before it could copy
9998 // anything looked empty with a full legacy store beside it. Adding the raw file index
9999 // still missed a file dropped from the index by a failed read while its legacy copy
10000 // was being put back. Adding the legacy environment still missed a files-only node
10001 // that had published bytes to disk but not yet indexed them, because a file is
10002 // published before it is indexed. Each fix closed one window and left another.
10003 //
10004 // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10005 // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10006 // lane, which is enforced in every release and is not the lane the migration holds
10007 // off — so a node that still holds the bytes is slashed for holding them. Retiring
10008 // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10009 // instead of vanishing now. Both set `has_current = false`; they differ only in
10010 // whether the node goes on being answerable in the meantime. A genuinely empty node
10011 // cannot answer either way, so retiring costs it nothing it had.
10012 //
10013 // So there is one branch, and no emptiness question to get wrong.
10014 //
10015 // A peer may still be pinning a root we gossiped
10016 // moments ago and could demand its bytes in a round-2 challenge, which
10017 // we can still answer (the bytes are present). But we must STOP
10018 // advertising the stale commitment: retire it so `current()` returns
10019 // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10020 // The retired slot then ages out by its gossip-answerability TTL while
10021 // remaining answerable for in-flight pins until then. Once it ages out,
10022 // `is_held` flips false and the pruner reclaims the now-uncommitted,
10023 // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10024 // pointing at the stale root, which the gossip loop would keep
10025 // re-stamping — pinning its keys forever.)
10026 debug!(
10027 "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10028 (stays answerable until its gossip TTL lapses, bytes still on disk)"
10029 );
10030 state.retire_current();
10031 storage.note_commitment_rebuilt();
10032 return Ok(());
10033 }
10034
10035 // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10036 // to more than the protocol limit; auditor would reject the
10037 // commitment otherwise).
10038 let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10039 if keys.len() > cap {
10040 warn!(
10041 "Commitment rotation: key set ({}) exceeds MAX_COMMITMENT_KEY_COUNT ({}); \
10042 truncating — investigate as this likely means a misconfiguration",
10043 keys.len(),
10044 cap
10045 );
10046 }
10047
10048 // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10049 // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10050 // full chunk re-read per rotation.
10051 //
10052 // Consequence to be precise about: because the leaf is `(key, key)`,
10053 // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10054 // commitment therefore binds "which keys I claim to hold"; it does NOT
10055 // by itself prove byte possession. Byte possession is enforced by the
10056 // round-2 slice audit: a Bao verified slice decoded against the chunk
10057 // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10058 // nonce, so a responder that holds the key list but dropped the bytes
10059 // cannot answer. This is sound ONLY while keys are content addresses;
10060 // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10061 // (`evaluate_subtree_structure`), so a non-content-addressed
10062 // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10063 // earn credit for `key`. If this module is ever reused for
10064 // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10065 // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10066 let entries: Vec<_> = keys.into_iter().take(cap).map(|k| (k, k)).collect();
10067
10068 // No-op-rotation guard: compute just the Merkle root from `entries`
10069 // and compare against the currently-advertised commitment's root.
10070 // If they match, the key set is unchanged and a new rotation would
10071 // only swap a randomized ML-DSA signature for a fresh one — same
10072 // content, different commitment_hash. That invalidates every
10073 // outstanding `recent_provers` credit on this node across the
10074 // close group with no security benefit, breaking steady-state
10075 // quorum liveness on large nodes that can't re-audit every key
10076 // every rotation interval. Skip the rotation entirely when the
10077 // tree is unchanged.
10078 // Build the tree ONCE here (moving `entries`): it serves both the no-op
10079 // root check below and, if we proceed, the signed commitment via
10080 // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10081 // inside `BuiltCommitment::build`).
10082 let candidate_tree = commitment::MerkleTree::build(entries)
10083 .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10084 let candidate_root = candidate_tree.root();
10085 if let Some(current) = state.current() {
10086 if current.commitment().root == candidate_root {
10087 debug!(
10088 "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10089 hex::encode(candidate_root)
10090 );
10091 // Even though we skip re-signing (to avoid invalidating holder
10092 // credit), retention must still advance on the wall clock: a
10093 // previously-gossiped commitment that holds a now-out-of-range key
10094 // must be able to age out of the answerability window even when the
10095 // committed key set is frozen here for many rotations. Without this,
10096 // the no-op guard would pin a stale slot — and its key — forever.
10097 state.age_out();
10098 // The advertised commitment already equals the committable set, which is
10099 // exactly what the retirement gate is counting.
10100 storage.note_commitment_rebuilt();
10101 return Ok(());
10102 }
10103 }
10104
10105 let sk_bytes = identity.secret_key_bytes().to_vec();
10106 let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10107 .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10108 let pk_bytes = identity.public_key().as_bytes().to_vec();
10109 let peer_id_bytes = *p2p.peer_id().as_bytes();
10110
10111 let built = commitment_state::BuiltCommitment::build_from_tree(
10112 candidate_tree,
10113 &peer_id_bytes,
10114 &sk,
10115 &pk_bytes,
10116 )
10117 .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10118
10119 let hash = hex::encode(built.hash());
10120 let key_count = built.commitment().key_count;
10121 state.rotate(built);
10122 info!("Storage commitment rotated: hash={hash} key_count={key_count}");
10123 // Counted only on the paths where the advertised commitment now genuinely reflects
10124 // the committable set, never merely on having read it. The retirement gate is what
10125 // consumes this, and it authorises deleting the legacy store.
10126 storage.note_commitment_rebuilt();
10127 Ok(())
10128}
10129
10130#[cfg(test)]
10131#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10132mod tests {
10133
10134 /// The two fetch failures mean different things and must be charged differently.
10135 ///
10136 /// `NotFound` is a peer saying it does not hold the chunk, which is what a node
10137 /// part-way through the migration says about chunks it has legitimately given up, so
10138 /// it is the lane this release withholds. `Error` has a single producer, the
10139 /// responder's own storage read failing, and that is never about the migration.
10140 #[test]
10141 fn a_missing_chunk_and_a_failed_read_are_different_faults() {
10142 let key = [7u8; 32];
10143 assert_eq!(
10144 fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
10145 Some(FetchFault::UnheldChunk)
10146 );
10147 assert_eq!(
10148 fetch_fault_for(&protocol::FetchResponse::Error {
10149 key,
10150 reason: "read failed".to_string(),
10151 }),
10152 Some(FetchFault::ResponderFault)
10153 );
10154 assert_eq!(
10155 fetch_fault_for(&protocol::FetchResponse::Success {
10156 key,
10157 data: vec![1, 2, 3],
10158 }),
10159 None
10160 );
10161 }
10162
10163 /// The responder's answer says which fault it is, so the mapping from a storage read
10164 /// to a response is what the classification above rests on.
10165 ///
10166 /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10167 /// an I/O fault or a failed integrity check, reads as `Err`. Nothing in the migration
10168 /// turns the first into the second.
10169 #[tokio::test]
10170 async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10171 let dir = tempfile::tempdir().expect("temp dir");
10172 let storage = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
10173 root_dir: dir.path().to_path_buf(),
10174 verify_on_read: true,
10175 max_map_size: 0,
10176 disk_reserve: 0,
10177 })
10178 .await
10179 .expect("open store");
10180
10181 let absent = [9u8; 32];
10182 assert!(
10183 matches!(storage.get(&absent).await, Ok(None)),
10184 "a chunk this node does not hold must read as a plain miss, not a fault"
10185 );
10186
10187 // And the answer each read produces. A miss is `NotFound`, which is the withheld
10188 // lane; a failed read is `Error`, which is not.
10189 assert!(matches!(
10190 fetch_response_for(absent, Ok(None)),
10191 protocol::FetchResponse::NotFound { .. }
10192 ));
10193 assert!(matches!(
10194 fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10195 protocol::FetchResponse::Success { .. }
10196 ));
10197 assert!(matches!(
10198 fetch_response_for(
10199 absent,
10200 Err(crate::error::Error::Storage("read failed".into()))
10201 ),
10202 protocol::FetchResponse::Error { .. }
10203 ));
10204 }
10205 use super::*;
10206 use super::{
10207 apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10208 audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10209 config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10210 first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10211 quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10212 FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10213 FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10214 FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10215 };
10216 use crate::payment::VerificationContext;
10217 use crate::replication::audit::AuditTickResult;
10218 use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10219 use crate::replication::recent_provers::RecentProvers;
10220 use crate::replication::types::{AuditFailureReason, FailureEvidence};
10221 use lru::LruCache;
10222 use saorsa_core::identity::PeerId;
10223 use std::collections::HashMap;
10224 use std::num::NonZeroUsize;
10225 use std::sync::atomic::Ordering;
10226 use std::sync::Arc;
10227 use std::time::Duration;
10228 use std::time::Instant;
10229 use std::time::SystemTime;
10230
10231 #[test]
10232 fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10233 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10234 assert_eq!(match_replication_protocol(id), Some((id, false)));
10235 assert_eq!(
10236 match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10237 Some((id, true))
10238 );
10239 }
10240 assert_eq!(
10241 match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10242 None
10243 );
10244 assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10245 assert_eq!(match_replication_protocol(RR_PREFIX), None);
10246 }
10247
10248 #[test]
10249 fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10250 use crate::replication::protocol::{
10251 AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10252 SubtreeSliceChallenge,
10253 };
10254
10255 let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10256 challenge_id: 1,
10257 nonce: [0u8; 32],
10258 challenged_peer_id: [0u8; 32],
10259 expected_commitment_hash: [0u8; 32],
10260 openings: vec![],
10261 });
10262 let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10263 challenge_id: 1,
10264 nonce: [0u8; 32],
10265 challenged_peer_id: [0u8; 32],
10266 keys: vec![[0u8; 32]],
10267 });
10268 let digest_response =
10269 ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10270 let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10271 key: [0u8; 32],
10272 data: vec![],
10273 proof_of_payment: vec![],
10274 });
10275
10276 assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10277 assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10278
10279 for body in [&digest_challenge, &digest_response, &core] {
10280 assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10281 assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10282 }
10283
10284 for body in [&subtree, &digest_challenge, &digest_response, &core] {
10285 assert!(body_matches_protocol(body, response_protocol_for(body)));
10286 }
10287 }
10288
10289 fn test_peer(b: u8) -> PeerId {
10290 let mut bytes = [0u8; 32];
10291 bytes[0] = b;
10292 PeerId::from_bytes(bytes)
10293 }
10294
10295 /// A structurally valid offer for `data`: real content address, a proof of
10296 /// the minimum accepted size, distinguished by `proof_marker` so a test can
10297 /// tell whose proof came back out of the queue.
10298 fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10299 protocol::FreshReplicationOffer {
10300 key: crate::client::compute_address(&data),
10301 data,
10302 proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10303 }
10304 }
10305
10306 fn admit_test_offer(
10307 in_flight: &FreshOfferInFlight,
10308 offer: protocol::FreshReplicationOffer,
10309 source: PeerId,
10310 ) -> FreshOfferAdmission {
10311 FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10312 }
10313
10314 #[test]
10315 fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10316 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10317 let data = vec![0x11u8; 64];
10318
10319 let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10320 let FreshOfferAdmission::Opened(entry) = opened else {
10321 panic!("first offer for a key should open the entry")
10322 };
10323
10324 // A second sender contributes its proof instead of being turned away:
10325 // its bytes are provably the same, so only the proof is worth keeping.
10326 assert!(
10327 matches!(
10328 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10329 FreshOfferAdmission::Joined
10330 ),
10331 "a duplicate from a new source should queue its proof"
10332 );
10333 // The same peer twice is not extra evidence, just extra work.
10334 assert!(
10335 matches!(
10336 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10337 FreshOfferAdmission::DuplicateSource
10338 ),
10339 "one source should hold at most one queued proof per key"
10340 );
10341
10342 // An entry that outlived its handler would bar the key forever.
10343 drop(entry);
10344 assert!(
10345 matches!(
10346 admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10347 FreshOfferAdmission::Opened(_)
10348 ),
10349 "a released key should be openable again"
10350 );
10351 }
10352
10353 #[test]
10354 fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10355 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10356
10357 // A node only receives offers for keys close to its own ID, so accepted
10358 // keys share a long prefix. Any prefix-derived shard index would have
10359 // funnelled these two onto one lock and serialized them.
10360 let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10361 assert!(
10362 matches!(
10363 admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10364 FreshOfferAdmission::Opened(_)
10365 ),
10366 "distinct keys should never block each other"
10367 );
10368 }
10369
10370 /// The regression that motivated queueing proofs at all.
10371 ///
10372 /// A sender whose proof does not verify must cost the network its own
10373 /// attempt and nothing more. Refusing every later offer outright made the
10374 /// first arrival the only arrival, so one bad proof lost the record — and
10375 /// the delayed possession check then charged that absence to this node.
10376 #[test]
10377 fn a_failing_proof_hands_the_key_to_the_next_sender() {
10378 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10379 let data = vec![0x5Au8; 128];
10380 let forger = test_peer(0xF0);
10381 let genuine = test_peer(0x0F);
10382
10383 let FreshOfferAdmission::Opened(mut entry) =
10384 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10385 else {
10386 panic!("the first offer should open the entry");
10387 };
10388 assert!(
10389 matches!(
10390 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10391 FreshOfferAdmission::Joined
10392 ),
10393 "the genuine sender must not be turned away by the forger"
10394 );
10395
10396 let first = entry
10397 .next_attempt()
10398 .expect("the opener's proof comes first");
10399 assert_eq!(first.source, forger);
10400
10401 // Treat the forger's proof as failed: the next one is still reachable,
10402 // and it is tried against the bytes already held rather than a refetch.
10403 let second = entry
10404 .next_attempt()
10405 .expect("a failed proof must not consume the key");
10406 assert_eq!(second.source, genuine);
10407 assert_eq!(
10408 second.proof_of_payment,
10409 vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10410 );
10411 assert_eq!(
10412 entry.data(),
10413 data.as_slice(),
10414 "every proof is tried against the one copy of the bytes"
10415 );
10416
10417 // Draining the queue releases the key rather than stranding it.
10418 assert!(entry.next_attempt().is_none());
10419 assert!(
10420 matches!(
10421 admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10422 FreshOfferAdmission::Opened(_)
10423 ),
10424 "an exhausted entry should release its key"
10425 );
10426 }
10427
10428 /// The cap has to be a lifetime budget, not a queue depth.
10429 ///
10430 /// The handler pops a proof before verifying it, so gating admission on the
10431 /// *instantaneous* queue length lets a fresh source refill the slot that pop
10432 /// just freed. Each refill is another on-chain payment verification, run
10433 /// sequentially while the entry holds its admission permit and a worker
10434 /// slot, so a stream of distinct sources could keep one key's handler — and
10435 /// one of only four workers — busy indefinitely.
10436 #[test]
10437 fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10438 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10439 let data = vec![0x3Du8; 32];
10440
10441 let FreshOfferAdmission::Opened(mut entry) =
10442 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10443 else {
10444 panic!("the first offer should open the entry")
10445 };
10446
10447 // Drive pop-then-admit with a fresh source every time, exactly as a
10448 // sybil stream would. The budget must be spent by admissions, not
10449 // returned by pops.
10450 let mut admitted = 1;
10451 for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10452 let _ = entry.next_attempt();
10453 if matches!(
10454 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10455 FreshOfferAdmission::Joined
10456 ) {
10457 admitted += 1;
10458 }
10459 }
10460
10461 assert!(
10462 admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10463 "a key accepted {admitted} proofs over its lifetime, but the budget is \
10464 {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10465 );
10466 }
10467
10468 #[test]
10469 fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10470 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10471 let data = vec![0x2Cu8; 32];
10472
10473 // The opener occupies the first slot, so the cap is reached after
10474 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10475 let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10476 for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10477 let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10478 assert!(
10479 matches!(
10480 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10481 FreshOfferAdmission::Joined
10482 ),
10483 "sender {i} is within the legitimate close-group fan-out"
10484 );
10485 }
10486
10487 let surplus = test_peer(0xEE);
10488 assert!(
10489 matches!(
10490 admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10491 FreshOfferAdmission::Full
10492 ),
10493 "past the cap a proof is surplus: enough are already queued to place the record"
10494 );
10495 }
10496
10497 #[test]
10498 fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10499 assert!(!verification_request_exceeds_limit(
10500 config::MAX_VERIFICATION_KEYS_PER_CYCLE
10501 ));
10502 assert!(verification_request_exceeds_limit(
10503 config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10504 ));
10505 }
10506
10507 // The heavy round-1 limiter enforces the per-peer rate cooldown
10508 // and single-use round-1 → round-2 sessions.
10509 #[tokio::test]
10510 async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10511 let limiter = SubtreeRound1Limiter::new(
10512 Duration::from_secs(3600),
10513 config::MAX_CONCURRENT_SUBTREE_ROUND1,
10514 );
10515 let peer = test_peer(1);
10516
10517 // First round-1 is admitted; drop the guard so concurrency is free again.
10518 let guard = limiter.admit(&peer).await;
10519 assert!(guard.is_some(), "first round-1 admitted");
10520 drop(guard);
10521 // A second round-1 within the cooldown is dropped even though the heavy
10522 // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10523 assert!(
10524 limiter.admit(&peer).await.is_none(),
10525 "second round-1 within cooldown is rate-dropped"
10526 );
10527 // A different peer has its own cooldown.
10528 assert!(limiter.admit(&test_peer(2)).await.is_some());
10529
10530 // Session: opened by round 1, consumed exactly once by the matching round 2.
10531 let hash = [7u8; 32];
10532 let nonce = [9u8; 32];
10533 limiter.open_session(peer, 42, hash, nonce).await;
10534 // Wrong nonce / commitment does not match.
10535 assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10536 assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10537 // A round 2 with no prior round 1 (wrong challenge_id) misses.
10538 assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10539 // The matching round 2 consumes it — and only once (single-use).
10540 assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10541 assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10542 }
10543
10544 // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10545 // so a party holding several identities refills its allowance by rotating
10546 // between them and can keep the heavy pool busy indefinitely. The work
10547 // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10548 // so a fresh identity is refused exactly like a repeat caller once it is
10549 // spent. That is the difference between bounding concurrency and bounding
10550 // sustained work.
10551 #[tokio::test]
10552 async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10553 // Cooldown disabled so only the work budget can refuse anything.
10554 let limiter =
10555 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10556 assert!(
10557 limiter.admit(&test_peer(1)).await.is_some(),
10558 "a node starts with budget in hand so it can serve audits at once"
10559 );
10560
10561 // Serve enough proof work to run the balance into debt. Charging exactly
10562 // the burst would leave it at zero, which the next nanosecond of refill
10563 // lifts back above the line — the debt is the point.
10564 limiter
10565 .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10566 .await;
10567
10568 for id in 2..8u8 {
10569 assert!(
10570 limiter.admit(&test_peer(id)).await.is_none(),
10571 "a never-seen peer must still be refused while the budget is spent"
10572 );
10573 }
10574 }
10575
10576 // The budget is a rate, not a quota: it comes back on its own, so an honest
10577 // auditor blocked by a flood is only delayed. Carrying the debt is what
10578 // prices an expensive proof above a cheap one — without it, a proof reading
10579 // a maximal subtree would cost no more of the next caller's wait than a
10580 // one-leaf proof.
10581 #[test]
10582 fn round1_work_budget_carries_debt_and_refills_over_time() {
10583 let now = Instant::now();
10584 let at = |secs: u64| {
10585 now.checked_add(Duration::from_secs(secs))
10586 .unwrap_or_else(Instant::now)
10587 };
10588 let mut budget = Round1WorkBudget {
10589 balance: 0,
10590 last_refill: now,
10591 };
10592 assert!(!budget.has_budget(now), "empty means empty");
10593
10594 // A proof costing four seconds' worth of refill leaves four seconds of
10595 // debt, so the wait scales with what was actually served.
10596 budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10597 assert!(
10598 !budget.has_budget(at(3)),
10599 "still in debt three seconds after an over-large proof"
10600 );
10601 assert!(
10602 budget.has_budget(at(5)),
10603 "the debt is worked off at the refill rate"
10604 );
10605
10606 // Idle time does not bank unbounded credit for a later flood.
10607 budget.refill(at(24 * 60 * 60));
10608 assert_eq!(
10609 budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10610 "refill is capped at the burst size"
10611 );
10612 }
10613
10614 // The heavy round-1 pool size is the tightest bound the responder applies and
10615 // the one least backed by fleet measurement, so it is read from config rather
10616 // than baked into the binary: a fleet that lands on the wrong number retunes
10617 // instead of waiting for a release. These pin that the configured value is
10618 // what actually gates admission, and that a 0 degrades to slow, not to off —
10619 // a wedged-shut responder would read on every auditor as a graced timeout,
10620 // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10621 #[tokio::test]
10622 async fn round1_pool_size_comes_from_config() {
10623 // Cooldown disabled so only concurrency can refuse anything.
10624 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10625 let held = limiter.admit(&test_peer(1)).await;
10626 assert!(held.is_some(), "the single configured slot is admitted");
10627 assert!(
10628 limiter.admit(&test_peer(2)).await.is_none(),
10629 "a second concurrent round 1 is refused at a configured pool of 1, \
10630 proving admission follows config rather than the compiled-in default"
10631 );
10632 drop(held);
10633 assert!(
10634 limiter.admit(&test_peer(2)).await.is_some(),
10635 "the slot is reusable once the first proof completes"
10636 );
10637 }
10638
10639 #[tokio::test]
10640 async fn round1_pool_size_of_zero_is_clamped_to_one() {
10641 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10642 assert!(
10643 limiter.admit(&test_peer(1)).await.is_some(),
10644 "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10645 );
10646 }
10647
10648 fn test_key(b: u8) -> crate::ant_protocol::XorName {
10649 let mut k = [0u8; 32];
10650 k[0] = b;
10651 k
10652 }
10653
10654 #[test]
10655 fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10656 let source = test_peer(0x91);
10657 let corroborator = test_peer(0x92);
10658 let mut evidence = types::KeyVerificationEvidence {
10659 presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10660 paid_list: HashMap::new(),
10661 };
10662 let failed = KeyVerificationOutcome::QuorumFailed;
10663
10664 assert_eq!(
10665 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10666 Some((source, SingletonHintFault::RejectedByCloseGroup)),
10667 "a close-group rejection outranks the denial: the key does not exist, which is \
10668 a bad hint however the sender's own disk is doing"
10669 );
10670 assert_eq!(
10671 punishable_singleton_replica_hint_source(
10672 &HashSet::from([source, corroborator]),
10673 &failed,
10674 &evidence,
10675 ),
10676 None,
10677 "corroborated hints must not use the sole-source penalty lane"
10678 );
10679 assert_eq!(
10680 punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10681 None,
10682 "paid-list advertisements do not claim possession, so they leave the \
10683 replica-hint source set empty and cannot be penalized"
10684 );
10685
10686 evidence
10687 .presence
10688 .insert(source, PresenceEvidence::Unresolved);
10689 assert_eq!(
10690 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10691 Some((source, SingletonHintFault::RejectedByCloseGroup)),
10692 "definitive close-group rejection is punishable without direct contradiction"
10693 );
10694 assert_eq!(
10695 punishable_singleton_replica_hint_source(
10696 &HashSet::from([source]),
10697 &KeyVerificationOutcome::QuorumInconclusive,
10698 &evidence,
10699 ),
10700 None,
10701 "timeouts and inconclusive evidence are neutral"
10702 );
10703
10704 evidence.presence.insert(source, PresenceEvidence::Absent);
10705 assert_eq!(
10706 punishable_singleton_replica_hint_source(
10707 &HashSet::from([source]),
10708 &KeyVerificationOutcome::QuorumVerified {
10709 sources: vec![corroborator],
10710 },
10711 &evidence,
10712 ),
10713 Some((source, SingletonHintFault::DeniedPossession)),
10714 "an explicit denial is punishable regardless of the overall outcome, and is \
10715 classified separately because it is a statement about the sender's own \
10716 storage rather than about the key"
10717 );
10718 }
10719
10720 /// Build a round-2 slice challenge matching an open session. `openings` is
10721 /// empty: these tests exercise admission and session handling only, which
10722 /// run before any block is opened.
10723 fn slice_challenge(
10724 challenge_id: u64,
10725 commitment_hash: [u8; 32],
10726 nonce: [u8; 32],
10727 ) -> protocol::SubtreeSliceChallenge {
10728 protocol::SubtreeSliceChallenge {
10729 challenge_id,
10730 nonce,
10731 challenged_peer_id: [0u8; 32],
10732 expected_commitment_hash: commitment_hash,
10733 openings: Vec::new(),
10734 }
10735 }
10736
10737 // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10738 // responder caps MUST NOT burn the single-use round-1 session.
10739 //
10740 // The handler used to consume the session first and admit second, so a
10741 // transient local capacity drop permanently destroyed that audit exchange —
10742 // every retry hit the `no live round-1 session` path and got `Transient`,
10743 // even after load cleared. Turning momentary local load into a deterministic
10744 // round-2 miss costs the responder its whole-slice credit for that round.
10745 #[tokio::test]
10746 async fn capacity_refused_slice_challenge_preserves_round1_session() {
10747 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10748 let inflight = Arc::new(RwLock::new(HashMap::new()));
10749 let round1 =
10750 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10751 let peer = test_peer(0xB1);
10752 let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10753 let challenge = slice_challenge(id, hash, nonce);
10754
10755 round1.open_session(peer, id, hash, nonce).await;
10756
10757 // Saturate this peer's share so the next admission must be refused.
10758 let mut hold = Vec::new();
10759 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10760 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10761 .await
10762 {
10763 Ok(guard) => hold.push(guard),
10764 Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10765 }
10766 }
10767
10768 let refused =
10769 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10770 assert!(
10771 matches!(refused, SliceAdmission::Capacity(_)),
10772 "a saturated peer share must refuse on capacity, not on session"
10773 );
10774
10775 // Load clears. The session must have survived the refusal.
10776 drop(hold);
10777 let retried =
10778 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10779 assert!(
10780 matches!(retried, SliceAdmission::Admitted(_)),
10781 "the round-1 session must survive a capacity refusal so the retry succeeds"
10782 );
10783
10784 // Still single-use: the successful admission consumed it exactly once.
10785 drop(retried);
10786 let replayed =
10787 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10788 assert!(
10789 matches!(replayed, SliceAdmission::NoSession),
10790 "a consumed session must not be replayable"
10791 );
10792 }
10793
10794 // The permit taken for the session probe is released when the probe misses,
10795 // so an unsessioned flood cannot pin the responder pool shut.
10796 #[tokio::test]
10797 async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10798 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10799 let inflight = Arc::new(RwLock::new(HashMap::new()));
10800 let round1 =
10801 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10802 let peer = test_peer(0xB2);
10803 let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10804
10805 // Far more unsessioned challenges than the per-peer cap would allow if
10806 // the slot leaked on the miss path.
10807 for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
10808 let outcome =
10809 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10810 assert!(
10811 matches!(outcome, SliceAdmission::NoSession),
10812 "no session was ever opened, so every attempt must miss"
10813 );
10814 }
10815
10816 assert_eq!(
10817 semaphore.available_permits(),
10818 MAX_CONCURRENT_AUDIT_RESPONSES,
10819 "every global permit must be returned"
10820 );
10821 assert!(
10822 inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
10823 "no per-peer slot may be left occupied"
10824 );
10825 }
10826
10827 #[test]
10828 fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
10829 assert!(!audit_failure_revokes_holder_credit(
10830 &AuditFailureReason::Timeout
10831 ));
10832 assert!(audit_failure_revokes_holder_credit(
10833 &AuditFailureReason::DigestMismatch
10834 ));
10835 }
10836
10837 #[tokio::test]
10838 async fn audit_responder_admission_reports_per_peer_cap_full() {
10839 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10840 let inflight = Arc::new(RwLock::new(HashMap::new()));
10841 let peer = test_peer(0xA1);
10842
10843 let mut guards = Vec::new();
10844 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10845 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
10846 .await
10847 {
10848 Ok(guard) => guards.push(guard),
10849 Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
10850 }
10851 }
10852
10853 let Err(err) =
10854 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10855 else {
10856 panic!("admission should fail once per-peer cap is full");
10857 };
10858 assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
10859 assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
10860 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10861 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10862
10863 drop(guards);
10864 }
10865
10866 #[tokio::test]
10867 async fn audit_responder_admission_reports_global_pool_full() {
10868 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10869 let inflight = Arc::new(RwLock::new(HashMap::new()));
10870 let peer = test_peer(0xA2);
10871
10872 let mut held_global_permits = Vec::new();
10873 for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
10874 held_global_permits.push(
10875 Arc::clone(&semaphore)
10876 .try_acquire_owned()
10877 .expect("test should be able to exhaust the global pool"),
10878 );
10879 }
10880
10881 let Err(err) =
10882 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
10883 else {
10884 panic!("admission should fail once global pool is full");
10885 };
10886 assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
10887 assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
10888 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
10889 assert_eq!(err.peer_inflight, 0);
10890 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
10891
10892 drop(held_global_permits);
10893 }
10894
10895 #[tokio::test]
10896 async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
10897 let semaphore = Arc::new(Semaphore::new(1));
10898 let inflight = Arc::new(RwLock::new(HashMap::new()));
10899 let peer = test_peer(0xA3);
10900
10901 let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
10902 .await
10903 .expect("first responder should be admitted");
10904 assert_eq!(semaphore.available_permits(), 0);
10905 assert_eq!(inflight.read().await.get(&peer), Some(&1));
10906
10907 drop(guard);
10908 assert_eq!(semaphore.available_permits(), 1);
10909 assert!(!inflight.read().await.contains_key(&peer));
10910 }
10911
10912 #[tokio::test]
10913 async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
10914 let semaphore = Arc::new(Semaphore::new(1));
10915 let inflight = Arc::new(RwLock::new(HashMap::new()));
10916 let peer = test_peer(0xA4);
10917 let held_map = inflight.write().await;
10918
10919 let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
10920 assert!(
10921 tokio::time::timeout(Duration::from_millis(10), waiting)
10922 .await
10923 .is_err(),
10924 "admission should still be waiting for the peer map"
10925 );
10926
10927 drop(held_map);
10928 assert_eq!(semaphore.available_permits(), 1);
10929 assert!(!inflight.read().await.contains_key(&peer));
10930 }
10931
10932 #[test]
10933 fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
10934 let timeout = Duration::from_secs(1);
10935 let old_received_at = Instant::now()
10936 .checked_sub(timeout)
10937 .unwrap_or_else(Instant::now);
10938
10939 assert!(request_is_stale(old_received_at, timeout));
10940 assert!(!request_is_stale(Instant::now(), timeout));
10941 }
10942
10943 #[tokio::test]
10944 async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
10945 let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
10946 let inflight = Arc::new(RwLock::new(HashMap::new()));
10947 let first_peer = test_peer(0xB3);
10948 let second_peer = test_peer(0xB4);
10949
10950 let first_guard = admit_bounded_responder(
10951 &semaphore,
10952 &inflight,
10953 &first_peer,
10954 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10955 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10956 )
10957 .await
10958 .expect("first sync from a peer should be admitted");
10959 let duplicate = admit_bounded_responder(
10960 &semaphore,
10961 &inflight,
10962 &first_peer,
10963 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10964 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10965 )
10966 .await;
10967 let other_peer = admit_bounded_responder(
10968 &semaphore,
10969 &inflight,
10970 &second_peer,
10971 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
10972 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
10973 )
10974 .await;
10975
10976 assert!(matches!(
10977 duplicate,
10978 Err(ResponderAdmissionFailure {
10979 reason: ResponderRejectReason::PerPeerCapFull,
10980 ..
10981 })
10982 ));
10983 assert!(other_peer.is_ok());
10984 drop(first_guard);
10985 drop(other_peer);
10986 }
10987
10988 /// One flooding peer must not be able to hold every fresh-offer slot.
10989 ///
10990 /// This is the eviction primitive the per-peer share closes: with only a
10991 /// global bound, a single source occupies the pool, every honest offer in
10992 /// that window is refused, and because a refusal reads as absence to the
10993 /// sender's delayed possession check those refusals land as
10994 /// audit-severity penalties on *this* node.
10995 #[tokio::test]
10996 async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
10997 let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
10998 let inflight = Arc::new(RwLock::new(HashMap::new()));
10999 let flooder = test_peer(0xC1);
11000 let honest = test_peer(0xC2);
11001
11002 let mut held = Vec::new();
11003 for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11004 held.push(
11005 admit_bounded_responder(
11006 &semaphore,
11007 &inflight,
11008 &flooder,
11009 FRESH_OFFER_MAX_OUTSTANDING,
11010 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11011 )
11012 .await
11013 .expect("offers within the per-peer share are admitted"),
11014 );
11015 }
11016
11017 let flooder_excess = admit_bounded_responder(
11018 &semaphore,
11019 &inflight,
11020 &flooder,
11021 FRESH_OFFER_MAX_OUTSTANDING,
11022 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11023 )
11024 .await;
11025 assert!(
11026 matches!(
11027 flooder_excess,
11028 Err(ResponderAdmissionFailure {
11029 reason: ResponderRejectReason::PerPeerCapFull,
11030 ..
11031 })
11032 ),
11033 "one source must not exceed its fresh-offer share"
11034 );
11035
11036 let honest_offer = admit_bounded_responder(
11037 &semaphore,
11038 &inflight,
11039 &honest,
11040 FRESH_OFFER_MAX_OUTSTANDING,
11041 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11042 )
11043 .await;
11044 assert!(
11045 honest_offer.is_ok(),
11046 "an honest sender must still be admitted while another peer floods"
11047 );
11048
11049 assert!(
11050 usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11051 < FRESH_OFFER_MAX_OUTSTANDING,
11052 "the per-peer share must leave room for other sources"
11053 );
11054
11055 drop(held);
11056 drop(honest_offer);
11057 }
11058
11059 /// Paid notifies get the same per-source treatment as every other class.
11060 #[tokio::test]
11061 async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11062 let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11063 let inflight = Arc::new(RwLock::new(HashMap::new()));
11064 let flooder = test_peer(0xC3);
11065 let honest = test_peer(0xC4);
11066
11067 let mut held = Vec::new();
11068 for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11069 held.push(
11070 admit_bounded_responder(
11071 &semaphore,
11072 &inflight,
11073 &flooder,
11074 PAID_NOTIFY_MAX_OUTSTANDING,
11075 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11076 )
11077 .await
11078 .expect("notifies within the per-peer share are admitted"),
11079 );
11080 }
11081
11082 assert!(
11083 matches!(
11084 admit_bounded_responder(
11085 &semaphore,
11086 &inflight,
11087 &flooder,
11088 PAID_NOTIFY_MAX_OUTSTANDING,
11089 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11090 )
11091 .await,
11092 Err(ResponderAdmissionFailure {
11093 reason: ResponderRejectReason::PerPeerCapFull,
11094 ..
11095 })
11096 ),
11097 "one source must not exceed its paid-notify share"
11098 );
11099 assert!(
11100 admit_bounded_responder(
11101 &semaphore,
11102 &inflight,
11103 &honest,
11104 PAID_NOTIFY_MAX_OUTSTANDING,
11105 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11106 )
11107 .await
11108 .is_ok(),
11109 "an honest sender must still be admitted while another peer floods"
11110 );
11111
11112 drop(held);
11113 }
11114
11115 /// The fresh-offer per-source bound must guarantee headroom for a peer
11116 /// holding nothing, without throttling a single legitimate fan-out.
11117 ///
11118 /// Sized as a quota rather than a reserve, this bound refused offers during
11119 /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11120 /// refusal is charged to THIS node at audit severity because the sender
11121 /// never reads it.
11122 #[test]
11123 fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11124 let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11125
11126 assert_eq!(
11127 FRESH_OFFER_MAX_OUTSTANDING - share,
11128 FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11129 "a source holding none must always find a free slot"
11130 );
11131 assert!(
11132 share < FRESH_OFFER_MAX_OUTSTANDING,
11133 "one peer must not be able to take the whole pool"
11134 );
11135 // The failure this pins: a share sized like the request/response
11136 // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11137 // one-way bulk traffic.
11138 assert!(
11139 share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11140 "fresh offers are one-way bulk, not request/response — their share \
11141 must not be sized like the request classes'"
11142 );
11143 }
11144
11145 /// A malformed offer must be refused before it can occupy an admission
11146 /// slot, so junk cannot hold capacity for the length of a verification.
11147 #[test]
11148 fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11149 let key = test_key(0xC5);
11150
11151 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11152
11153 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11154 .expect("an offer with no proof must be refused");
11155 assert!(
11156 rejection.penalise,
11157 "an honest sender always attaches a proof"
11158 );
11159
11160 // A proof is retained per queued sender, so its size has to be bounded
11161 // here rather than at the verifier, which only sees it on a worker.
11162 let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11163 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11164 .expect("an undersized proof must be refused");
11165 assert!(
11166 rejection.penalise,
11167 "no honest sender constructs an undersized proof"
11168 );
11169 let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11170 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11171 .expect("an oversized proof must be refused");
11172 assert!(
11173 rejection.penalise,
11174 "no honest sender constructs an oversized proof"
11175 );
11176
11177 let rejection = fresh_offer_structural_rejection(
11178 &key,
11179 &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11180 &valid_proof,
11181 )
11182 .expect("an oversized offer must be refused");
11183 assert!(
11184 rejection.penalise,
11185 "no honest sender constructs an oversized offer"
11186 );
11187
11188 let data = vec![0u8; 1];
11189 assert!(
11190 fresh_offer_structural_rejection(
11191 &crate::client::compute_address(&data),
11192 &data,
11193 &valid_proof
11194 )
11195 .is_none(),
11196 "a well-formed offer must reach admission"
11197 );
11198 }
11199
11200 /// Knowing a key must not be enough to enter its entry.
11201 ///
11202 /// Opening an entry on an unverified key/bytes association would let a peer
11203 /// that has only *learned* the key — every recipient of its `PaidNotify`,
11204 /// not just the close group that gets the chunk — seize it with junk.
11205 /// Joining one would be worse: the handler tries each queued proof against
11206 /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11207 /// on bytes it never offered.
11208 #[test]
11209 fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11210 let genuine_data = vec![0x5Au8; 128];
11211 let key = crate::client::compute_address(&genuine_data);
11212 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11213
11214 let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11215 .expect("bytes that do not hash to the advertised key must be refused");
11216 assert!(
11217 rejection.penalise,
11218 "no honest sender offers bytes that do not hash to the advertised key"
11219 );
11220
11221 // Dispatch reaches the entry only past that rejection, so the forged
11222 // offer never touched the key and the genuine one still opens it.
11223 assert!(
11224 fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11225 "the offer that actually carries the key's bytes must reach the entry"
11226 );
11227
11228 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11229 assert!(
11230 matches!(
11231 admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11232 FreshOfferAdmission::Opened(_)
11233 ),
11234 "an offer refused on payload shape must leave the key openable"
11235 );
11236 }
11237
11238 #[tokio::test]
11239 async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11240 let peer = test_peer(0xA5);
11241 let key = test_key(0xA5);
11242 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11243 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11244 let is_bootstrapping = Arc::new(RwLock::new(true));
11245 let bootstrap_complete_notify = Arc::new(Notify::new());
11246
11247 let now = Instant::now();
11248 queues.write().await.add_pending_verify(
11249 key,
11250 VerificationEntry {
11251 state: VerificationState::PendingVerify,
11252 verified_sources: Vec::new(),
11253 tried_sources: HashSet::new(),
11254 created_at: now,
11255 next_verify_at: now,
11256 hint_sources: HashSet::from([peer]),
11257 replica_hint_sources: HashSet::from([peer]),
11258 unresolved_retries: 0,
11259 no_holder_reported: false,
11260 },
11261 );
11262 super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11263 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11264 {
11265 let q = queues.read().await;
11266 assert!(
11267 !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11268 "capacity rejection should initially block bootstrap drain"
11269 );
11270 }
11271
11272 update_bootstrap_after_peer_removed(
11273 &peer,
11274 &bootstrap_state,
11275 &queues,
11276 &is_bootstrapping,
11277 &bootstrap_complete_notify,
11278 )
11279 .await;
11280
11281 let state = bootstrap_state.read().await;
11282 assert!(state.capacity_rejected_sources.is_empty());
11283 assert!(state.pending_keys.is_empty());
11284 assert!(state.is_drained());
11285 drop(state);
11286 assert!(!*is_bootstrapping.read().await);
11287 }
11288
11289 /// A fairness displacement forfeits the key but must not stamp its former
11290 /// owner: the owner did nothing wrong, and stamping it lets a flooding
11291 /// source block bootstrap drain through an unrelated honest peer.
11292 #[tokio::test]
11293 async fn fairness_displacement_does_not_stamp_its_victim() {
11294 let displaced_owner = test_peer(0xB1);
11295 let incoming_source = test_peer(0xB2);
11296 let displaced_key = test_key(0xB1);
11297 let admitted_key = test_key(0xB2);
11298 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11299 {
11300 let mut state = bootstrap_state.write().await;
11301 state.pending_keys.insert(displaced_key);
11302 state
11303 .capacity_rejected_sources
11304 .insert(incoming_source, Instant::now());
11305 }
11306 let outcomes = [(
11307 incoming_source,
11308 AdmissionOutcome {
11309 discovered: HashSet::from([admitted_key]),
11310 capacity_rejected_count: 0,
11311 displaced: vec![CapacityDisplacement {
11312 key: displaced_key,
11313 owner: displaced_owner,
11314 }],
11315 },
11316 )];
11317
11318 publish_bootstrap_admission_outcomes(
11319 &bootstrap_state,
11320 &outcomes,
11321 &HashSet::from([admitted_key]),
11322 )
11323 .await;
11324
11325 let state = bootstrap_state.read().await;
11326 assert!(!state.pending_keys.contains(&displaced_key));
11327 assert!(state.pending_keys.contains(&admitted_key));
11328 assert!(
11329 !state
11330 .capacity_rejected_sources
11331 .contains_key(&displaced_owner),
11332 "the displaced owner must not be charged for our own fairness reclaim"
11333 );
11334 assert!(!state
11335 .capacity_rejected_sources
11336 .contains_key(&incoming_source));
11337 }
11338
11339 /// A source that keeps overflowing us must not keep its own record fresh.
11340 ///
11341 /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11342 /// rejection the debt could never age out, so `check_bootstrap_drained`
11343 /// stayed false forever and auditing never started (Invariant 19).
11344 #[tokio::test]
11345 async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11346 const REJECTION_ROUNDS: usize = 5;
11347
11348 let source = test_peer(0xB3);
11349 let key = test_key(0xB3);
11350 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11351
11352 let first_seen = {
11353 let outcomes = [(
11354 source,
11355 AdmissionOutcome {
11356 discovered: HashSet::new(),
11357 capacity_rejected_count: 1,
11358 displaced: Vec::new(),
11359 },
11360 )];
11361 publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11362 .await;
11363 bootstrap_state
11364 .read()
11365 .await
11366 .capacity_rejected_sources
11367 .get(&source)
11368 .copied()
11369 .expect("first rejection recorded")
11370 };
11371
11372 for _ in 0..REJECTION_ROUNDS {
11373 let outcomes = [(
11374 source,
11375 AdmissionOutcome {
11376 discovered: HashSet::from([key]),
11377 capacity_rejected_count: 1,
11378 displaced: Vec::new(),
11379 },
11380 )];
11381 publish_bootstrap_admission_outcomes(
11382 &bootstrap_state,
11383 &outcomes,
11384 &HashSet::from([key]),
11385 )
11386 .await;
11387 }
11388
11389 let recorded = bootstrap_state
11390 .read()
11391 .await
11392 .capacity_rejected_sources
11393 .get(&source)
11394 .copied()
11395 .expect("debt still outstanding");
11396 assert_eq!(
11397 recorded, first_seen,
11398 "repeat rejections must not restart the expiry clock"
11399 );
11400 }
11401
11402 /// The verification-worker tick's self-heal path: a capacity rejection
11403 /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11404 /// blocks drain until the TTL expires it, at which point the same tick
11405 /// completes bootstrap without any external event.
11406 #[tokio::test]
11407 async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11408 let peer = test_peer(0xA6);
11409 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11410 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11411 let is_bootstrapping = Arc::new(RwLock::new(true));
11412 let bootstrap_complete_notify = Arc::new(Notify::new());
11413
11414 // PeerRemoved was fully processed before the rejection landed, so no
11415 // future event will ever clear this entry.
11416 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11417
11418 // Within the TTL the tick keeps waiting for re-delivery.
11419 expire_and_recheck_bootstrap_drain(
11420 &bootstrap_state,
11421 &queues,
11422 &is_bootstrapping,
11423 &bootstrap_complete_notify,
11424 ReplicationConfig::default().capacity_rejected_max_age(),
11425 )
11426 .await;
11427 assert!(!bootstrap_state.read().await.is_drained());
11428 assert!(*is_bootstrapping.read().await);
11429
11430 // Past the TTL the tick expires the orphan and completes bootstrap.
11431 expire_and_recheck_bootstrap_drain(
11432 &bootstrap_state,
11433 &queues,
11434 &is_bootstrapping,
11435 &bootstrap_complete_notify,
11436 Duration::ZERO,
11437 )
11438 .await;
11439 assert!(bootstrap_state.read().await.is_drained());
11440 assert!(!*is_bootstrapping.read().await);
11441 }
11442
11443 #[test]
11444 fn first_audit_terminal_outcomes_are_stable() {
11445 let peer = test_peer(1);
11446 let passed = AuditTickResult::Passed {
11447 challenged_peer: peer,
11448 keys_checked: 1,
11449 };
11450 let timed_out = AuditTickResult::Failed {
11451 evidence: FailureEvidence::AuditFailure {
11452 challenge_id: 1,
11453 challenged_peer: peer,
11454 confirmed_failed_keys: vec![test_key(1)],
11455 summary: crate::replication::types::AuditFailureSummary::default(),
11456 reason: AuditFailureReason::Timeout,
11457 },
11458 no_response_class: Some("timeout"),
11459 };
11460
11461 assert_eq!(
11462 first_audit_terminal_outcome(&passed),
11463 FirstAuditTerminalOutcome::Passed
11464 );
11465 assert_eq!(
11466 first_audit_terminal_outcome(&timed_out),
11467 FirstAuditTerminalOutcome::Timeout
11468 );
11469 assert_eq!(
11470 first_audit_terminal_outcome(&AuditTickResult::Idle),
11471 FirstAuditTerminalOutcome::Idle
11472 );
11473 assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11474 assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11475 assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11476 assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11477 assert_eq!(
11478 FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11479 "insufficient_keys"
11480 );
11481 assert_eq!(
11482 FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11483 "bootstrap_claim"
11484 );
11485 }
11486
11487 #[test]
11488 fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11489 let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11490 let mut rng = StdRng::seed_from_u64(7);
11491 let peer = test_peer(1);
11492 let base = MonetizedPinEvent {
11493 peer,
11494 pin: [1; 32],
11495 key_count: 100,
11496 quote_ts: SystemTime::now(),
11497 };
11498
11499 // First insert into an empty slot: Queued.
11500 assert_eq!(
11501 coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11502 FirstAuditQueueOutcome::Queued
11503 );
11504
11505 // A strictly LOWER-count same-peer nomination must NOT displace it.
11506 let lower = MonetizedPinEvent {
11507 pin: [2; 32],
11508 key_count: 50,
11509 ..base
11510 };
11511 assert_eq!(
11512 coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11513 FirstAuditQueueOutcome::SuppressedLower
11514 );
11515 assert_eq!(
11516 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11517 Some(([1; 32], 100)),
11518 "the higher-count pin is retained"
11519 );
11520
11521 // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11522 let higher = MonetizedPinEvent {
11523 pin: [3; 32],
11524 key_count: 400,
11525 ..base
11526 };
11527 assert_eq!(
11528 coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11529 FirstAuditQueueOutcome::Coalesced
11530 );
11531 assert_eq!(
11532 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11533 Some(([3; 32], 400))
11534 );
11535
11536 // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11537 let equal_newer = MonetizedPinEvent {
11538 pin: [4; 32],
11539 key_count: 400,
11540 ..base
11541 };
11542 assert_eq!(
11543 coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11544 FirstAuditQueueOutcome::Coalesced
11545 );
11546 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11547 // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11548 let equal_older = MonetizedPinEvent {
11549 pin: [5; 32],
11550 key_count: 400,
11551 ..base
11552 };
11553 assert_eq!(
11554 coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11555 FirstAuditQueueOutcome::RetainedOnTie
11556 );
11557 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11558
11559 // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11560 let other_peer = MonetizedPinEvent {
11561 peer: test_peer(2),
11562 pin: [6; 32],
11563 key_count: 100,
11564 ..base
11565 };
11566 assert_eq!(
11567 coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11568 FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11569 );
11570 assert_eq!(pending.len(), 1);
11571 assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11572 }
11573
11574 // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11575
11576 #[test]
11577 fn first_audit_limiter_enforces_burst_then_refills() {
11578 let base = Instant::now();
11579 let mut limiter = FirstAuditLimiter::new(base);
11580 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11581
11582 // The full burst is admitted back-to-back (distinct peers).
11583 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11584 let peer = test_peer(u8::try_from(i).expect("small burst"));
11585 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11586 limiter.commit_launch(peer, 10, base);
11587 }
11588 // Bucket empty: the next distinct peer is deferred, never dropped.
11589 let extra = test_peer(0xEE);
11590 assert_eq!(
11591 limiter.assess(&extra, 10, base, 0),
11592 LimiterVerdict::RateDeferred
11593 );
11594
11595 // One full interval later exactly one token is available again.
11596 let later = base + interval;
11597 assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11598 limiter.commit_launch(extra, 10, later);
11599 let extra2 = test_peer(0xEF);
11600 assert_eq!(
11601 limiter.assess(&extra2, 10, later, 0),
11602 LimiterVerdict::RateDeferred
11603 );
11604 }
11605
11606 #[test]
11607 fn first_audit_limiter_refill_keeps_fractional_remainder() {
11608 let base = Instant::now();
11609 let mut limiter = FirstAuditLimiter::new(base);
11610 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11611 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11612 let peer = test_peer(u8::try_from(i).expect("small burst"));
11613 assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11614 limiter.commit_launch(peer, 1, base);
11615 }
11616 // 1.5 intervals later one token is earned and the half interval is
11617 // NOT lost to drift...
11618 let at_1_5 = base + interval + interval / 2;
11619 let p = test_peer(0xAA);
11620 assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11621 limiter.commit_launch(p, 1, at_1_5);
11622 // ...so the next token arrives at 2.0 intervals, not 2.5.
11623 let at_2_0 = base + interval * 2;
11624 let q = test_peer(0xAB);
11625 assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11626 }
11627
11628 #[test]
11629 fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11630 let base = Instant::now();
11631 let mut limiter = FirstAuditLimiter::new(base);
11632 let peer = test_peer(1);
11633 assert_eq!(
11634 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11635 LimiterVerdict::RateDeferred
11636 );
11637 // A freed slot admits without any clock movement.
11638 assert_eq!(
11639 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11640 LimiterVerdict::Admit
11641 );
11642 }
11643
11644 #[test]
11645 fn first_audit_limiter_assess_consumes_nothing() {
11646 let base = Instant::now();
11647 let mut limiter = FirstAuditLimiter::new(base);
11648 let peer = test_peer(3);
11649 // Repeated assessment must not burn budget or stamp the window: only
11650 // `commit_launch` consumes (the cooldown gate between assess and
11651 // commit can defer, and that deferral must be free).
11652 for _ in 0..10 {
11653 assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11654 }
11655 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11656 let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11657 assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11658 limiter.commit_launch(p, 5, base);
11659 }
11660 }
11661
11662 #[test]
11663 fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11664 let base = Instant::now();
11665 let mut limiter = FirstAuditLimiter::new(base);
11666 let peer = test_peer(7);
11667 assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11668 limiter.commit_launch(peer, 100, base);
11669
11670 // A rotated pin with a similar count inside the window is dropped...
11671 let soon = base + Duration::from_secs(60);
11672 assert_eq!(
11673 limiter.assess(&peer, 100, soon, 0),
11674 LimiterVerdict::WindowDeduped
11675 );
11676 // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11677 assert_eq!(
11678 limiter.assess(&peer, 150, soon, 0),
11679 LimiterVerdict::WindowDeduped
11680 );
11681 // ...but a >1.5x committed-count jump re-nominates immediately (an
11682 // inflated sidecar-only pin is invisible to the gossip lottery, so
11683 // the window must not shield it).
11684 assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11685
11686 // Window expiry re-admits an unchanged count.
11687 let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11688 assert_eq!(
11689 limiter.assess(&peer, 100, expired, 0),
11690 LimiterVerdict::Admit
11691 );
11692 }
11693
11694 #[test]
11695 fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11696 // A window-deduped nomination must be DROPPED, not kept pending as
11697 // rate-deferred, even when the bucket is also empty: re-queuing a
11698 // suppressed rotation would hold a pending slot for two hours.
11699 let base = Instant::now();
11700 let mut limiter = FirstAuditLimiter::new(base);
11701 let peer = test_peer(9);
11702 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11703 limiter.commit_launch(peer, 10, base);
11704 let other = test_peer(10);
11705 assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11706 limiter.commit_launch(other, 10, base);
11707 assert_eq!(
11708 limiter.assess(&peer, 10, base, 0),
11709 LimiterVerdict::WindowDeduped
11710 );
11711 }
11712
11713 /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11714 /// is answerable now but would age out of the answerability window during
11715 /// the launch jitter, so scheduling state is only ever committed for a pin
11716 /// that can still be challenged when it actually sends.
11717 #[test]
11718 fn first_audit_horizon_prefilter_boundary() {
11719 let now = SystemTime::now();
11720 // C = the too-old cutoff; H = the worst-case send horizon.
11721 let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11722 let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11723 // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11724 let boundary = now
11725 .checked_add(h)
11726 .and_then(|t| t.checked_sub(c))
11727 .expect("boundary time");
11728
11729 // In window at `now` (age = C - H < C)...
11730 assert!(quote_within_audit_window(boundary, now));
11731 // ...but the horizon prefilter rejects it (age == C at now + H).
11732 assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11733
11734 // A hair newer stays answerable through the horizon; a hair older does
11735 // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11736 // a nanosecond step would round to the same instant there.
11737 let newer = boundary
11738 .checked_add(Duration::from_micros(1))
11739 .expect("newer");
11740 let older = boundary
11741 .checked_sub(Duration::from_micros(1))
11742 .expect("older");
11743 assert!(quote_answerable_through_nominal_jitter(newer, now));
11744 assert!(!quote_answerable_through_nominal_jitter(older, now));
11745
11746 // A quote too far in the FUTURE is rejected at `now`, independent of the
11747 // horizon.
11748 let future = now
11749 .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11750 .and_then(|t| t.checked_add(Duration::from_secs(60)))
11751 .expect("future");
11752 assert!(!quote_answerable_through_nominal_jitter(future, now));
11753 }
11754
11755 /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11756 /// answerability check fails at promotion is fully state-neutral — it stamps
11757 /// no `first_audited`, no per-peer window, refunds its token, releases its
11758 /// in-flight slot, does not flip the lane, and does not count a launch — and
11759 /// a same-peer, same-count successor enqueued DURING the reservation is
11760 /// retained and becomes the next reservation after the cancel. This is the
11761 /// exact hole the reviewer flagged: suppression must never outlive a launch
11762 /// that did not send.
11763 /// A pending pin that has aged past the answerability horizon must not
11764 /// suppress a live lower-count nomination for the same peer: under token
11765 /// starvation no reserve scan ever collects the dead entry, so without the
11766 /// enqueue-time check the peer would stay unauditable through this path
11767 /// indefinitely (e.g. after a prune legitimately lowered its key count).
11768 #[test]
11769 fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11770 let obs = Arc::new(FirstAuditObservability::default());
11771 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11772 let peer = test_peer(1);
11773
11774 let dead_quote = SystemTime::now()
11775 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11776 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
11777 .expect("past wall time");
11778 let stale_high = MonetizedPinEvent {
11779 peer,
11780 pin: [1; 32],
11781 key_count: 400,
11782 quote_ts: dead_quote,
11783 };
11784 scheduler.enqueue(stale_high, &obs);
11785 assert_eq!(scheduler.pending_len(), 1);
11786
11787 // A fresh, lower-count nomination (a post-prune commitment).
11788 let fresh_lower = MonetizedPinEvent {
11789 peer,
11790 pin: [2; 32],
11791 key_count: 100,
11792 quote_ts: SystemTime::now(),
11793 };
11794 scheduler.enqueue(fresh_lower, &obs);
11795
11796 assert_eq!(scheduler.pending_len(), 1);
11797 assert_eq!(
11798 scheduler.pending.peek(&peer).map(|e| e.pin),
11799 Some([2; 32]),
11800 "the live nomination replaced the dead incumbent"
11801 );
11802 assert_eq!(
11803 obs.suppressed_lower.load(Ordering::Relaxed),
11804 0,
11805 "no self-erasure signal for displacing a dead pin"
11806 );
11807 assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
11808 assert_eq!(
11809 obs.outside_answerability_window.load(Ordering::Relaxed),
11810 1,
11811 "the dead incumbent is accounted as an expiry"
11812 );
11813 }
11814
11815 /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
11816 /// nomination still loses to an answerable higher-count pending pin.
11817 #[test]
11818 fn first_audit_live_incumbent_still_suppresses_lower_count() {
11819 let obs = Arc::new(FirstAuditObservability::default());
11820 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11821 let peer = test_peer(1);
11822
11823 let live_high = MonetizedPinEvent {
11824 peer,
11825 pin: [1; 32],
11826 key_count: 400,
11827 quote_ts: SystemTime::now(),
11828 };
11829 scheduler.enqueue(live_high, &obs);
11830 let cheaper = MonetizedPinEvent {
11831 peer,
11832 pin: [2; 32],
11833 key_count: 100,
11834 quote_ts: SystemTime::now(),
11835 };
11836 scheduler.enqueue(cheaper, &obs);
11837
11838 assert_eq!(scheduler.pending_len(), 1);
11839 assert_eq!(
11840 scheduler.pending.peek(&peer).map(|e| e.pin),
11841 Some([1; 32]),
11842 "the higher-count live pin is retained"
11843 );
11844 assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
11845 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
11846 }
11847
11848 /// A fresh nomination for peer `b` (distinct pin per peer).
11849 fn live_nomination(b: u8) -> MonetizedPinEvent {
11850 MonetizedPinEvent {
11851 peer: test_peer(b),
11852 pin: [b; 32],
11853 key_count: 100,
11854 quote_ts: SystemTime::now(),
11855 }
11856 }
11857
11858 /// The pending admission cap must equal the number of usable launches the
11859 /// token budget can perform inside one answerability window, counted by
11860 /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
11861 /// tokens at age zero, one refill per launch interval), not by repeating
11862 /// the derivation formula. Any larger and admitted work is guaranteed to
11863 /// expire unlaunched; any smaller and the budget idles while nominations
11864 /// are displaced.
11865 #[test]
11866 fn first_audit_pending_cap_matches_strict_launch_horizon() {
11867 let quote_ts = SystemTime::now();
11868 // Burst launches fire at age zero and must pass the reserve predicate.
11869 assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
11870 let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
11871 let mut refill = 1u32;
11872 loop {
11873 let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
11874 let at = quote_ts + age;
11875 if !quote_answerable_through_nominal_jitter(quote_ts, at) {
11876 break;
11877 }
11878 usable += 1;
11879 refill += 1;
11880 assert!(refill < 10_000, "runaway horizon simulation");
11881 }
11882 assert_eq!(
11883 FIRST_AUDIT_PENDING_CAP, usable,
11884 "cap must match the simulated strict launch horizon"
11885 );
11886 }
11887
11888 /// The pending queue is sized to the launch budget while the dedup set
11889 /// keeps the commitment-cache bound: shrinking `first_audited` would
11890 /// forget audited pins and re-admit duplicates.
11891 #[test]
11892 fn first_audit_pending_cap_independent_of_dedup_cap() {
11893 let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11894 assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
11895 assert_eq!(
11896 scheduler.first_audited.cap().get(),
11897 MAX_LAST_COMMITMENT_BY_PEER
11898 );
11899 }
11900
11901 /// Admission beyond the cap displaces exactly one incumbent per overflow
11902 /// and every displacement is accounted as `capacity_evicted` — the steady
11903 /// overload signal — never silent loss, and never an admission refusal.
11904 #[test]
11905 fn first_audit_admission_beyond_cap_displaces_and_counts() {
11906 let obs = Arc::new(FirstAuditObservability::default());
11907 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11908 let overflow: usize = 5;
11909 let total = FIRST_AUDIT_PENDING_CAP + overflow;
11910
11911 for i in 0..total {
11912 let b = u8::try_from(i + 1).expect("test peer count fits u8");
11913 scheduler.enqueue(live_nomination(b), &obs);
11914 }
11915
11916 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11917 assert_eq!(
11918 obs.capacity_evicted.load(Ordering::Relaxed),
11919 u64::try_from(overflow).expect("overflow fits u64"),
11920 "each admission past the cap displaces exactly one entry"
11921 );
11922 assert_eq!(
11923 obs.queued.load(Ordering::Relaxed),
11924 u64::try_from(total).expect("total fits u64"),
11925 "displacement is not an admission refusal"
11926 );
11927 // Every arrival was admitted (the newest always enters the sample).
11928 let last = u8::try_from(total).expect("test peer count fits u8");
11929 assert!(
11930 scheduler.pending.peek(&test_peer(last)).is_some(),
11931 "the newest arrival always enters the sample"
11932 );
11933 }
11934
11935 /// The reviewer-demonstrated suppression route: a target followed by an
11936 /// ordered batch of distinct-peer nominations, all inside one ingress
11937 /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
11938 /// the token bucket EMPTY so no reservation can intervene. Under the old
11939 /// keep-newest LRU the target was evicted with certainty; under random
11940 /// displacement its per-overflow eviction probability is `1/cap`, so
11941 /// across repeated trials the target must survive some runs and be
11942 /// displaced in others — never deterministically flushed, and every
11943 /// displacement accounted.
11944 #[test]
11945 fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
11946 let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
11947 assert!(FIRST_AUDIT_PENDING_CAP < flood);
11948 assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
11949
11950 let trials = 100u64;
11951 let mut survived = 0u32;
11952 let mut evicted = 0u32;
11953 for trial in 0..trials {
11954 let obs = Arc::new(FirstAuditObservability::default());
11955 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11956 // Deterministic per-trial seed: the run is fully reproducible (no
11957 // flake budget at all) while still exercising 100 distinct
11958 // eviction sequences.
11959 scheduler.rng = StdRng::seed_from_u64(trial);
11960 // Drain the burst tokens so the pre-overflow reservation
11961 // opportunity cannot fire: this isolates pure retention.
11962 scheduler.limiter.reserve_token();
11963 scheduler.limiter.reserve_token();
11964
11965 let target = test_peer(200);
11966 scheduler.enqueue(live_nomination(200), &obs);
11967 for i in 0..flood {
11968 let b = u8::try_from(i + 1).expect("flood peer fits u8");
11969 scheduler.enqueue(live_nomination(b), &obs);
11970 }
11971
11972 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
11973 let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
11974 .expect("overflow count fits u64");
11975 assert_eq!(
11976 obs.capacity_evicted.load(Ordering::Relaxed),
11977 overflows,
11978 "every overflow past the cap is accounted, none silent"
11979 );
11980 if scheduler.pending.peek(&target).is_some() {
11981 survived += 1;
11982 } else {
11983 evicted += 1;
11984 }
11985 }
11986 // With eviction probability 1/cap per overflow, P(target survives one
11987 // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
11988 // 100 seeded trials — and the seeds make the split exactly
11989 // reproducible rather than a (vanishingly small) flake budget.
11990 assert!(
11991 survived > 0,
11992 "target must survive some ordered floods — deterministic eviction \
11993 would mean keep-newest retention regressed"
11994 );
11995 assert!(
11996 evicted > 0,
11997 "target must also be displaceable — otherwise overflow is refusing \
11998 admissions instead of sampling"
11999 );
12000 }
12001
12002 /// With a token AVAILABLE, an overflowing arrival must first give pending
12003 /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12004 /// one entry out of the queue, so admission proceeds without any eviction.
12005 #[test]
12006 fn first_audit_overflow_reserves_before_destructive_eviction() {
12007 let obs = Arc::new(FirstAuditObservability::default());
12008 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12009 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12010
12011 for i in 0..FIRST_AUDIT_PENDING_CAP {
12012 let b = u8::try_from(i + 1).expect("test peer count fits u8");
12013 scheduler.enqueue(live_nomination(b), &obs);
12014 }
12015 let overflowing = live_nomination(250);
12016 assert!(scheduler.would_displace(&overflowing));
12017
12018 // The drainer's pre-overflow sequence: reserve, then enqueue.
12019 assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12020 assert!(
12021 !scheduler.would_displace(&overflowing),
12022 "a successful reservation frees the slot"
12023 );
12024 scheduler.enqueue(overflowing, &obs);
12025
12026 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12027 assert_eq!(
12028 obs.capacity_evicted.load(Ordering::Relaxed),
12029 0,
12030 "no destructive eviction when a launch opportunity existed"
12031 );
12032 }
12033
12034 /// Displacement stamps no suppression state: a displaced peer's next
12035 /// nomination re-enters like any newcomer (it is NOT window-deduped or
12036 /// treated as a duplicate), so under overload every peer keeps an
12037 /// unpredictable chance of prompt first audit.
12038 #[test]
12039 fn first_audit_displaced_peer_may_be_renominated() {
12040 let obs = Arc::new(FirstAuditObservability::default());
12041 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12042 let total = FIRST_AUDIT_PENDING_CAP + 1;
12043
12044 for i in 0..total {
12045 let b = u8::try_from(i + 1).expect("test peer count fits u8");
12046 scheduler.enqueue(live_nomination(b), &obs);
12047 }
12048 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12049 // Find whichever peer the random displacement removed.
12050 let displaced = (1..=total)
12051 .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12052 .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12053 .expect("exactly one admitted peer was displaced");
12054
12055 scheduler.enqueue(live_nomination(displaced), &obs);
12056
12057 assert!(
12058 scheduler.pending.peek(&test_peer(displaced)).is_some(),
12059 "the displaced peer re-enters the sample"
12060 );
12061 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12062 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12063 assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12064 assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12065 }
12066
12067 /// The periodic sweep collects expired pending entries even when the token
12068 /// bucket is empty — the reserve path returns at the budget gate and never
12069 /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12070 /// honest under fleet-wide starvation.
12071 #[test]
12072 fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12073 let obs = Arc::new(FirstAuditObservability::default());
12074 let mono = Instant::now();
12075 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12076
12077 let dead_quote = SystemTime::now()
12078 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12079 .and_then(|t| t.checked_sub(Duration::from_secs(60)))
12080 .expect("past wall time");
12081 scheduler.enqueue(
12082 MonetizedPinEvent {
12083 peer: test_peer(1),
12084 pin: [1; 32],
12085 key_count: 100,
12086 quote_ts: dead_quote,
12087 },
12088 &obs,
12089 );
12090 scheduler.enqueue(
12091 MonetizedPinEvent {
12092 peer: test_peer(2),
12093 pin: [2; 32],
12094 key_count: 100,
12095 quote_ts: SystemTime::now(),
12096 },
12097 &obs,
12098 );
12099 assert_eq!(scheduler.pending_len(), 2);
12100
12101 // Empty the bucket so the reserve path is budget-gated (fleet-wide
12102 // starvation) and cannot collect the dead entry itself.
12103 scheduler.limiter.tokens = 0;
12104 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12105 assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12106 assert_eq!(
12107 scheduler.pending_len(),
12108 2,
12109 "budget-gated reserve scans nothing"
12110 );
12111
12112 let wall_now = SystemTime::now();
12113 assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12114 assert_eq!(scheduler.pending_len(), 1);
12115 assert!(
12116 scheduler.pending.peek(&test_peer(2)).is_some(),
12117 "the live entry survives the sweep"
12118 );
12119 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12120 let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12121 assert!(
12122 Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12123 "the age gauge reflects only live work after the sweep"
12124 );
12125 }
12126
12127 #[test]
12128 #[allow(clippy::too_many_lines)]
12129 fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12130 let obs = Arc::new(FirstAuditObservability::default());
12131 let mono = Instant::now();
12132 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12133
12134 // A pre-existing window sentinel for an UNRELATED peer must survive the
12135 // cancel byte-for-byte (cancel never touches `recent`).
12136 let sentinel_peer = test_peer(0xAA);
12137 scheduler.limiter.promote(sentinel_peer, 500, mono);
12138 let sentinel_before = scheduler
12139 .limiter
12140 .recent
12141 .peek(&sentinel_peer)
12142 .copied()
12143 .expect("sentinel present");
12144
12145 let peer = test_peer(1);
12146 let a = MonetizedPinEvent {
12147 peer,
12148 pin: [1; 32],
12149 key_count: 100,
12150 quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12151 };
12152 scheduler.enqueue(a, &obs);
12153
12154 let tokens_before = scheduler.tokens();
12155 let lane_before = scheduler.oldest_first_lane;
12156 let launched_before = obs.launched.load(Ordering::Relaxed);
12157 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12158
12159 // Reserve A (jitter 0 so it is immediately due).
12160 let inflight0 = obs.inflight.load(Ordering::Relaxed);
12161 assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12162 assert_eq!(scheduler.reserved_peer(), Some(peer));
12163 assert_eq!(
12164 scheduler.tokens(),
12165 tokens_before - 1,
12166 "reserve consumes a token"
12167 );
12168 assert_eq!(
12169 obs.inflight.load(Ordering::Relaxed),
12170 1,
12171 "reserve holds a slot"
12172 );
12173
12174 // A same-peer, same-count successor arrives DURING the reservation. It
12175 // must be retained (bypasses the window for the reserved peer) and must
12176 // NOT create a second reservation.
12177 let b = MonetizedPinEvent {
12178 peer,
12179 pin: [2; 32],
12180 key_count: 100,
12181 quote_ts: SystemTime::now(),
12182 };
12183 scheduler.enqueue(b, &obs);
12184 assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12185 assert!(
12186 !scheduler.try_reserve(
12187 mono,
12188 obs.inflight.load(Ordering::Relaxed),
12189 Duration::ZERO,
12190 &cooldown,
12191 &obs
12192 ),
12193 "no second reservation while one is outstanding"
12194 );
12195
12196 // Resolve A with an injected wall time PAST A's answerability cutoff.
12197 let reservation = scheduler
12198 .take_due_reservation(mono)
12199 .expect("A is due at jitter 0");
12200 let wall_fail = a
12201 .quote_ts
12202 .checked_add(GOSSIP_ANSWERABILITY_TTL)
12203 .and_then(|t| t.checked_add(Duration::from_secs(1)))
12204 .expect("past-cutoff wall time");
12205 let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12206 assert!(
12207 promoted.is_none(),
12208 "answerability lapsed -> cancelled, not promoted"
12209 );
12210
12211 // State-neutral cancel.
12212 assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12213 assert!(
12214 scheduler.limiter.recent.peek(&peer).is_none(),
12215 "cancel stamps no per-peer window"
12216 );
12217 assert_eq!(
12218 scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12219 Some(sentinel_before),
12220 "unrelated window sentinel untouched"
12221 );
12222 assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12223 assert_eq!(
12224 scheduler.tokens(),
12225 tokens_before,
12226 "token refunded on cancel"
12227 );
12228 assert_eq!(
12229 obs.inflight.load(Ordering::Relaxed),
12230 0,
12231 "in-flight slot released"
12232 );
12233 assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12234 assert_eq!(
12235 obs.launched.load(Ordering::Relaxed),
12236 launched_before,
12237 "no launch counted"
12238 );
12239 assert_eq!(
12240 obs.outside_answerability_window.load(Ordering::Relaxed),
12241 1,
12242 "the cancel reason is recorded"
12243 );
12244
12245 // The successor is still pending and is now fully schedulable: a fresh
12246 // reserve makes B the next reservation (proving eligibility, not merely
12247 // that the limiter would admit it).
12248 assert_eq!(
12249 scheduler.pending_len(),
12250 1,
12251 "successor still pending after cancel"
12252 );
12253 assert!(scheduler.reserved.is_none());
12254 assert!(scheduler.try_reserve(
12255 mono,
12256 obs.inflight.load(Ordering::Relaxed),
12257 Duration::ZERO,
12258 &cooldown,
12259 &obs
12260 ));
12261 assert_eq!(
12262 scheduler.reserved_peer(),
12263 Some(peer),
12264 "the retained successor becomes the next reservation"
12265 );
12266 }
12267
12268 /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12269 /// race, the reserved event is requeued ONLY if no same-peer successor is
12270 /// already pending. A successor arrived after the reservation, so it is the
12271 /// newer nomination (e.g. a count jump) and must not be overwritten by the
12272 /// older reserved event.
12273 #[test]
12274 fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
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 // Reserve A.
12281 let a = MonetizedPinEvent {
12282 peer,
12283 pin: [1; 32],
12284 key_count: 100,
12285 quote_ts: SystemTime::now(),
12286 };
12287 scheduler.enqueue(a, &obs);
12288 let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12289 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12290
12291 // A newer same-peer successor B (a count jump) arrives during the
12292 // reservation and is retained.
12293 let b = MonetizedPinEvent {
12294 peer,
12295 pin: [2; 32],
12296 key_count: 400,
12297 quote_ts: SystemTime::now(),
12298 };
12299 scheduler.enqueue(b, &obs);
12300 assert_eq!(scheduler.pending_len(), 1);
12301
12302 // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12303 // is already stamped for the peer, so promotion loses the race.
12304 let reservation = scheduler.take_due_reservation(mono).expect("due");
12305 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12306 cooldown.insert(peer, mono); // freshly on cooldown
12307 let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12308 assert!(promoted.is_none(), "cooldown race -> not promoted");
12309
12310 // B (newer) is preserved; A did NOT overwrite it.
12311 assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12312 assert_eq!(
12313 scheduler.pending.peek(&peer).map(|e| e.pin),
12314 Some([2; 32]),
12315 "the newer successor B is retained, not the older reserved A"
12316 );
12317 assert!(scheduler.first_audited.is_empty());
12318 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12319 }
12320
12321 /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12322 /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12323 /// and saturates to `0` for a future-dated quote (clock skew) without
12324 /// panicking. A climbing value is the pending-work-aging-out signal.
12325 #[test]
12326 fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12327 let now = SystemTime::now();
12328 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12329 assert_eq!(
12330 scheduler.oldest_pending_quote_age_ms(now),
12331 0,
12332 "empty pending -> zero"
12333 );
12334
12335 // Two peers: quotes 10s and 2s old. The gauge must track the older.
12336 for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12337 let _ = coalesce_first_audit_event(
12338 &mut scheduler.pending,
12339 MonetizedPinEvent {
12340 peer: test_peer(peer_id),
12341 pin,
12342 key_count: 100,
12343 quote_ts: now - Duration::from_secs(secs),
12344 },
12345 true,
12346 &mut scheduler.rng,
12347 );
12348 }
12349 assert_eq!(
12350 scheduler.oldest_pending_quote_age_ms(now),
12351 10_000,
12352 "tracks the oldest (10s), not the newest (2s)"
12353 );
12354
12355 // A future-dated quote (clock skew) saturates to zero, never panics.
12356 let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12357 let _ = coalesce_first_audit_event(
12358 &mut skewed.pending,
12359 MonetizedPinEvent {
12360 peer: test_peer(3),
12361 pin: [3; 32],
12362 key_count: 100,
12363 quote_ts: now + Duration::from_secs(5),
12364 },
12365 true,
12366 &mut skewed.rng,
12367 );
12368 assert_eq!(
12369 skewed.oldest_pending_quote_age_ms(now),
12370 0,
12371 "future quote_ts saturates to zero"
12372 );
12373 }
12374
12375 /// A flood of strictly-lower-count same-peer nominations must neither
12376 /// displace the retained higher pin NOR disturb its recency position (each
12377 /// is suppressed via `peek`, no `push`), and each must be counted as
12378 /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12379 /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12380 /// (the documented `lru` contract that also drives the reserve scan's lane
12381 /// ordering), deliberately independent of the overflow policy: eviction is
12382 /// random-victim, so no assertion may require a particular peer to be
12383 /// displaced.
12384 #[test]
12385 fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12386 let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12387 LruCache::new(NonZeroUsize::new(2).unwrap());
12388 let mut rng = StdRng::seed_from_u64(11);
12389 let victim = test_peer(1);
12390 let other = test_peer(2);
12391 // Victim (high count) inserted first (older), then `other` (newer/MRU).
12392 let _ = coalesce_first_audit_event(
12393 &mut pending,
12394 MonetizedPinEvent {
12395 peer: victim,
12396 pin: [1; 32],
12397 key_count: 400,
12398 quote_ts: SystemTime::now(),
12399 },
12400 true,
12401 &mut rng,
12402 );
12403 let _ = coalesce_first_audit_event(
12404 &mut pending,
12405 MonetizedPinEvent {
12406 peer: other,
12407 pin: [9; 32],
12408 key_count: 100,
12409 quote_ts: SystemTime::now(),
12410 },
12411 true,
12412 &mut rng,
12413 );
12414 let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12415 assert_eq!(
12416 order_before,
12417 vec![other, victim],
12418 "sanity: `other` is MRU, the victim is LRU"
12419 );
12420
12421 // Flood the victim with cheaper nominations.
12422 let mut suppressed = 0u64;
12423 for i in 0..8u8 {
12424 let out = coalesce_first_audit_event(
12425 &mut pending,
12426 MonetizedPinEvent {
12427 peer: victim,
12428 pin: [i; 32],
12429 key_count: 50,
12430 quote_ts: SystemTime::now(),
12431 },
12432 true,
12433 &mut rng,
12434 );
12435 assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12436 suppressed += 1;
12437 }
12438 assert_eq!(suppressed, 8);
12439 // Victim pin/count unchanged.
12440 assert_eq!(
12441 pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12442 Some(([1; 32], 400))
12443 );
12444 // Recency untouched: the iteration order (which the reserve lanes
12445 // consume) is byte-for-byte what it was before the flood.
12446 let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12447 assert_eq!(
12448 order_after, order_before,
12449 "the suppressed-lower flood must not have changed any recency position"
12450 );
12451 }
12452
12453 /// The cooldown-race requeue counts a genuine different-peer capacity
12454 /// eviction (the ADR promises capacity loss is observable).
12455 #[test]
12456 fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12457 let obs = Arc::new(FirstAuditObservability::default());
12458 let mono = Instant::now();
12459 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12460 // Pending capacity 1 so a requeue of a different peer must evict.
12461 scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12462 let reserved_peer = test_peer(1);
12463 let other_peer = test_peer(2);
12464
12465 // Reserve peer 1.
12466 scheduler.enqueue(
12467 MonetizedPinEvent {
12468 peer: reserved_peer,
12469 pin: [1; 32],
12470 key_count: 100,
12471 quote_ts: SystemTime::now(),
12472 },
12473 &obs,
12474 );
12475 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12476 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12477
12478 // A DIFFERENT peer fills the single pending slot during the reservation.
12479 scheduler.enqueue(
12480 MonetizedPinEvent {
12481 peer: other_peer,
12482 pin: [2; 32],
12483 key_count: 100,
12484 quote_ts: SystemTime::now(),
12485 },
12486 &obs,
12487 );
12488 assert_eq!(scheduler.pending_len(), 1);
12489
12490 // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12491 let reservation = scheduler.take_due_reservation(mono).expect("due");
12492 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12493 cooldown.insert(reserved_peer, mono);
12494 let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12495 assert!(scheduler
12496 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12497 .is_none());
12498 assert_eq!(
12499 obs.capacity_evicted.load(Ordering::Relaxed),
12500 cap_before + 1,
12501 "the requeue eviction of a different peer is counted"
12502 );
12503 assert_eq!(
12504 scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12505 Some([1; 32])
12506 );
12507 }
12508
12509 /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12510 /// nomination arriving while an inflated pin is PENDING must not displace it.
12511 /// The inflated pin stays and is the one launched.
12512 #[test]
12513 fn first_audit_pending_lower_count_does_not_replace_higher() {
12514 let obs = Arc::new(FirstAuditObservability::default());
12515 let mono = Instant::now();
12516 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12517 let peer = test_peer(1);
12518
12519 // Inflated (high-count) sidecar pin lands in pending.
12520 scheduler.enqueue(
12521 MonetizedPinEvent {
12522 peer,
12523 pin: [1; 32],
12524 key_count: 400,
12525 quote_ts: SystemTime::now(),
12526 },
12527 &obs,
12528 );
12529 // A cheaper same-peer settlement arrives right after.
12530 scheduler.enqueue(
12531 MonetizedPinEvent {
12532 peer,
12533 pin: [2; 32],
12534 key_count: 100,
12535 quote_ts: SystemTime::now(),
12536 },
12537 &obs,
12538 );
12539
12540 assert_eq!(scheduler.pending_len(), 1);
12541 assert_eq!(
12542 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12543 Some(([1; 32], 400)),
12544 "the inflated pin must not be erased by the cheaper successor"
12545 );
12546 // The dropped cheaper nomination is counted through the enqueue path.
12547 assert_eq!(
12548 obs.suppressed_lower.load(Ordering::Relaxed),
12549 1,
12550 "the attempted cheaper-pin self-erasure is observable"
12551 );
12552
12553 // It reserves and promotes as the inflated pin/count.
12554 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12555 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12556 let reservation = scheduler.take_due_reservation(mono).expect("due");
12557 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12558 let (event, _slot) = scheduler
12559 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12560 .expect("promotes");
12561 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12562 }
12563
12564 /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12565 /// loses the cooldown race must be requeued OVER a lower-count same-peer
12566 /// successor that arrived during its jitter, and must remain launchable once
12567 /// the shared cooldown expires — the cheaper successor cannot suppress it.
12568 #[test]
12569 fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12570 let obs = Arc::new(FirstAuditObservability::default());
12571 let mono = Instant::now();
12572 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12573 let peer = test_peer(1);
12574
12575 // Reserve the inflated pin.
12576 scheduler.enqueue(
12577 MonetizedPinEvent {
12578 peer,
12579 pin: [1; 32],
12580 key_count: 400,
12581 quote_ts: SystemTime::now(),
12582 },
12583 &obs,
12584 );
12585 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12586 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12587
12588 // A cheaper successor arrives during the reservation (bypasses the
12589 // window as the reserved peer) and sits in pending.
12590 scheduler.enqueue(
12591 MonetizedPinEvent {
12592 peer,
12593 pin: [2; 32],
12594 key_count: 100,
12595 quote_ts: SystemTime::now(),
12596 },
12597 &obs,
12598 );
12599 assert_eq!(scheduler.pending_len(), 1);
12600
12601 // Resolve: answerability passes but the shared cooldown is already
12602 // stamped, so the reservation loses the race and requeues.
12603 let reservation = scheduler.take_due_reservation(mono).expect("due");
12604 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12605 cooldown.insert(peer, mono);
12606 assert!(scheduler
12607 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12608 .is_none());
12609
12610 // The inflated pin (400) replaced the cheaper successor (100).
12611 assert_eq!(scheduler.pending_len(), 1);
12612 assert_eq!(
12613 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12614 Some(([1; 32], 400)),
12615 "the inflated reserved pin must survive the requeue over the cheaper successor"
12616 );
12617 assert!(scheduler.first_audited.is_empty());
12618 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12619
12620 // Once the shared cooldown expires, the inflated pin reserves and
12621 // promotes with its intended pin/count.
12622 let later = mono
12623 .checked_add(Duration::from_secs(
12624 config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12625 ))
12626 .expect("later");
12627 let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12628 assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12629 let reservation = scheduler.take_due_reservation(later).expect("due");
12630 let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12631 let (event, _slot) = scheduler
12632 .resolve(
12633 reservation,
12634 SystemTime::now(),
12635 later,
12636 &mut cooldown_later,
12637 &obs,
12638 )
12639 .expect("promotes after cooldown");
12640 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12641 }
12642
12643 /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12644 /// launch lane, driven through the real scheduler (reserve -> resolve ->
12645 /// promote), so a stream of fresh nominations cannot keep every launch on
12646 /// the newest lane and starve the oldest.
12647 #[test]
12648 fn first_audit_lane_alternates_across_promotions() {
12649 let obs = Arc::new(FirstAuditObservability::default());
12650 let mono = Instant::now();
12651 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12652 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12653
12654 // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12655 let oldest_peer = test_peer(1);
12656 let newest_peer = test_peer(2);
12657 scheduler.enqueue(
12658 MonetizedPinEvent {
12659 peer: oldest_peer,
12660 pin: [1; 32],
12661 key_count: 100,
12662 quote_ts: SystemTime::now(),
12663 },
12664 &obs,
12665 );
12666 scheduler.enqueue(
12667 MonetizedPinEvent {
12668 peer: newest_peer,
12669 pin: [2; 32],
12670 key_count: 100,
12671 quote_ts: SystemTime::now(),
12672 },
12673 &obs,
12674 );
12675
12676 let mut launched_peers = Vec::new();
12677 for _ in 0..2 {
12678 assert!(scheduler.try_reserve(
12679 mono,
12680 obs.inflight.load(Ordering::Relaxed),
12681 Duration::ZERO,
12682 &cooldown,
12683 &obs
12684 ));
12685 let reservation = scheduler.take_due_reservation(mono).expect("due");
12686 // Answerable wall time == the quote's own time (age 0).
12687 let (event, _slot) = scheduler
12688 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12689 .expect("fresh in-window quote promotes");
12690 launched_peers.push(event.peer);
12691 }
12692
12693 // First launch takes the newest lane (lane starts false = newest), the
12694 // second takes the oldest lane: strict alternation.
12695 assert_eq!(
12696 launched_peers,
12697 vec![newest_peer, oldest_peer],
12698 "consecutive promotions alternate newest-then-oldest lane"
12699 );
12700 }
12701
12702 #[test]
12703 fn first_audit_count_jump_boundaries() {
12704 // Exactly 1.5x is NOT a jump; strictly above is.
12705 assert!(!first_audit_count_jump(100, 150));
12706 assert!(first_audit_count_jump(100, 151));
12707 // Anything beats an audited zero; zero never jumps.
12708 assert!(first_audit_count_jump(0, 1));
12709 assert!(!first_audit_count_jump(0, 0));
12710 // Equal max counts must not jump (and must not overflow).
12711 assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12712 }
12713
12714 /// A verified payment's quote list includes the local node's own quote, so
12715 /// the verifier emits a monetized-pin event for the local peer on every
12716 /// payment it verifies. The node cannot network-audit itself, so the
12717 /// scheduler must drop such an event at ingress: never queued, and hence
12718 /// never launched nor marked first-audited.
12719 #[test]
12720 fn first_audit_queue_drops_self_targeting_events() {
12721 let obs = Arc::new(FirstAuditObservability::default());
12722 let self_peer = test_peer(1);
12723 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12724 let self_event = MonetizedPinEvent {
12725 peer: self_peer,
12726 pin: [7; 32],
12727 key_count: 1,
12728 quote_ts: SystemTime::now(),
12729 };
12730
12731 scheduler.enqueue(self_event, &obs);
12732 assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12733 assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12734 assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12735
12736 // A remote peer's event still queues normally under the same filter.
12737 let remote_event = MonetizedPinEvent {
12738 peer: test_peer(2),
12739 pin: [8; 32],
12740 ..self_event
12741 };
12742 scheduler.enqueue(remote_event, &obs);
12743 assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12744 assert_eq!(scheduler.pending_len(), 1);
12745 assert_eq!(
12746 obs.self_target_skipped.load(Ordering::Relaxed),
12747 1,
12748 "remote event must not count as a self-target skip"
12749 );
12750 }
12751
12752 #[test]
12753 fn fresh_offer_runs_store_admission_payment_checks() {
12754 let context = fresh_offer_payment_context();
12755 assert_eq!(context, VerificationContext::FreshReplication);
12756 // Fresh replication must keep verifying exactly like a direct client
12757 // PUT (store-strength cache, same live checks); the variant only
12758 // exists so price-floor telemetry can tell the two paths apart.
12759 assert!(context.is_store_admission());
12760 }
12761
12762 #[test]
12763 fn paid_notify_uses_paid_list_admission_payment_checks() {
12764 assert_eq!(
12765 paid_notify_payment_context(),
12766 VerificationContext::PaidListAdmission
12767 );
12768 }
12769
12770 /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12771 /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12772 /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12773 #[test]
12774 fn monetized_quote_audit_window_fails_closed_both_ends() {
12775 let now = SystemTime::now();
12776 // Fresh (just quoted) and small future/past skew -> audited.
12777 assert!(quote_within_audit_window(now, now));
12778 assert!(quote_within_audit_window(
12779 now + Duration::from_secs(60),
12780 now
12781 ));
12782 assert!(quote_within_audit_window(
12783 now - Duration::from_secs(3600),
12784 now
12785 ));
12786 // Far future (badly-skewed / replayed) -> skipped.
12787 assert!(!quote_within_audit_window(
12788 now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_secs(60),
12789 now
12790 ));
12791 // Older than the window -> skipped (pin may have aged out).
12792 assert!(!quote_within_audit_window(
12793 now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12794 now
12795 ));
12796 }
12797
12798 #[tokio::test]
12799 async fn replication_branch_lagged_events_are_counted() {
12800 let before = audit_metrics::replication_event_lagged_total();
12801 let flow = handle_replication_event_recv_error(
12802 &tokio::sync::broadcast::error::RecvError::Lagged(3),
12803 );
12804 assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12805 let after = audit_metrics::replication_event_lagged_total();
12806 assert_eq!(after.saturating_sub(before), 3);
12807 }
12808
12809 #[tokio::test]
12810 async fn replication_branch_closed_events_stop_the_loop() {
12811 let flow =
12812 handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
12813 assert_eq!(flow, std::ops::ControlFlow::Break(()));
12814 }
12815
12816 #[tokio::test]
12817 async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
12818 let (sender, mut receiver) = mpsc::channel(1);
12819 let dropped_body =
12820 ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
12821 keys: Vec::new(),
12822 paid_list_check_indices: Vec::new(),
12823 });
12824 let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12825 let first = InboundReplicationMessage {
12826 source: test_peer(0xC1),
12827 msg: ReplicationMessage {
12828 request_id: 1,
12829 body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
12830 key: test_key(1),
12831 }),
12832 },
12833 rr_message_id: None,
12834 received_at: Instant::now(),
12835 };
12836 let second = InboundReplicationMessage {
12837 source: test_peer(0xC2),
12838 msg: ReplicationMessage {
12839 request_id: 2,
12840 body: dropped_body.clone(),
12841 },
12842 rr_message_id: None,
12843 received_at: Instant::now(),
12844 };
12845
12846 assert!(try_enqueue_serial_message(&sender, first).is_ok());
12847 let dropped = try_enqueue_serial_message(&sender, second)
12848 .expect_err("a full serial queue must refuse the second message");
12849 assert_eq!(dropped.reason, SerialQueueDropReason::Full);
12850 assert_eq!(dropped.message_class, "verification_request");
12851 assert_eq!(dropped.queue_depth, 1);
12852 let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
12853 assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
12854
12855 let queued = receiver
12856 .recv()
12857 .await
12858 .expect("first message should remain queued");
12859 assert_eq!(queued.msg.request_id, 1);
12860 assert!(receiver.try_recv().is_err());
12861 }
12862
12863 #[tokio::test]
12864 async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
12865 let peer = test_peer(0x44);
12866 let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
12867
12868 let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
12869 let mut digest_guards = Vec::new();
12870 for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
12871 let guard = admit_audit_responder(
12872 &semaphore,
12873 &digest_inflight,
12874 &peer,
12875 AuditResponderClass::Digest,
12876 )
12877 .await;
12878 assert!(guard.is_ok());
12879 digest_guards.push(guard);
12880 }
12881 assert!(
12882 admit_audit_responder(
12883 &semaphore,
12884 &digest_inflight,
12885 &peer,
12886 AuditResponderClass::Digest,
12887 )
12888 .await
12889 .is_err(),
12890 "digest class must stop at its documented per-source cap"
12891 );
12892 drop(digest_guards);
12893
12894 let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
12895 let mut subtree_guards = Vec::new();
12896 for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
12897 let guard = admit_audit_responder(
12898 &semaphore,
12899 &subtree_inflight,
12900 &peer,
12901 AuditResponderClass::Subtree,
12902 )
12903 .await;
12904 assert!(guard.is_ok());
12905 subtree_guards.push(guard);
12906 }
12907 assert!(
12908 admit_audit_responder(
12909 &semaphore,
12910 &subtree_inflight,
12911 &peer,
12912 AuditResponderClass::Subtree,
12913 )
12914 .await
12915 .is_err(),
12916 "subtree class must retain the deployed cap of two"
12917 );
12918 drop(subtree_guards);
12919 }
12920
12921 #[test]
12922 fn in_scope_audit_deadlines_share_one_formula() {
12923 let config = config::ReplicationConfig::default();
12924 for key_count in [1, 4, 16] {
12925 assert_eq!(
12926 audit::responsible_audit_response_timeout(&config, key_count),
12927 config.audit_response_timeout(key_count)
12928 );
12929 assert_eq!(
12930 pruning::prune_audit_response_timeout(&config, key_count),
12931 config.audit_response_timeout(key_count)
12932 );
12933 }
12934 assert_eq!(
12935 possession::possession_probe_response_timeout(&config),
12936 config.audit_response_timeout(1)
12937 );
12938 }
12939
12940 #[test]
12941 fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
12942 const EXISTING_SOURCE_ID: u8 = 1;
12943 const HINT_SENDER_ID: u8 = 2;
12944
12945 let existing_source = test_peer(EXISTING_SOURCE_ID);
12946 let hint_sender = test_peer(HINT_SENDER_ID);
12947 let mut sources = vec![existing_source];
12948
12949 let hint_sources = HashSet::from([hint_sender]);
12950 add_replica_hint_sources(&mut sources, &hint_sources);
12951 add_replica_hint_sources(&mut sources, &hint_sources);
12952
12953 // A paid-only advertiser leaves the claim set empty (see
12954 // `queue_admitted_hints`), so it contributes no fetch source.
12955 add_replica_hint_sources(&mut sources, &HashSet::new());
12956
12957 assert_eq!(sources, vec![existing_source, hint_sender]);
12958 }
12959
12960 #[test]
12961 fn audit_timeout_preserves_active_bootstrap_claim() {
12962 assert!(!audit_failure_clears_bootstrap_claim(
12963 &AuditFailureReason::Timeout
12964 ));
12965 }
12966
12967 fn strike_peer(b: u8) -> PeerId {
12968 let mut bytes = [0u8; 32];
12969 bytes[0] = b;
12970 PeerId::from_bytes(bytes)
12971 }
12972
12973 // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
12974 // cooldown must collapse a gossip flood into at most one audit per window.
12975
12976 #[test]
12977 fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
12978 let peer = strike_peer(1);
12979 let mut map: HashMap<PeerId, Instant> = HashMap::new();
12980 let t0 = Instant::now();
12981 // First gossip in the window passes; a burst of further gossips at the
12982 // same instant are all suppressed.
12983 assert!(cooldown_allows_audit(&mut map, &peer, t0));
12984 let mut passed = 1;
12985 for _ in 0..100 {
12986 if cooldown_allows_audit(&mut map, &peer, t0) {
12987 passed += 1;
12988 }
12989 }
12990 assert_eq!(
12991 passed, 1,
12992 "a flood at one instant must trigger exactly one audit"
12993 );
12994 }
12995
12996 // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
12997 // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
12998 // consumes the window. This is the property the isolated cooldown tests above
12999 // cannot see: they never sample the lottery, so a regression that reordered
13000 // the gates (sample probability first, only stamp the cooldown on a win)
13001 // would still pass them while breaking flood-resistance: a flood would then
13002 // re-roll the lottery on EVERY message until one won, multiplying audits.
13003 //
13004 // We model the exact production gate order (attempt-window, lottery,
13005 // shared cooldown) with a lottery driven by a fixed outcome instead of
13006 // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13007 // messages all WIN. With the production order, the losing first ticket
13008 // burns the ATTEMPT window and every later winner in the same window is
13009 // blocked, so there are 0 audits this window. If the gates were flipped,
13010 // the second message's winning ticket would slip through. The window only
13011 // reopens after it elapses.
13012 //
13013 // FLIPS IF: the lottery is sampled before the attempt-window
13014 // check-and-stamp (a losing ticket no longer consumes the window),
13015 // re-enabling a flood-amplified audit storm.
13016 #[test]
13017 fn losing_lottery_still_consumes_attempt_window() {
13018 // Calls the SHIPPED `audit_launch_decision` (the same function
13019 // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13020 // production fails this test — not a local reimplementation.
13021 let peer = strike_peer(3);
13022 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13023 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13024 let t0 = Instant::now();
13025
13026 // First flooded message at t0 LOSES the lottery, but the attempt window
13027 // is stamped BEFORE the lottery is consulted, so the window is consumed.
13028 assert!(
13029 !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13030 "a losing ticket launches no audit"
13031 );
13032
13033 // 99 more flooded messages at the same instant would all WIN the lottery,
13034 // yet every one must be blocked by the attempt window the loser stamped.
13035 // (If production sampled the lottery FIRST, these would each get a fresh
13036 // roll and audits would multiply — this assertion catches that reorder.)
13037 let mut audits = 0;
13038 for _ in 0..99 {
13039 if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13040 audits += 1;
13041 }
13042 }
13043 assert_eq!(
13044 audits, 0,
13045 "a losing first ticket must consume the attempt window so no later \
13046 flooded message in the same window can audit"
13047 );
13048
13049 // The window only reopens after it elapses; the next winning ticket
13050 // then launches exactly one audit and stamps the SHARED cooldown.
13051 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13052 assert!(
13053 audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13054 "after the window a winning ticket audits again"
13055 );
13056 assert!(
13057 launched.contains_key(&peer),
13058 "a real launch stamps the shared cooldown"
13059 );
13060 }
13061
13062 /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13063 /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13064 /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13065 /// first audit deferred until its answerability window expires.
13066 ///
13067 /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13068 /// loss (the pre-split behavior, where both paths shared one map).
13069 #[test]
13070 fn losing_lottery_does_not_suppress_monetized_first_audit() {
13071 let peer = strike_peer(4);
13072 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13073 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13074 let t0 = Instant::now();
13075
13076 // A losing ticket consumes the gossip attempt window...
13077 assert!(!audit_launch_decision(
13078 &mut attempts,
13079 &mut launched,
13080 &peer,
13081 t0,
13082 false
13083 ));
13084 // ...but leaves the shared map untouched, so the first-audit reserve
13085 // gate (read-only) and the authoritative promotion check-and-stamp both
13086 // still allow the paid audit to launch immediately.
13087 assert!(
13088 cooldown_would_allow(&launched, &peer, t0),
13089 "reserve gate must not see a losing ticket as audit coverage"
13090 );
13091 assert!(
13092 cooldown_allows_audit(&mut launched, &peer, t0),
13093 "promotion must not be deferred by a losing ticket"
13094 );
13095
13096 // Conversely a WINNING ticket (real audit sent) does suppress the
13097 // first audit for the window, which is the intended shared semantics.
13098 let peer_won = strike_peer(5);
13099 assert!(audit_launch_decision(
13100 &mut attempts,
13101 &mut launched,
13102 &peer_won,
13103 t0,
13104 true
13105 ));
13106 assert!(
13107 !cooldown_would_allow(&launched, &peer_won, t0),
13108 "a real gossip audit still covers the peer for the window"
13109 );
13110 }
13111
13112 #[test]
13113 fn cooldown_lets_audit_through_after_the_window() {
13114 let peer = strike_peer(2);
13115 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13116 let t0 = Instant::now();
13117 assert!(cooldown_allows_audit(&mut map, &peer, t0));
13118 // Within the window: suppressed.
13119 let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13120 assert!(!cooldown_allows_audit(&mut map, &peer, within));
13121 // Past the window: allowed again.
13122 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13123 assert!(cooldown_allows_audit(&mut map, &peer, after));
13124 }
13125
13126 #[test]
13127 fn cooldown_is_per_peer_independent() {
13128 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13129 let t0 = Instant::now();
13130 // Different peers each get their own first-audit pass at the same instant.
13131 for i in 0..20u8 {
13132 assert!(
13133 cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13134 "peer {i} should be auditable independently"
13135 );
13136 }
13137 }
13138
13139 #[test]
13140 fn audit_on_gossip_constants_match_adr() {
13141 // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13142 // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13143 // values above 5 would silently never be requested).
13144 assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13145 assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13146 assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13147 }
13148
13149 // (d) A confirmed storage-integrity failure penalizes immediately and
13150 // revokes credit; it is not a timeout.
13151 #[test]
13152 fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13153 assert!(audit_failure_clears_bootstrap_claim(
13154 &AuditFailureReason::DigestMismatch
13155 ));
13156 assert!(audit_failure_revokes_holder_credit(
13157 &AuditFailureReason::DigestMismatch
13158 ));
13159 }
13160
13161 /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13162 /// uses: confirmed failures revoke credit, `Timeout` does not.
13163 #[test]
13164 fn confirmed_failures_revoke_credit_timeout_does_not() {
13165 for reason in [
13166 AuditFailureReason::MalformedResponse,
13167 AuditFailureReason::DigestMismatch,
13168 AuditFailureReason::KeyAbsent,
13169 AuditFailureReason::Rejected,
13170 ] {
13171 assert!(
13172 audit_failure_revokes_holder_credit(&reason),
13173 "confirmed failure {reason:?} must revoke holder credit"
13174 );
13175 }
13176 assert!(
13177 !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13178 "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13179 );
13180 }
13181
13182 /// Wiring test for the security fix: the helper the handler calls
13183 /// actually strips a credited peer on a confirmed failure
13184 /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13185 /// Records genuine credit first so neither assertion is vacuous;
13186 /// this fails if `forget_peer` stops being called, or if the
13187 /// `Timeout` exclusion is dropped (both verified by mutation).
13188 #[test]
13189 fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13190 let peer = test_peer(0xAB);
13191 let key = test_key(1);
13192 let hash = [0xCD; 32];
13193
13194 // Confirmed failure -> credit revoked.
13195 let mut provers = RecentProvers::new();
13196 provers.record_proof(key, peer, hash, Instant::now());
13197 assert!(
13198 provers.is_credited_holder(&key, &peer, &hash),
13199 "precondition: peer credited before failure"
13200 );
13201 apply_audit_failure_credit_revocation(
13202 &mut provers,
13203 &peer,
13204 &AuditFailureReason::DigestMismatch,
13205 );
13206 assert!(
13207 !provers.is_credited_holder(&key, &peer, &hash),
13208 "DigestMismatch must strip the peer's holder credit"
13209 );
13210
13211 // Timeout -> credit retained.
13212 let mut provers_timeout = RecentProvers::new();
13213 provers_timeout.record_proof(key, peer, hash, Instant::now());
13214 apply_audit_failure_credit_revocation(
13215 &mut provers_timeout,
13216 &peer,
13217 &AuditFailureReason::Timeout,
13218 );
13219 assert!(
13220 provers_timeout.is_credited_holder(&key, &peer, &hash),
13221 "Timeout must retain holder credit (deliberate liveness cushion)"
13222 );
13223 }
13224
13225 #[test]
13226 fn decoded_audit_failures_clear_active_bootstrap_claim() {
13227 for reason in [
13228 AuditFailureReason::MalformedResponse,
13229 AuditFailureReason::DigestMismatch,
13230 AuditFailureReason::KeyAbsent,
13231 AuditFailureReason::Rejected,
13232 ] {
13233 assert!(
13234 audit_failure_clears_bootstrap_claim(&reason),
13235 "decoded non-bootstrap failure {reason:?} should clear active claim"
13236 );
13237 }
13238 }
13239
13240 #[test]
13241 fn first_failed_key_label_truncates_to_16_hex_chars() {
13242 // The high-order 8 bytes of the XorName determine the label so an
13243 // operator can group audit-failures on the same chunk prefix.
13244 let mut key = [0u8; 32];
13245 key[0] = 0x18;
13246 key[7] = 0xff;
13247 // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13248 // to verify they are NOT included in the label.
13249 for byte in &mut key[8..] {
13250 *byte = 0xAA;
13251 }
13252 let label = first_failed_key_label(&[key]);
13253 // Only the first 8 bytes are encoded, low-order bytes are dropped.
13254 assert_eq!(label, "0x18000000000000ff");
13255 assert_eq!(label.len(), "0x".len() + 16);
13256 }
13257
13258 #[test]
13259 fn first_failed_key_label_falls_back_when_empty() {
13260 // Should never happen in production (audit failure handling rejects
13261 // empty sets), but the formatter must still produce a valid label
13262 // so the log line doesn't contain a misleading default.
13263 assert_eq!(first_failed_key_label(&[]), "0x");
13264 }
13265
13266 #[test]
13267 fn first_failed_key_label_uses_first_key_only() {
13268 let first = [0x11u8; 32];
13269 let second = [0x22u8; 32];
13270 assert_eq!(
13271 first_failed_key_label(&[first, second]),
13272 format!("0x{}", hex::encode(&first[..8]))
13273 );
13274 }
13275
13276 // -- apply_fetch_result --------------------------------------------------
13277 //
13278 // The worker's disposition of a fetch outcome. Note there is no trust
13279 // handle in `apply_fetch_result`'s signature: the worker cannot report a
13280 // trust event for ANY outcome, and `execute_single_fetch` returns
13281 // `NoLongerResponsible` before its trust-reporting paths — the source did
13282 // nothing wrong when this node's own responsibility lapsed.
13283
13284 /// Route `key` through the real pipeline stages (pending → promoted →
13285 /// dequeued → in-flight) so it carries a verification retry-slot
13286 /// reservation, exactly as a worker-dequeued key does. Returns the
13287 /// in-flight source.
13288 fn drive_key_in_flight(
13289 q: &mut ReplicationQueues,
13290 key: XorName,
13291 sources: Vec<PeerId>,
13292 ) -> PeerId {
13293 let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13294 let now = Instant::now();
13295 let entry = VerificationEntry {
13296 state: VerificationState::PendingVerify,
13297 verified_sources: Vec::new(),
13298 tried_sources: HashSet::new(),
13299 created_at: now,
13300 next_verify_at: now,
13301 hint_sources: HashSet::from([hinter]),
13302 replica_hint_sources: HashSet::from([hinter]),
13303 unresolved_retries: 0,
13304 no_holder_reported: false,
13305 };
13306 assert!(q.add_pending_verify(key, entry).admitted());
13307 assert!(q.promote_pending_to_fetch(key, key, sources));
13308 let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13309 let source = *candidate.sources.first().expect("candidate has a source");
13310 q.start_dequeued_fetch(candidate, source);
13311 source
13312 }
13313
13314 #[test]
13315 fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13316 const RETRY_AFTER: Duration = Duration::from_secs(60);
13317
13318 let mut q = ReplicationQueues::new();
13319 let key = test_key(0xAB);
13320 drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13321 assert_eq!(q.retry_reserved_slot_count(), 1);
13322
13323 let follow_up =
13324 apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13325
13326 assert_eq!(
13327 follow_up,
13328 FetchFollowUp::Terminal,
13329 "lapsed responsibility must run the caller's terminal bootstrap accounting"
13330 );
13331 assert!(
13332 !q.contains_key(&key),
13333 "the key must leave every pipeline stage — alternate sources included"
13334 );
13335 assert_eq!(
13336 q.pending_count(),
13337 0,
13338 "a lapsed-responsibility key must not be requeued for verification"
13339 );
13340 assert_eq!(
13341 q.retry_reserved_slot_count(),
13342 0,
13343 "terminal exit must release the verification retry-slot reservation"
13344 );
13345 }
13346
13347 #[test]
13348 fn no_longer_responsible_shares_the_stored_terminal_path() {
13349 const RETRY_AFTER: Duration = Duration::from_secs(60);
13350
13351 // Both variants must walk the identical terminal gate so the
13352 // battle-tested Stored accounting (retry-slot release + bootstrap
13353 // pending-set shrink in the caller) covers lapsed responsibility too.
13354 for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13355 let mut q = ReplicationQueues::new();
13356 let key = test_key(0xCD);
13357 drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13358
13359 let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13360
13361 assert_eq!(follow_up, FetchFollowUp::Terminal);
13362 assert!(!q.contains_key(&key));
13363 assert_eq!(q.retry_reserved_slot_count(), 0);
13364 }
13365 }
13366
13367 #[test]
13368 fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13369 const RETRY_AFTER: Duration = Duration::from_secs(60);
13370
13371 let mut q = ReplicationQueues::new();
13372 let key = test_key(0xEF);
13373 let first = test_peer(0x04);
13374 let second = test_peer(0x05);
13375 drive_key_in_flight(&mut q, key, vec![first, second]);
13376
13377 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13378 assert_eq!(
13379 follow_up,
13380 FetchFollowUp::RetryFrom(second),
13381 "a failed source must not abandon the remaining verified sources"
13382 );
13383 assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13384
13385 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13386 assert_eq!(
13387 follow_up,
13388 FetchFollowUp::RequeuedForVerification,
13389 "exhausted sources must restore the reserved verification entry"
13390 );
13391 assert_eq!(q.pending_count(), 1);
13392 assert_eq!(
13393 q.retry_reserved_slot_count(),
13394 0,
13395 "the reservation converts back into the pending entry itself"
13396 );
13397 }
13398
13399 #[test]
13400 fn source_failure_without_retry_metadata_is_terminal() {
13401 const RETRY_AFTER: Duration = Duration::from_secs(60);
13402
13403 // Direct enqueue (no pending entry) models a fetch with no
13404 // verification retry reservation to restore.
13405 let mut q = ReplicationQueues::new();
13406 let key = test_key(0x1F);
13407 let source = test_peer(0x06);
13408 assert!(q.enqueue_fetch(key, key, vec![source]));
13409 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13410 q.start_dequeued_fetch(candidate, source);
13411
13412 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13413
13414 assert_eq!(follow_up, FetchFollowUp::Terminal);
13415 assert!(!q.contains_key(&key));
13416 }
13417
13418 #[test]
13419 fn already_held_key_leaves_the_pipeline_terminally() {
13420 const RETRY_AFTER: Duration = Duration::from_secs(60);
13421
13422 let mut q = ReplicationQueues::new();
13423 let key = test_key(0x4C);
13424 let source = test_peer(0x0B);
13425 drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13426
13427 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13428
13429 assert_eq!(
13430 follow_up,
13431 FetchFollowUp::Terminal,
13432 "holding the key already discharges the duty, so the key must leave \
13433 the pipeline exactly as a completed fetch does — requeueing it \
13434 would re-verify a key that needs nothing"
13435 );
13436 assert!(!q.contains_key(&key));
13437 assert_eq!(
13438 q.retry_reserved_slot_count(),
13439 0,
13440 "the terminal path must release the retry-slot reservation, or the \
13441 owner's verification budget leaks"
13442 );
13443 }
13444
13445 #[test]
13446 fn local_write_failure_does_not_conscript_the_remaining_sources() {
13447 const RETRY_AFTER: Duration = Duration::from_secs(60);
13448
13449 let mut q = ReplicationQueues::new();
13450 let key = test_key(0x2A);
13451 let first = test_peer(0x07);
13452 let second = test_peer(0x08);
13453 let third = test_peer(0x09);
13454 drive_key_in_flight(&mut q, key, vec![first, second, third]);
13455
13456 let follow_up =
13457 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13458
13459 assert_eq!(
13460 follow_up,
13461 FetchFollowUp::RequeuedForVerification,
13462 "a local write failure must go straight back to verification: the two \
13463 untried sources would each re-upload the same chunk into the same \
13464 full disk, and neither of them did anything wrong"
13465 );
13466 assert_eq!(q.in_flight_count(), 0);
13467 assert_eq!(
13468 q.pending_count(),
13469 1,
13470 "the key must come back — capacity frees up, and a stranded key is \
13471 a replica this node silently stops owing"
13472 );
13473 assert_eq!(q.retry_reserved_slot_count(), 0);
13474 }
13475
13476 #[test]
13477 fn local_write_failure_without_retry_metadata_is_terminal() {
13478 const RETRY_AFTER: Duration = Duration::from_secs(60);
13479
13480 // No pending entry to restore, so the only way not to strand the key
13481 // in `in_flight_fetch` forever — which would also stall bootstrap
13482 // drain — is the terminal path.
13483 let mut q = ReplicationQueues::new();
13484 let key = test_key(0x3B);
13485 let source = test_peer(0x0A);
13486 assert!(q.enqueue_fetch(key, key, vec![source]));
13487 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13488 q.start_dequeued_fetch(candidate, source);
13489
13490 let follow_up =
13491 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13492
13493 assert_eq!(follow_up, FetchFollowUp::Terminal);
13494 assert!(!q.contains_key(&key));
13495 assert_eq!(q.retry_reserved_slot_count(), 0);
13496 }
13497}