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(crate) mod out_of_range_clocks;
28pub mod paid_list;
29pub mod pointer;
30pub mod possession;
31pub mod protocol;
32pub mod pruning;
33pub mod quorum;
34pub mod recent_provers;
35pub mod retention;
36pub mod scheduling;
37pub mod slice;
38pub mod storage_commitment_audit;
39pub mod subtree;
40pub mod types;
41
42use std::collections::{HashMap, HashSet, VecDeque};
43use std::fmt;
44use std::io::Write as _;
45use std::num::NonZeroUsize;
46use std::ops::ControlFlow;
47use std::path::{Path, PathBuf};
48use std::sync::atomic::{AtomicU64, Ordering};
49use std::sync::Arc;
50use std::time::{Duration, Instant, SystemTime};
51
52use lru::LruCache;
53use std::pin::Pin;
54
55use crate::logging::{debug, error, info, warn};
56use futures::stream::FuturesUnordered;
57use futures::{future::join_all, Future, StreamExt};
58use parking_lot::Mutex;
59use rand::rngs::StdRng;
60use rand::{Rng, SeedableRng};
61use tokio::sync::broadcast::error::RecvError;
62use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
63use tokio::task::JoinHandle;
64use tokio_util::sync::CancellationToken;
65use tokio_util::task::TaskTracker;
66
67use crate::ant_protocol::XorName;
68use crate::error::{Error, Result};
69use crate::payment::{
70 PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
71 MIN_PAYMENT_PROOF_SIZE_BYTES,
72};
73use crate::pointer::store::PointerStore;
74use crate::pointer::{FinalStateWitness, PointerService};
75use crate::replication::audit::AuditTickResult;
76use crate::replication::audit_coordinator::AuditChallengeCoordinator;
77use crate::replication::audit_metrics::{
78 AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
79 ReplicationResponderClass, ResponderAdmissionCeiling,
80};
81use crate::replication::commitment::{commitment_hash, StorageCommitment};
82use crate::replication::commitment_state::{
83 PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
84};
85use crate::replication::config::{
86 fresh_read_retry_delay, max_parallel_fetch, storage_admission_width, ReplicationConfig,
87 MAX_AUDIT_RESPONSES_PER_PEER, MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
88 MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_FRESH_READ_ATTEMPTS, MAX_INCOMING_VERIFICATION_KEYS,
89 MAX_PENDING_FRESH_OFFERS, MAX_SESSION_POINTER_BINDINGS, MAX_SUBTREE_ROUND1_PER_PEER,
90 MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE, REPLICATION_PROTOCOL_ID,
91 SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
92 SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
93};
94use crate::replication::paid_list::PaidList;
95use crate::replication::protocol::{
96 FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
97 VerificationResponse,
98};
99use crate::replication::quorum::KeyVerificationOutcome;
100use crate::replication::recent_provers::RecentProvers;
101use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
102use crate::replication::storage_commitment_audit::PointerBindings;
103use crate::replication::types::{
104 AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
105 NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
106 VerificationState,
107};
108use crate::storage::{CapacityVerdict, ChunkStore};
109use saorsa_core::identity::{NodeIdentity, PeerId};
110use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
111use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
112
113/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
114/// because it was full (Amendment 2). Process-global because the producer is
115/// the payment verifier (a different module) and the drop happens before the
116/// per-drainer `received` counter. A non-zero value is the rollout signal that
117/// nomination ingress is saturating — benign (penalty-free, lottery/next-
118/// payment covered) but worth watching. `Closed` (engine shut down) is not
119/// counted: it is not a saturation signal.
120static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
121
122/// Record one ingress-full drop. Called by the payment verifier's `try_send`
123/// sites; read by the drainer's periodic summary.
124pub(crate) fn note_monetized_ingress_drop() {
125 FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
126}
127
128#[derive(Default)]
129struct FirstAuditObservability {
130 received: AtomicU64,
131 queued: AtomicU64,
132 coalesced: AtomicU64,
133 duplicates: AtomicU64,
134 capacity_evicted: AtomicU64,
135 /// An event targeting the local peer itself, dropped at ingress: the node
136 /// cannot network-audit itself (no dialable address for the local peer).
137 self_target_skipped: AtomicU64,
138 /// A strictly-lower-count same-peer nomination that was dropped so a
139 /// higher-count pending pin survived. A sustained rise is the signal of an
140 /// attempted "erase the inflated pin with a cheaper one" self-suppression.
141 suppressed_lower: AtomicU64,
142 cooldown_deferred_attempts: AtomicU64,
143 rate_deferred_attempts: AtomicU64,
144 window_deduped: AtomicU64,
145 launched: AtomicU64,
146 passed: AtomicU64,
147 timed_out: AtomicU64,
148 failed: AtomicU64,
149 bootstrap_claims: AtomicU64,
150 idle: AtomicU64,
151 insufficient_keys: AtomicU64,
152 outside_answerability_window: AtomicU64,
153 inflight: AtomicU64,
154}
155
156/// Test-only snapshot of the first-audit scheduler counters.
157///
158/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
159/// self-targeting monetized pin was dropped and never launched) instead of
160/// scraping log lines.
161#[cfg(any(test, feature = "test-utils"))]
162#[derive(Debug, Clone, Copy)]
163pub struct FirstAuditStats {
164 /// Events ingested from the monetized-pin channel.
165 pub received: u64,
166 /// Events accepted into the pending first-audit queue.
167 pub queued: u64,
168 /// Events dropped because they targeted the local peer.
169 pub self_target_skipped: u64,
170 /// Audits launched.
171 pub launched: u64,
172 /// Launched audits that passed.
173 pub passed: u64,
174 /// Launched audits that timed out (non-response lane).
175 pub timed_out: u64,
176 /// Launched audits that ended in a confirmed failure.
177 pub failed: u64,
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181enum FirstAuditTerminalOutcome {
182 Passed,
183 Timeout,
184 Failed,
185 BootstrapClaim,
186 Idle,
187 InsufficientKeys,
188}
189
190impl FirstAuditTerminalOutcome {
191 #[cfg(any(feature = "logging", test))]
192 const fn as_str(self) -> &'static str {
193 match self {
194 Self::Passed => "passed",
195 Self::Timeout => "timeout",
196 Self::Failed => "failed",
197 Self::BootstrapClaim => "bootstrap_claim",
198 Self::Idle => "idle",
199 Self::InsufficientKeys => "insufficient_keys",
200 }
201 }
202}
203
204fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
205 match result {
206 AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
207 AuditTickResult::Failed {
208 evidence:
209 FailureEvidence::AuditFailure {
210 reason: AuditFailureReason::Timeout,
211 ..
212 },
213 ..
214 } => FirstAuditTerminalOutcome::Timeout,
215 AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
216 AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
217 AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
218 AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
219 }
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223enum FirstAuditQueueOutcome {
224 /// New peer inserted with free capacity.
225 Queued,
226 /// Collapsed with an existing same-peer entry; the incoming won (higher
227 /// count, or equal count and newer) and replaced it.
228 Coalesced,
229 /// Collapsed with an existing same-peer entry; the incoming LOST because it
230 /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
231 /// in place. This is the attempted cheaper-pin self-erasure signal.
232 SuppressedLower,
233 /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
234 /// lost the freshness tie (it was not the newer of the two) and the
235 /// existing entry was retained. Benign, not an attack signal.
236 RetainedOnTie,
237 /// A DIFFERENT peer's entry was displaced from the capped pending queue
238 /// (random victim) to make room.
239 CapacityEvicted { peer: PeerId, pin: [u8; 32] },
240}
241
242/// Coalesce a monetized nomination into the per-peer pending queue with a
243/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
244/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
245///
246/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
247/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
248/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
249/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
250/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
251/// cannot promote the retained pin's lane position.
252///
253/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
254/// last, so it wins an equal-count tie for freshness) from a cooldown-race
255/// requeue of an older reserved event (the pending successor is newer, so it
256/// wins the tie).
257fn coalesce_first_audit_event(
258 pending: &mut LruCache<PeerId, MonetizedPinEvent>,
259 incoming: MonetizedPinEvent,
260 incoming_is_newer: bool,
261 rng: &mut StdRng,
262) -> FirstAuditQueueOutcome {
263 if let Some(existing) = pending.peek(&incoming.peer) {
264 // Strictly lower -> the incoming loses and is dropped WITHOUT touching
265 // the retained pin's recency (the security-relevant self-erasure case).
266 if incoming.key_count < existing.key_count {
267 return FirstAuditQueueOutcome::SuppressedLower;
268 }
269 // Equal count -> keep the fresher; an older incoming loses a benign tie.
270 if incoming.key_count == existing.key_count && !incoming_is_newer {
271 return FirstAuditQueueOutcome::RetainedOnTie;
272 }
273 // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
274 // the value and bumps MRU; replacing an existing key never evicts a
275 // different peer.
276 let _ = pending.push(incoming.peer, incoming);
277 return FirstAuditQueueOutcome::Coalesced;
278 }
279 // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
280 // never the LRU: deterministic keep-newest would let an ordered batch of
281 // `cap` distinct-peer nominations flush a chosen target before any launch
282 // lane sees it, cutting the eviction cost from probabilistic to exact. A
283 // random victim caps an attacker's per-nomination eviction probability at
284 // `1/cap` regardless of arrival order or timing, so suppressing a specific
285 // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
286 // nominations and is never certain (ADR-0004 Amendment 4).
287 if pending.len() >= pending.cap().get() {
288 let victim = {
289 let idx = rng.gen_range(0..pending.len());
290 pending.iter().nth(idx).map(|(p, _)| *p)
291 };
292 if let Some(victim_peer) = victim {
293 if let Some(evicted) = pending.pop(&victim_peer) {
294 let _ = pending.push(incoming.peer, incoming);
295 return FirstAuditQueueOutcome::CapacityEvicted {
296 peer: victim_peer,
297 pin: evicted.pin,
298 };
299 }
300 }
301 }
302 match pending.push(incoming.peer, incoming) {
303 None => FirstAuditQueueOutcome::Queued,
304 // Unreachable: the random-displacement branch above guarantees
305 // `len < cap` here (the caller holds `&mut`, so no concurrent insert
306 // exists). Kept so any future logic error surfaces as an ACCOUNTED
307 // eviction rather than silent loss — but note this arm would be
308 // LRU-order, not random, so it must stay unreachable.
309 Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
310 peer: evicted_peer,
311 pin: evicted.pin,
312 },
313 }
314}
315
316/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
317/// prefiltering a nomination's answerability at schedule time, covering the
318/// spawn/dispatch latency between the timer firing and the wire challenge so a
319/// jitter==MAX pin is not admitted only to fail the authoritative check by a
320/// few milliseconds. Tiny against the multi-hour answerability window.
321const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
322
323/// A first audit the limiter recently launched at a peer: when, and the
324/// committed key count that was audited (for the count-jump override).
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326struct RecentFirstAudit {
327 launched_at: Instant,
328 key_count: u32,
329}
330
331/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
332/// panicking or cancelled audit task can never leak a slot and wedge the
333/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
334struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
335
336impl FirstAuditInflightSlot {
337 fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
338 observability.inflight.fetch_add(1, Ordering::Relaxed);
339 Self(Arc::clone(observability))
340 }
341}
342
343impl Drop for FirstAuditInflightSlot {
344 fn drop(&mut self) {
345 self.0.inflight.fetch_sub(1, Ordering::Relaxed);
346 }
347}
348
349/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
350/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
351/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
352/// overflow-free integer math). A jump re-nominates a peer despite a recent
353/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
354/// only, so no gossip-lottery audit can ever cover it.
355const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
356 (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
357 > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
358}
359
360/// The launch limiter's verdict for one pending monetized pin.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362enum LimiterVerdict {
363 /// Within budget and window: the caller may reserve a launch (and consumes
364 /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
365 Admit,
366 /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
367 /// pin pending and retry on a later tick.
368 RateDeferred,
369 /// The peer had a first audit within
370 /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
371 /// shows no [`first_audit_count_jump`]. Drop the nomination (the
372 /// gossip-lottery re-audit path is unaffected).
373 WindowDeduped,
374}
375
376/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
377/// (launch rate), an in-flight cap, and a per-peer re-audit window that
378/// survives pin rotation.
379///
380/// This is the load-bearing aggregate bound the original scheduler lacked:
381/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
382/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
383/// `now`/`inflight` values so every decision is unit-testable without a
384/// runtime.
385struct FirstAuditLimiter {
386 /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
387 tokens: u32,
388 /// Refill anchor. While the bucket is full this tracks `now` (a full
389 /// bucket accrues nothing); while below capacity it advances only by
390 /// whole refill intervals so fractional elapsed time is never lost.
391 last_refill: Instant,
392 /// Peers given a first audit recently, with the audited key count.
393 /// Bounded like the drainer's other per-peer maps.
394 recent: LruCache<PeerId, RecentFirstAudit>,
395}
396
397impl FirstAuditLimiter {
398 fn new(now: Instant) -> Self {
399 Self {
400 tokens: config::FIRST_AUDIT_BUDGET_BURST,
401 last_refill: now,
402 recent: LruCache::new(
403 NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
404 ),
405 }
406 }
407
408 /// Whether the per-peer re-audit window admits a nomination for `peer`
409 /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
410 /// call at ENQUEUE time — suppressed nominations never occupy pending
411 /// slots — without disturbing LRU recency.
412 fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
413 self.recent.peek(peer).is_none_or(|prev| {
414 now.saturating_duration_since(prev.launched_at)
415 >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
416 || first_audit_count_jump(prev.key_count, key_count)
417 })
418 }
419
420 /// Refill the token bucket for the time elapsed up to `now`.
421 fn refill(&mut self, now: Instant) {
422 if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
423 // Full bucket accrues nothing; keep the anchor current so the
424 // next consumption starts its interval from here.
425 self.last_refill = now;
426 return;
427 }
428 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
429 let elapsed = now.saturating_duration_since(self.last_refill);
430 let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
431 if earned == 0 {
432 return;
433 }
434 let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
435 if earned >= capacity_gap {
436 self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
437 self.last_refill = now;
438 } else {
439 // earned < capacity_gap <= u32::MAX, so both casts are lossless.
440 self.tokens = self
441 .tokens
442 .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
443 let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
444 self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
445 }
446 }
447
448 /// Decide whether a pending pin may launch now. Consumes NOTHING: the
449 /// caller runs the remaining (per-peer cooldown) gate and calls
450 /// [`Self::commit_launch`] only for a launch that actually happens, so a
451 /// deferral elsewhere never burns budget or stamps the window.
452 fn assess(
453 &mut self,
454 peer: &PeerId,
455 key_count: u32,
456 now: Instant,
457 inflight: u64,
458 ) -> LimiterVerdict {
459 if !self.window_allows(peer, key_count, now) {
460 return LimiterVerdict::WindowDeduped;
461 }
462 self.refill(now);
463 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
464 return LimiterVerdict::RateDeferred;
465 }
466 LimiterVerdict::Admit
467 }
468
469 /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
470 /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
471 /// only at [`Self::promote`], after the authoritative post-jitter
472 /// answerability check, so a reservation that is later cancelled leaves no
473 /// suppression behind.
474 fn reserve_token(&mut self) {
475 self.tokens = self.tokens.saturating_sub(1);
476 }
477
478 /// Return a token consumed by a reservation that was cancelled before it
479 /// launched (answerability lapsed or a concurrent gossip audit won the
480 /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
481 /// the bucket.
482 fn refund_token(&mut self) {
483 self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
484 }
485
486 /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
487 /// (promotion). Separated from token consumption so suppression is only
488 /// ever recorded for a real send.
489 fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
490 self.recent.put(
491 peer,
492 RecentFirstAudit {
493 launched_at: now,
494 key_count,
495 },
496 );
497 }
498
499 /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
500 /// and stamp the window in one call. Production splits these across
501 /// reservation and promotion; the limiter's own budget/window unit tests do
502 /// not model the jitter reservation and use this shorthand.
503 #[cfg(test)]
504 fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
505 self.reserve_token();
506 self.promote(peer, key_count, now);
507 }
508}
509
510/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
511/// across the ENTIRE launch-jitter window ending at
512/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
513/// for it cannot later require aborting an out-of-window challenge. The
514/// too-future bound is enforced at `now` (a jitter delay only ages a pin
515/// forward, never toward the future); the too-old bound is enforced at the
516/// latest possible send time. This is a conservative admission prefilter; the
517/// authoritative answerability check still runs at promotion against the real
518/// send-time wall clock, so A1 (no false conviction) holds regardless of how
519/// jitter and the answerability margin are sized. `checked_add` overflow fails
520/// closed (skip the pin).
521fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
522 let Some(latest_send) = now
523 .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
524 .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
525 else {
526 return false;
527 };
528 quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
529}
530
531/// Open the single first-audit reservation from `pending` if none is
532/// outstanding: samples the launch jitter, snapshots the shared cooldown
533/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
534/// shared implementation for both drainer call sites — the per-wake launch
535/// phase and the pre-overflow opportunity inside the ingress batch — so the
536/// two cannot drift.
537async fn open_first_audit_reservation(
538 scheduler: &mut FirstAuditScheduler,
539 cooldown: &RwLock<HashMap<PeerId, Instant>>,
540 observability: &Arc<FirstAuditObservability>,
541) {
542 if scheduler.has_reservation() {
543 return;
544 }
545 let jitter = Duration::from_millis(rand::thread_rng().gen_range(
546 0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
547 ));
548 let inflight = observability.inflight.load(Ordering::Relaxed);
549 let reserved = {
550 let cooldown = cooldown.read().await;
551 scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
552 };
553 if reserved {
554 if let Some(peer) = scheduler.reserved_peer() {
555 debug!(
556 "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
557 scheduler.pending_len()
558 );
559 }
560 }
561}
562
563/// A far-future `Instant` used to effectively DISABLE the promotion-timer
564/// select arm when no reservation is outstanding. The drainer still wakes at
565/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
566/// needs to be comfortably past the next tick.
567fn first_audit_far_future() -> Instant {
568 Instant::now()
569 .checked_add(Duration::from_hours(1))
570 .unwrap_or_else(Instant::now)
571}
572
573/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
574/// its in-flight slot and launch token from schedule time until the jitter
575/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
576/// only if the authoritative post-jitter answerability + cooldown checks pass at
577/// promotion, so a cancelled reservation leaves NO suppression behind.
578struct FirstAuditReservation {
579 event: MonetizedPinEvent,
580 ready_at: Instant,
581 inflight: FirstAuditInflightSlot,
582}
583
584/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
585/// pending queue, the dedup set, the launch limiter, the alternating lane, and
586/// the single outstanding reservation. All mutation is single-threaded in the
587/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
588/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
589/// state machine is unit-testable with injected clocks.
590struct FirstAuditScheduler {
591 /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
592 /// (a real send), never at reservation, so a cancelled reservation can be
593 /// re-nominated.
594 first_audited: LruCache<[u8; 32], ()>,
595 /// Highest-count-per-peer pending nominations not yet launched. Capped at
596 /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
597 /// one effective answerability window); at capacity a uniformly RANDOM
598 /// incumbent is displaced and counted as `capacity_evicted`, so eviction
599 /// of a specific entry can never be forced deterministically. One further
600 /// entry may be held in `reserved` outside this queue — a deliberate
601 /// one-entry guard slot, so total schedulable occupancy is at most
602 /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
603 pending: LruCache<PeerId, MonetizedPinEvent>,
604 /// Token bucket + per-peer re-audit window.
605 limiter: FirstAuditLimiter,
606 /// The single outstanding reservation (E′ serializes reservations so the
607 /// per-launch lane alternation is preserved and at most one jitter timer is
608 /// live).
609 reserved: Option<FirstAuditReservation>,
610 /// Alternating launch lane, flipped on every PROMOTION (real launch).
611 oldest_first_lane: bool,
612 /// The local node's own peer ID. A verified payment's quote list includes
613 /// the node's own quote, so the verifier emits a monetized-pin event for
614 /// the local peer on every payment it verifies. The node cannot
615 /// network-audit itself (there is no dialable address for the local peer,
616 /// so the challenge fails instantly and is miscounted as a timeout), while
617 /// any other payee that verifies the same payment schedules its own first
618 /// audit of this node's pin — a self-dial adds no coverage either way.
619 /// Such an event is dropped at ingress: never queued, and hence never
620 /// launched nor marked first-audited.
621 self_peer: PeerId,
622 /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
623 /// scheduler so tests can seed it and reproduce eviction sequences exactly;
624 /// production seeds from OS entropy at construction.
625 rng: StdRng,
626}
627
628impl FirstAuditScheduler {
629 fn new(now: Instant, self_peer: PeerId) -> Self {
630 let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
631 let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
632 Self {
633 first_audited: LruCache::new(dedup_cap),
634 pending: LruCache::new(pending_cap),
635 limiter: FirstAuditLimiter::new(now),
636 reserved: None,
637 oldest_first_lane: false,
638 self_peer,
639 rng: StdRng::from_entropy(),
640 }
641 }
642
643 /// Observability getter: used by the scheduler summary log and unit tests,
644 /// both absent from a release `--no-default-features` build, so it is dead
645 /// only in that configuration.
646 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
647 fn pending_len(&self) -> usize {
648 self.pending.len()
649 }
650
651 /// Observability getter (see [`Self::pending_len`]).
652 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
653 fn tokens(&self) -> u32 {
654 self.limiter.tokens
655 }
656
657 /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
658 /// signed quote timestamp of the oldest pin still awaiting a first audit:
659 /// how close the longest-waiting pending pin is to aging out of the
660 /// answerability window. A value climbing toward the window means pending
661 /// work is expiring unaudited instead of launching; a small, steady value
662 /// means the queue is draining promptly. Returns `0` when `pending` is empty
663 /// and saturates to `0` for a future-dated quote (clock skew), never panics.
664 #[cfg_attr(not(feature = "logging"), allow(dead_code))]
665 fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
666 self.pending
667 .iter()
668 .map(|(_, e)| e.quote_ts)
669 .min()
670 .and_then(|oldest| now.duration_since(oldest).ok())
671 .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
672 }
673
674 /// Drop every pending nomination that has aged past the answerability
675 /// horizon. `try_reserve` collects expired entries only while it can scan —
676 /// under token starvation it returns at the budget gate first — so without
677 /// a periodic sweep dead entries squat the capped pending queue (displacing
678 /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
679 /// telemetry. Each removal is accounted as `outside_answerability_window`,
680 /// exactly like a scan-time expiry. Returns how many entries were dropped;
681 /// survivor recency is untouched.
682 fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
683 let expired: Vec<PeerId> = self
684 .pending
685 .iter()
686 .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
687 .map(|(peer, _)| *peer)
688 .collect();
689 for peer in &expired {
690 self.pending.pop(peer);
691 }
692 if !expired.is_empty() {
693 obs.outside_answerability_window.fetch_add(
694 u64::try_from(expired.len()).unwrap_or(u64::MAX),
695 Ordering::Relaxed,
696 );
697 }
698 expired.len()
699 }
700
701 fn has_reservation(&self) -> bool {
702 self.reserved.is_some()
703 }
704
705 /// Whether admitting `event` would displace a DIFFERENT peer's pending
706 /// entry: the queue is at capacity and `event.peer` has no incumbent to
707 /// coalesce into. The drainer checks this before enqueueing so pending
708 /// work gets a reservation opportunity BEFORE destructive overflow
709 /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
710 /// of `pending`, freeing the slot without any eviction.
711 fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
712 self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
713 }
714
715 /// When the outstanding reservation becomes eligible for promotion.
716 fn reserved_ready_at(&self) -> Option<Instant> {
717 self.reserved.as_ref().map(|r| r.ready_at)
718 }
719
720 /// The peer of the outstanding reservation, if any.
721 fn reserved_peer(&self) -> Option<PeerId> {
722 self.reserved.as_ref().map(|r| r.event.peer)
723 }
724
725 /// Admit a monetized nomination into `pending`. Dropped at ingress if it
726 /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
727 /// if already first-audited; the window screen is bypassed for the currently
728 /// reserved peer (so a successor is retained across the reservation, never
729 /// window-dropped); otherwise window-screened. Coalescing is
730 /// highest-count-per-peer (newest on a tie) — a lower-count successor never
731 /// displaces a higher-count pending pin. An incumbent that has aged past
732 /// the answerability horizon is dropped (and accounted as an expiry) before
733 /// coalescing, so a dead pin never vetoes a live nomination. Admission for
734 /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
735 /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
736 /// displacement is accounted as `capacity_evicted` and stamps no
737 /// suppression, so a displaced peer's next nomination is judged like any
738 /// newcomer. The drainer additionally offers a reservation opportunity
739 /// via [`Self::would_displace`] before calling this on an overflowing
740 /// arrival.
741 fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
742 if event.peer == self.self_peer {
743 obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
744 return;
745 }
746 if self.first_audited.contains(&event.pin) {
747 obs.duplicates.fetch_add(1, Ordering::Relaxed);
748 return;
749 }
750 let reserved_peer = self.reserved_peer();
751 let is_reserved_peer = reserved_peer == Some(event.peer);
752 if !is_reserved_peer
753 && !self
754 .limiter
755 .window_allows(&event.peer, event.key_count, Instant::now())
756 {
757 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
758 return;
759 }
760 // A pending incumbent past the answerability horizon can never launch,
761 // yet its (possibly higher) key count would still win the coalesce
762 // against a live incoming — e.g. a fresh post-prune lower-count pin —
763 // and under token starvation no reserve scan runs to collect it. Drop
764 // it first so the incoming is judged on its own merits.
765 let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
766 !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
767 });
768 if stale_incumbent {
769 self.pending.pop(&event.peer);
770 obs.outside_answerability_window
771 .fetch_add(1, Ordering::Relaxed);
772 }
773 // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
774 // tie.
775 match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
776 FirstAuditQueueOutcome::Queued => {
777 obs.queued.fetch_add(1, Ordering::Relaxed);
778 }
779 FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
780 obs.coalesced.fetch_add(1, Ordering::Relaxed);
781 }
782 FirstAuditQueueOutcome::SuppressedLower => {
783 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
784 }
785 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
786 obs.queued.fetch_add(1, Ordering::Relaxed);
787 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
788 }
789 }
790 }
791
792 /// Attempt to create the single reservation from `pending` (E′ reserve).
793 /// Scans in the current lane order and reserves the FIRST eligible pin:
794 /// consumes one token, acquires one in-flight slot, and sets `ready_at =
795 /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
796 /// flip the lane — those happen only at promotion. Returns whether a
797 /// reservation was made. `cooldown` is a read-only snapshot (the
798 /// authoritative check-and-stamp is at promotion).
799 fn try_reserve(
800 &mut self,
801 mono_now: Instant,
802 inflight: u64,
803 jitter: Duration,
804 cooldown: &HashMap<PeerId, Instant>,
805 obs: &Arc<FirstAuditObservability>,
806 ) -> bool {
807 if self.reserved.is_some() || self.pending.is_empty() {
808 return false;
809 }
810 self.limiter.refill(mono_now);
811 if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
812 obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
813 return false;
814 }
815 // MRU->LRU order; reverse for the oldest-first lane so the preferred
816 // end is at the front.
817 let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
818 .pending
819 .iter()
820 .enumerate()
821 .map(|(i, (p, e))| (i, *p, *e))
822 .collect();
823 self.pending.clear();
824 if self.oldest_first_lane {
825 ordered.reverse();
826 }
827 let mut chosen: Option<MonetizedPinEvent> = None;
828 let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
829 for (idx, peer, event) in ordered {
830 if chosen.is_some() {
831 kept.push((idx, peer, event));
832 continue;
833 }
834 if self.first_audited.contains(&event.pin) {
835 obs.duplicates.fetch_add(1, Ordering::Relaxed);
836 continue; // drop: already audited
837 }
838 if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
839 obs.outside_answerability_window
840 .fetch_add(1, Ordering::Relaxed);
841 continue; // drop: cannot stay answerable through the jitter
842 }
843 // Window + budget + inflight. Tokens do not decrease during the
844 // scan (reserve happens after the loop) and `inflight` is fixed, so
845 // after the upfront budget gate `assess` never returns RateDeferred
846 // here; a defensive RateDeferred keeps the pin.
847 match self
848 .limiter
849 .assess(&peer, event.key_count, mono_now, inflight)
850 {
851 LimiterVerdict::WindowDeduped => {
852 obs.window_deduped.fetch_add(1, Ordering::Relaxed);
853 continue; // drop: recently first-audited, no count jump
854 }
855 LimiterVerdict::RateDeferred => {
856 kept.push((idx, peer, event));
857 continue; // keep (defensive; unreachable after upfront gate)
858 }
859 LimiterVerdict::Admit => {}
860 }
861 if !cooldown_would_allow(cooldown, &peer, mono_now) {
862 obs.cooldown_deferred_attempts
863 .fetch_add(1, Ordering::Relaxed);
864 kept.push((idx, peer, event));
865 continue; // keep: on shared cooldown, retry later
866 }
867 chosen = Some(event);
868 }
869 // Restore relative recency (oldest re-put first -> newest stays MRU).
870 kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
871 for (_, peer, event) in kept {
872 self.pending.put(peer, event);
873 }
874 let Some(event) = chosen else {
875 return false;
876 };
877 self.limiter.reserve_token();
878 let inflight_slot = FirstAuditInflightSlot::acquire(obs);
879 let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
880 self.reserved = Some(FirstAuditReservation {
881 event,
882 ready_at,
883 inflight: inflight_slot,
884 });
885 true
886 }
887
888 /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
889 fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
890 if self
891 .reserved
892 .as_ref()
893 .is_some_and(|r| mono_now >= r.ready_at)
894 {
895 self.reserved.take()
896 } else {
897 None
898 }
899 }
900
901 /// Authoritative promotion of a due reservation (E′). The caller holds the
902 /// shared cooldown write lock and passes the real send-time `wall_now` and
903 /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
904 /// launch, or `None` when the launch was cancelled (answerability lapsed
905 /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
906 /// On both `None` paths the token is refunded, the in-flight slot released,
907 /// and NO suppression is recorded.
908 ///
909 /// Known operational residual: suppression is stamped here, at promotion,
910 /// while the wire challenge is sent by the detached task the caller spawns
911 /// with the returned event. A task-start or encoding failure between the
912 /// two therefore leaves a stamped-but-unsent window. No remote input can
913 /// force that failure (it requires local task-spawn/alloc failure), so it
914 /// is accepted rather than closed; closing it would require stamping from
915 /// inside the spawned task and re-introduce the cancel-leaves-suppression
916 /// race this design exists to prevent.
917 fn resolve(
918 &mut self,
919 reservation: FirstAuditReservation,
920 wall_now: SystemTime,
921 mono_now: Instant,
922 cooldown: &mut HashMap<PeerId, Instant>,
923 obs: &Arc<FirstAuditObservability>,
924 ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
925 let FirstAuditReservation {
926 event, inflight, ..
927 } = reservation;
928 // Authoritative answerability at the REAL send time.
929 if !quote_within_audit_window(event.quote_ts, wall_now) {
930 self.limiter.refund_token();
931 obs.outside_answerability_window
932 .fetch_add(1, Ordering::Relaxed);
933 drop(inflight);
934 return None; // cancelled; nothing stamped, nothing to roll back
935 }
936 // Authoritative shared-cooldown check-and-stamp. Losing this race to a
937 // concurrent gossip audit requeues the reserved event through the SAME
938 // security-aware coalescing: the reserved event is OLDER than any
939 // same-peer successor (`incoming_is_newer = false`), so a higher-count
940 // reserved event still wins over a lower-count successor (the inflated
941 // pin must be audited), while an equal/higher successor is preserved.
942 if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
943 self.limiter.refund_token();
944 obs.cooldown_deferred_attempts
945 .fetch_add(1, Ordering::Relaxed);
946 drop(inflight);
947 // Account for the requeue outcome (the nomination itself was already
948 // counted at ingress, so `queued` is not re-incremented): a capacity
949 // eviction of a DIFFERENT peer and a suppressed reserved event are
950 // both observable per the ADR funnel.
951 match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
952 FirstAuditQueueOutcome::CapacityEvicted { .. } => {
953 obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
954 }
955 FirstAuditQueueOutcome::SuppressedLower => {
956 obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
957 }
958 FirstAuditQueueOutcome::Queued
959 | FirstAuditQueueOutcome::Coalesced
960 | FirstAuditQueueOutcome::RetainedOnTie => {}
961 }
962 return None;
963 }
964 // Promote: stamp durable suppression, flip the lane, count the launch.
965 self.limiter.promote(event.peer, event.key_count, mono_now);
966 self.first_audited.put(event.pin, ());
967 self.oldest_first_lane = !self.oldest_first_lane;
968 obs.launched.fetch_add(1, Ordering::Relaxed);
969 Some((event, inflight))
970 }
971}
972
973// ---------------------------------------------------------------------------
974// Constants
975// ---------------------------------------------------------------------------
976
977/// Prefix used by saorsa-core's request-response mechanism.
978const RR_PREFIX: &str = "/rr/";
979
980/// Bounded handoff from the P2P broadcast receiver to serial non-audit
981/// replication processing.
982///
983/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
984/// bulk/non-audit messages here. If this fills, the message is **dropped** —
985/// `start_message_handler` must never block on a full queue, because a stalled
986/// receiver laps the P2P broadcast ring and silently loses messages it never
987/// observed. Every serial-lane class has protocol recovery, so a drop costs a
988/// retry rather than the message.
989///
990/// This bounds a message COUNT, but a queued item is an owned decoded message
991/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
992/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
993/// for: the lane carries small requests and challenges alongside
994/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
995/// right for both. Responses never reach here — `replication_payload_from_event`
996/// filters them out and their requesters correlate them. ADR-0005 decision 12
997/// records the trade and why byte accounting is the correct eventual fix.
998const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
999
1000/// Maximum fresh-replication offers processed concurrently, away from the
1001/// serial non-audit loop.
1002///
1003/// Fresh offers can perform an on-chain payment verification and a 4 MiB
1004/// write. Four workers keep that latency off the responder dispatch path while
1005/// keeping concurrent EVM/storage pressure small and predictable.
1006const FRESH_OFFER_WORKER_LIMIT: usize = 4;
1007
1008/// Maximum fresh offers admitted at once, counting both those running on a
1009/// worker and those queued for one.
1010///
1011/// An admitted offer holds its payload until it completes, so this bounds
1012/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1013/// Offers past the bound are refused rather than queued or handled inline —
1014/// handling one on the message loop stalls every other non-audit message behind
1015/// a payment verification and a multi-MiB write. A refusal is not free: the
1016/// sender does not read it, so it resurfaces as a missing key at the delayed
1017/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1018/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1019/// bound is sized to make refusal rare rather than cheap.
1020const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1021
1022/// Distinct payment proofs queued for one fresh-offer key.
1023///
1024/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1025/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1026/// chunk out to the close group, so a receiver sees the same key from about that
1027/// many senders. They differ only in their proof — the bytes are provably
1028/// identical, since `fresh_offer_structural_rejection` has confirmed
1029/// `key == BLAKE3(data)` before any of them is queued.
1030///
1031/// Sizing the queue to the number of legitimate senders is what lets a failing
1032/// proof fall through to the next one instead of costing the node the record.
1033///
1034/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1035/// admitted, and a proof the handler has popped has spent its slot rather than
1036/// returned it. That distinction is what bounds the work an attacker can buy —
1037/// at most this many on-chain verifications per key, after which the entry
1038/// refuses everyone until it closes. Gating on the queue's instantaneous length
1039/// instead would let a stream of distinct sources refill each popped slot and
1040/// run unbounded sequential verifications while holding one of the four worker
1041/// slots. One attempt per source additionally means a single peer can only ever
1042/// consume one of these.
1043const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1044
1045/// Fresh-offer slots kept reachable by sources that hold none.
1046///
1047/// The property worth guaranteeing is that one peer cannot *starve* others, not
1048/// that any peer is held to a small quota. Expressing the bound as a reserve
1049/// rather than a quota is what keeps those two apart.
1050const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1051
1052/// Maximum fresh offers admitted from one source peer.
1053///
1054/// Without a per-source bound, one peer can hold every slot in the global pool
1055/// and every honest offer arriving in that window is refused — and because a
1056/// refusal is later read as absence by the sender's delayed possession check,
1057/// those refusals land as audit-severity trust penalties on the *refuser*.
1058/// That makes an unbounded global pool a targeted eviction primitive.
1059///
1060/// The bound is deliberately far looser than the other responder classes'
1061/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1062/// the opposite shape. Those are request/response: a requester needs only a
1063/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1064/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1065/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1066/// for request/response traffic therefore binds on completely legitimate
1067/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1068/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1069/// ceiling and none to the global pool.
1070///
1071/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1072/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1073/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1074// The cast is from a compile-time constant difference of two small literals
1075// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1076// relationship visible in the code rather than only in a test.
1077#[allow(clippy::cast_possible_truncation)]
1078const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1079 (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1080
1081/// Maximum paid-list notifications served concurrently.
1082///
1083/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1084/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1085/// Two workers keep cross-peer progress without multiplying concurrent EVM
1086/// and DHT lookup pressure.
1087const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1088
1089/// Maximum paid-list notifications admitted across workers and their waiters.
1090///
1091/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1092/// is one-way: the protocol defines no response and the sender never retries,
1093/// so a refused notify is information permanently lost to this node until a
1094/// later verification cycle happens to re-derive the key's paid status from a
1095/// paid-list quorum. A tight admission bound therefore does not shed load, it
1096/// discards durable state — which is why the class's real protection is
1097/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1098/// is actually expensive, rather than this queue depth.
1099///
1100/// A client PUT fans one notify per key out to the whole paid close group, so
1101/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1102/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1103/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1104/// carry no chunk payload.
1105const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1106
1107/// Maximum admitted paid-list notifications from one source peer.
1108///
1109/// A quarter of the pool. One peer legitimately supplies a whole upload's
1110/// worth of notifies, so this must comfortably exceed a typical file's chunk
1111/// count in flight; it exists to stop a single source evicting every other
1112/// peer's durable paid-list evidence, not to ration ordinary traffic.
1113const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1114
1115/// Maximum fetch responses served concurrently.
1116///
1117/// Each successful response can upload a 4 MiB chunk. Matching
1118/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1119/// simultaneous chunk data, which avoids saturating typical home upload links.
1120const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1121
1122/// Maximum fetch requests admitted across workers and their bounded waiters.
1123///
1124/// Four worker waves absorb short bursts without retaining chunk bytes—the
1125/// request contains only a key—while the dequeue deadline sheds work before a
1126/// sustained flood can keep the node serving requests whose callers timed out.
1127const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1128
1129/// Maximum admitted fetch requests from one source peer.
1130///
1131/// Two requests let one peer pipeline useful reads while leaving at least one
1132/// of the three workers available to other peers under a single-source flood.
1133const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1134
1135/// Maximum verification batches served concurrently.
1136///
1137/// Point lookups are fast, but a batch can contain 8,192 of them. Two
1138/// workers isolate that synchronous work from message dispatch without turning
1139/// large batches into an I/O fan-out throughput contest.
1140const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1141
1142/// Maximum verification batches admitted across workers and bounded waiters.
1143///
1144/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1145/// deadline prevents queued batches from consuming lookup capacity after their
1146/// requesters have stopped waiting.
1147const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1148
1149/// Maximum admitted verification batches from one source peer.
1150///
1151/// Senders already aggregate a peer's keys into one batch. One outstanding
1152/// batch therefore preserves useful work while reserving the other worker and
1153/// the bounded queue for different peers.
1154const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1155
1156/// Maximum neighbor-sync requests served concurrently across source peers.
1157///
1158/// Building a response scans local keys and performs DHT lookups, so two
1159/// workers allow cross-peer progress without multiplying that expensive scan
1160/// into broad network and storage contention.
1161const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1162
1163/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1164///
1165/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1166/// payloads bounded; expired waiters are shed before any key scan begins.
1167const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1168
1169/// Maximum admitted neighbor-sync requests from one source peer.
1170///
1171/// Sync history must be updated before repair proofs for the same peer. A
1172/// single slot preserves that ordering while independent peers remain parallel.
1173const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1174
1175/// Match an inbound topic against the replication protocol ids, in both the bare
1176/// gossip form and the `/rr/<id>` request-response form.
1177///
1178/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1179/// was the RR form. The matched id is carried into the handler so it can enforce
1180/// that subtree messages only arrive on the subtree id.
1181fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1182 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1183 if topic == id {
1184 return Some((id, false));
1185 }
1186 if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1187 if rest == id {
1188 return Some((id, true));
1189 }
1190 }
1191 }
1192 None
1193}
1194
1195/// Whether a decoded body belongs on the protocol id it arrived on:
1196/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1197/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1198///
1199/// The receive guard drops any mismatch (a cross-version or misrouted message);
1200/// sharing this one predicate between the guard and its regression test means a
1201/// change to the rule cannot pass the test unnoticed.
1202fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1203 protocol == response_protocol_for(body)
1204}
1205
1206/// The protocol id a body belongs on — the single source of truth for BOTH
1207/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1208/// response selector in `send_replication_response_checked`.
1209///
1210/// Sharing one function makes the subtree/core isolation symmetric.
1211fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1212 if body.is_subtree_audit() {
1213 SUBTREE_AUDIT_PROTOCOL_ID
1214 } else {
1215 REPLICATION_PROTOCOL_ID
1216 }
1217}
1218
1219fn fresh_offer_payment_context() -> VerificationContext {
1220 VerificationContext::FreshReplication
1221}
1222
1223fn paid_notify_payment_context() -> VerificationContext {
1224 VerificationContext::PaidListAdmission
1225}
1226
1227/// Boxed future type for in-flight fetch tasks.
1228type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1229
1230/// Fresh-offer keys currently being handled, each with the proofs still to try.
1231///
1232/// Concurrent duplicates are routine: a client PUT is confirmed by
1233/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1234/// commonly arrives from several senders at once. Collapsing them onto one
1235/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1236/// and an on-chain verification per copy.
1237///
1238/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1239/// refusing every later offer outright made the first arrival the only arrival:
1240/// if its proof failed, the record was lost even though a valid proof for the
1241/// same bytes was queued behind it, and the resulting absence was charged to
1242/// this node by the delayed possession check. So the entry holds the bytes once
1243/// and queues each sender's proof, and the handler works down that queue. A
1244/// later offer therefore costs a proof, not a payload — sound only because
1245/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1246/// every one of them before it is queued, which is what makes their bytes
1247/// provably identical.
1248///
1249/// Entries are exact keys rather than hash shards. A node only receives offers
1250/// for keys it is close to, so the accepted key set clusters tightly around its
1251/// own ID — any index derived from the key would land nearly every offer on one
1252/// shard and serialize unrelated keys behind each other. Exact keys keep them
1253/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1254/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1255///
1256/// The critical section is a map insert, pop, or remove and is never held across
1257/// an await, so this is a blocking mutex rather than an async one.
1258type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1259
1260/// One sender's unverified claim to have paid for a key already in flight.
1261///
1262/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1263/// content-address check ran before this attempt was queued.
1264struct FreshOfferAttempt {
1265 source: PeerId,
1266 proof_of_payment: Vec<u8>,
1267 request_id: u64,
1268 rr_message_id: Option<String>,
1269}
1270
1271/// Proofs still to try for one in-flight key, and who supplied them.
1272///
1273/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1274/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1275struct FreshOfferEntry {
1276 /// Untried proofs in arrival order. The handler holds the current one.
1277 pending: VecDeque<FreshOfferAttempt>,
1278 /// Sources already represented, so one peer cannot fill the queue alone.
1279 sources: HashSet<PeerId>,
1280 /// Proofs admitted over this entry's whole life, **never decremented**.
1281 ///
1282 /// The budget has to be spent by admissions rather than held by the queue.
1283 /// The handler pops a proof before verifying it, so gating on
1284 /// `pending.len()` would let a fresh source refill the slot that pop just
1285 /// freed, and a stream of distinct sources could then run unbounded
1286 /// sequential payment verifications while holding one of only four worker
1287 /// slots. Counting admissions makes the cap a lifetime budget instead.
1288 admitted: usize,
1289}
1290
1291/// How an arriving fresh offer joined the work already in flight for its key.
1292enum FreshOfferAdmission {
1293 /// Opened the entry. This offer's handler owns the key and drives every
1294 /// queued proof, including proofs that arrive later.
1295 Opened(Box<FreshOfferEntryGuard>),
1296 /// Merged into an entry another offer opened; its handler reaches this proof
1297 /// if the ones ahead of it fail.
1298 Joined,
1299 /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1300 Full,
1301 /// This source already has a proof queued for this key.
1302 DuplicateSource,
1303}
1304
1305// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1306// `debug!`, which compiles to nothing without the feature.
1307#[cfg(feature = "logging")]
1308impl FreshOfferAdmission {
1309 /// Why the offer added nothing to the work already queued for its key.
1310 ///
1311 /// Local logging only — the wire reason stays uniform so a probing peer
1312 /// cannot tell a full queue from a repeat of its own proof.
1313 const fn surplus_reason(&self) -> &'static str {
1314 match self {
1315 Self::DuplicateSource => "this source already has a proof queued",
1316 Self::Full => "the key already holds its full complement of proofs",
1317 Self::Opened(_) | Self::Joined => "not surplus",
1318 }
1319 }
1320}
1321
1322/// RAII ownership of one in-flight fresh-offer key.
1323///
1324/// Clears the entry on drop, so an early return, an error, or a panic cannot
1325/// strand a key as permanently in flight. Also owns the single copy of the
1326/// offered bytes that every queued proof is tried against.
1327struct FreshOfferEntryGuard {
1328 in_flight: FreshOfferInFlight,
1329 key: XorName,
1330 /// The bytes every attempt for this key shares, held exactly once.
1331 data: Vec<u8>,
1332 /// Arrival of the offer that opened the entry.
1333 received_at: Instant,
1334 /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1335 /// a *later* offer has since opened for the same key.
1336 holds_entry: bool,
1337}
1338
1339impl FreshOfferEntryGuard {
1340 /// Open an entry for this offer's key, or queue its proof behind the entry
1341 /// already open.
1342 ///
1343 /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1344 /// on every other outcome they are dropped here rather than held for the
1345 /// lifetime of the entry.
1346 fn admit(
1347 in_flight: &FreshOfferInFlight,
1348 offer: protocol::FreshReplicationOffer,
1349 source: PeerId,
1350 request_id: u64,
1351 rr_message_id: Option<String>,
1352 received_at: Instant,
1353 ) -> FreshOfferAdmission {
1354 let key = offer.key;
1355 let attempt = FreshOfferAttempt {
1356 source,
1357 proof_of_payment: offer.proof_of_payment,
1358 request_id,
1359 rr_message_id,
1360 };
1361
1362 let mut in_flight_map = in_flight.lock();
1363 if let Some(entry) = in_flight_map.get_mut(&key) {
1364 if entry.sources.contains(&source) {
1365 return FreshOfferAdmission::DuplicateSource;
1366 }
1367 // Lifetime budget, not queue depth: a proof the handler has already
1368 // popped has spent its slot, not returned it.
1369 if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1370 return FreshOfferAdmission::Full;
1371 }
1372 entry.admitted = entry.admitted.saturating_add(1);
1373 entry.sources.insert(source);
1374 entry.pending.push_back(attempt);
1375 return FreshOfferAdmission::Joined;
1376 }
1377
1378 let mut sources = HashSet::new();
1379 sources.insert(source);
1380 let mut pending = VecDeque::new();
1381 pending.push_back(attempt);
1382 in_flight_map.insert(
1383 key,
1384 FreshOfferEntry {
1385 pending,
1386 sources,
1387 admitted: 1,
1388 },
1389 );
1390 drop(in_flight_map);
1391 FreshOfferAdmission::Opened(Box::new(Self {
1392 in_flight: Arc::clone(in_flight),
1393 key,
1394 data: offer.data,
1395 received_at,
1396 holds_entry: true,
1397 }))
1398 }
1399
1400 /// The bytes every proof for this key is tried against.
1401 fn data(&self) -> &[u8] {
1402 &self.data
1403 }
1404
1405 /// When the first offer for this key arrived.
1406 fn received_at(&self) -> Instant {
1407 self.received_at
1408 }
1409
1410 /// Take the next untried proof, releasing the key when none remain.
1411 ///
1412 /// Popping and releasing happen under one lock so a proof arriving exactly
1413 /// as the queue empties is never silently discarded: it either lands in this
1414 /// entry and is returned here, or finds no entry and opens its own.
1415 fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1416 let mut in_flight = self.in_flight.lock();
1417 let Some(entry) = in_flight.get_mut(&self.key) else {
1418 self.holds_entry = false;
1419 return None;
1420 };
1421 if let Some(attempt) = entry.pending.pop_front() {
1422 return Some(attempt);
1423 }
1424 in_flight.remove(&self.key);
1425 self.holds_entry = false;
1426 None
1427 }
1428
1429 /// Release the key and return the proofs that were never tried, so their
1430 /// senders can be told the outcome the key reached without them.
1431 fn release(&mut self) -> Vec<FreshOfferAttempt> {
1432 let mut in_flight = self.in_flight.lock();
1433 self.holds_entry = false;
1434 in_flight
1435 .remove(&self.key)
1436 .map(|entry| entry.pending.into_iter().collect())
1437 .unwrap_or_default()
1438 }
1439}
1440
1441impl Drop for FreshOfferEntryGuard {
1442 fn drop(&mut self) {
1443 if self.holds_entry {
1444 self.in_flight.lock().remove(&self.key);
1445 }
1446 }
1447}
1448
1449/// Shared dependencies for one verification worker cycle.
1450struct VerificationCycleContext<'a> {
1451 p2p_node: &'a Arc<P2PNode>,
1452 paid_list: &'a Arc<PaidList>,
1453 storage: &'a Arc<ChunkStore>,
1454 queues: &'a Arc<RwLock<ReplicationQueues>>,
1455 config: &'a ReplicationConfig,
1456 bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1457 is_bootstrapping: &'a Arc<RwLock<bool>>,
1458 bootstrap_complete_notify: &'a Arc<Notify>,
1459 /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1460 /// peer's Present claim to Unresolved unless they're a credited
1461 /// holder of the key (i.e. they recently passed a commitment-bound
1462 /// audit on it under their currently-credited commitment hash).
1463 last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1464 ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1465 recent_provers: &'a Arc<RwLock<RecentProvers>>,
1466}
1467
1468/// Fetch worker polling interval in milliseconds.
1469const FETCH_WORKER_POLL_MS: u64 = 100;
1470
1471/// Verification worker polling interval in milliseconds.
1472const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1473
1474/// Verification cycle duration that is worth surfacing at info level.
1475const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1476
1477/// Standard trust event weight for per-operation success/failure signals.
1478///
1479/// Used for individual replication fetch outcomes, integrity check failures,
1480/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1481/// is reserved for confirmed audit failures.
1482const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1483/// Bound trust updates from one verification cycle. A malicious peer can
1484/// advertise thousands of bad singleton keys at once; a few independent
1485/// contradictions are enough for the trust engine without flooding it.
1486const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1487
1488/// Bootstrap drain check interval in seconds.
1489const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1490
1491/// Grace period `shutdown()` waits for each long-lived background task to
1492/// observe the cancellation token and terminate before aborting it.
1493///
1494/// Detached tasks are drained without a timeout because storage-capable work
1495/// may be awaiting a `spawn_blocking` storage operation, which continues running
1496/// if its async waiter is dropped.
1497const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1498
1499/// How often the responder rebuilds + rotates its storage commitment.
1500///
1501/// Each rebuild scans the store to compute leaf hashes; for ~10k keys this is
1502/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1503/// rotation-anchored: the responder stays answerable for the current
1504/// commitment plus every root it recently gossiped that is still in-window
1505/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1506/// its last emission (see `commitment_state`). So the rotation cadence does
1507/// not by itself bound answerability — a gossiped commitment stays
1508/// answerable across rotations until its gossip TTL lapses.
1509///
1510/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1511/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1512/// comfortably exceeds the gap between our rotation and the next gossip
1513/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1514/// Idle audit-skip pattern from being the common case.
1515///
1516/// Why not faster: the v12 pin is bound to a specific point-in-time
1517/// commitment, so rotation isn't security-critical for pin freshness —
1518/// only for keeping the committed key set current as the responder
1519/// writes new keys. 1 hour is plenty for that, and slow enough that
1520/// honest auditors mostly hit `current` or `previous` rather than the
1521/// "rotated past" case.
1522const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1523
1524/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1525/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1526/// durable well before it could matter to a restart, while the write-on-change
1527/// guard keeps idle nodes from needless disk writes.
1528const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1529
1530/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1531/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1532/// default that keeps log volume negligible.
1533const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1534
1535/// Cadence of the read-only bootstrap state snapshot used to separate drain
1536/// debt from cache and broader connectivity failures in fleet logs.
1537#[cfg(feature = "logging")]
1538const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1539
1540/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1541/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1542/// for first audit only if its SIGNED `quote_ts` lands in
1543/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1544/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1545/// badly-skewed or replayed quote) and one too old (the responder may have aged
1546/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1547/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1548/// within this margin); a legit first audit fires moments after payment
1549/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1550/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1551/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1552const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_mins(30);
1553
1554/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1555/// inside the answerability window relative to `now`, so first-auditing it cannot
1556/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1557/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1558/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1559/// All comparisons use `duration_since` (no `Duration` overflow).
1560fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1561 let too_future = quote_ts
1562 .duration_since(now)
1563 .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1564 let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1565 let too_old = now
1566 .duration_since(quote_ts)
1567 .is_ok_and(|age| age >= audit_cutoff);
1568 !(too_future || too_old)
1569}
1570
1571/// Minimum interval between commitment signature verifications for a
1572/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1573///
1574/// A sybil that bypasses the routing-table gate (e.g. by transient
1575/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1576/// per gossip message. This rate limit caps the verify-per-peer rate
1577/// at 1/min, which is comfortably above the legitimate gossip cadence
1578/// (the 10-20 min neighbor-sync round on each peer).
1579const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_mins(1);
1580
1581/// Hard cap on the size of `last_commitment_by_peer`.
1582///
1583/// Bounds the per-process memory cost of the auditor's per-peer
1584/// commitment cache. Each entry holds a `StorageCommitment`
1585/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1586/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1587/// realistic close-group neighborhood. When the cap is hit, one
1588/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1589/// order is unspecified; we do not track insertion order). The
1590/// `PeerRemoved` handler proactively drops entries as the DHT
1591/// detects departures, and `ingest_peer_commitment` only admits
1592/// commitments from peers currently in the routing table — together
1593/// the cap is the third line of defence against sybil/churn flooding.
1594const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1595
1596/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1597/// sized to the launch budget instead of the commitment cache.
1598///
1599/// The token bucket can launch at most one audit per
1600/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1601/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1602/// launchable for at most the effective answerability window
1603/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1604/// occupancy beyond `window / interval + burst` is work that cannot launch
1605/// before it expires, so admitting it only builds an aging backlog whose
1606/// telemetry measures the backlog instead of schedulable work.
1607///
1608/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1609/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1610/// rolling sample in which no arrival order lets an attacker deterministically
1611/// flush a chosen target; a fresh pin always enters the sample with an
1612/// unpredictable chance of near-immediate audit, whereas refusing at the door
1613/// would let a sustained payment flood guarantee that every later pin is never
1614/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1615/// ADR-0004 Amendment 4 for the eviction-cost math.
1616///
1617/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1618/// is usable only if the quote stays answerable through `a` plus the maximum
1619/// launch jitter and send slack, so the last usable refill is the largest
1620/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1621/// simulates the shipped predicate instant-by-instant and must agree.
1622#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1623const FIRST_AUDIT_PENDING_CAP: usize = {
1624 let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1625 .as_secs()
1626 .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1627 .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1628 .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1629 // Strictly-inside count: a refill landing exactly ON the horizon is dead
1630 // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1631 // if the launch interval is ever zeroed: a zero interval makes the budget
1632 // (and this cap) meaningless.
1633 let refills =
1634 strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1635 (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1636};
1637
1638// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1639// strictly tighter than the commitment-cache bound it replaced.
1640const _: () = {
1641 assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1642 assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1643};
1644
1645/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1646/// long-running bootstrap node cannot have the set grow without limit
1647/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1648/// the set comfortably outlives normal LRU churn but still caps the
1649/// blast radius of identity-rotation attacks. Once full we refuse new
1650/// inserts (no eviction) — keeps the historic set stable; new v12
1651/// peers above the cap are treated as legacy on rejoin, which matches
1652/// the behaviour before this set existed, not a security regression.
1653const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1654
1655// ---------------------------------------------------------------------------
1656// ReplicationEngine
1657// ---------------------------------------------------------------------------
1658
1659/// The replication engine manages all replication background tasks and state.
1660pub struct ReplicationEngine {
1661 /// Replication configuration (shared across spawned tasks).
1662 config: Arc<ReplicationConfig>,
1663 /// P2P networking node.
1664 p2p_node: Arc<P2PNode>,
1665 /// Local chunk storage.
1666 storage: Arc<ChunkStore>,
1667 /// Persistent paid-for-list.
1668 paid_list: Arc<PaidList>,
1669 /// Payment verifier for `PoP` validation.
1670 payment_verifier: Arc<PaymentVerifier>,
1671 /// Replication pipeline queues.
1672 queues: Arc<RwLock<ReplicationQueues>>,
1673 /// Neighbor sync cycle state.
1674 sync_state: Arc<RwLock<NeighborSyncState>>,
1675 /// Per-peer sync history (for `RepairOpportunity`).
1676 ///
1677 /// This map grows with peer churn and is intentionally unbounded: entries
1678 /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1679 /// naturally bounded by the routing table's k-bucket capacity.
1680 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1681 /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1682 ///
1683 /// Records when each peer was last audited so a burst of gossiped
1684 /// commitment changes cannot spawn back-to-back audits of the same peer.
1685 /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1686 audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1687 /// Gossip-private lottery attempt window (one roll per peer per window,
1688 /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1689 /// ticket never stamps the shared map and thus never defers a monetized
1690 /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1691 gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1692 /// Completed local neighbor-sync cycle epoch for proof maturity.
1693 sync_cycle_epoch: Arc<RwLock<u64>>,
1694 /// Per-key repair proof tracking for audit eligibility.
1695 repair_proofs: Arc<RwLock<RepairProofs>>,
1696 /// Bootstrap state tracking.
1697 bootstrap_state: Arc<RwLock<BootstrapState>>,
1698 /// Whether this node is currently bootstrapping.
1699 is_bootstrapping: Arc<RwLock<bool>>,
1700 /// Trigger for early neighbor sync (signalled on topology changes).
1701 sync_trigger: Arc<Notify>,
1702 /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1703 bootstrap_complete_notify: Arc<Notify>,
1704 /// Node identity (for signing storage commitments).
1705 ///
1706 /// Phase 3 of the v12 storage-bound audit design. The responder
1707 /// uses this to sign its periodically-built `StorageCommitment`.
1708 identity: Arc<NodeIdentity>,
1709 /// Responder-side commitment state (two-slot atomic rotation).
1710 ///
1711 /// Periodically rebuilt from the live key set; gossiped on
1712 /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1713 /// commitment-bound audit handler.
1714 commitment_state: Arc<ResponderCommitmentState>,
1715 /// Path to the persisted responder retention snapshot
1716 /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1717 /// node's answerability survives restart (ADR-0004 A1), which is what makes
1718 /// removing audit grace safe (an unanswerable in-window pin is then provable
1719 /// misbehaviour, not an honest crash-restart).
1720 retention_path: PathBuf,
1721 /// Auditor-side per-peer commitment record (last known commitment +
1722 /// sticky `commitment_capable` flag).
1723 ///
1724 /// Populated whenever an inbound gossip carries a verified
1725 /// commitment from the sender. Used by `audit_tick` to snapshot
1726 /// `expected_commitment_hash` into outbound challenges, and by
1727 /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1728 /// proof should be honoured. The sticky `commitment_capable` flag
1729 /// flips true on first successful ingest and never reverts (§2
1730 /// step 5).
1731 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1732 /// Sticky set of peer IDs we have EVER seen carrying a v12
1733 /// commitment, independent of whether their commitment bytes are
1734 /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1735 /// closure consults this set to keep treating churned-out
1736 /// previously-v12 peers as v12-capable (rather than degrading them
1737 /// to "legacy" credit-unconditionally) when they re-appear on the
1738 /// network before their next gossip arrives. Bounded growth: even
1739 /// at one million peers seen over the node's lifetime, the set is
1740 /// 32 MB.
1741 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1742 /// Auditor-side holder-eligibility cache (v12 §6).
1743 ///
1744 /// Recorded on successful commitment-bound audit; read by future
1745 /// quorum / paid-list eligibility checks (phase-3 stretch).
1746 recent_provers: Arc<RwLock<RecentProvers>>,
1747 /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1748 /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1749 /// failure) so a peer we've never successfully verified can't burn
1750 /// CPU on a flood of structurally-plausible-but-invalid gossips.
1751 /// Lives separately from `last_commitment_by_peer` because that
1752 /// map's records only exist after a successful verify.
1753 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1754 /// Limits concurrent outbound replication sends to prevent bandwidth
1755 /// saturation on home broadband connections.
1756 send_semaphore: Arc<Semaphore>,
1757 /// Bounds how many encoded fresh offers can wait behind `send_semaphore`;
1758 /// see [`MAX_PENDING_FRESH_OFFERS`].
1759 pending_offer_semaphore: Arc<Semaphore>,
1760 /// Fresh offers encoded and handed to their per-peer sends.
1761 fresh_offers_dispatched: Arc<AtomicU64>,
1762 /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1763 /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1764 /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1765 /// message loop so disk
1766 /// reads don't block replication; the semaphore restores a global
1767 /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1768 /// / multi-MiB byte serves.
1769 audit_responder_semaphore: Arc<Semaphore>,
1770 /// Per-source in-flight audit-responder counts, capped at
1771 /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1772 /// flood-fair: one peer spamming challenges could occupy every slot and
1773 /// starve honest auditors, whose dropped challenges then convert to
1774 /// audit timeouts against HONEST peers (codex-r2 A). This
1775 /// per-peer cap guarantees no single source can hold more than its share,
1776 /// so a flood self-throttles without denying service to everyone else.
1777 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1778 /// Windowed per-origin capacity and processing-time telemetry for every
1779 /// request sharing the audit responder pool.
1780 audit_responder_metrics: Arc<AuditResponderMetrics>,
1781 /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1782 ///
1783 /// Responsible-chunk audits, prune confirmations, and possession checks
1784 /// all use this before sending so local bursts wait instead of breaching
1785 /// the responder's deployed per-source admission cap.
1786 audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1787 /// Worker permits for bandwidth-bound fetch responses.
1788 fetch_responder_worker_semaphore: Arc<Semaphore>,
1789 /// Admission permits bounding fetch workers and queued waiters together.
1790 fetch_responder_admission_semaphore: Arc<Semaphore>,
1791 /// Per-source fetch responder counts for flood-fair admission.
1792 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1793 /// Worker permits for lookup-heavy verification batches.
1794 verification_responder_worker_semaphore: Arc<Semaphore>,
1795 /// Admission permits bounding verification workers and queued waiters.
1796 verification_responder_admission_semaphore: Arc<Semaphore>,
1797 /// Per-source verification responder counts for flood-fair admission.
1798 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1799 /// Worker permits for expensive inbound neighbor-sync requests.
1800 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1801 /// Admission permits bounding sync workers and queued waiters together.
1802 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1803 /// Per-source sync responder counts; capped at one to preserve ordering.
1804 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1805 /// Bounded worker permits for expensive fresh-offer handling.
1806 fresh_offer_worker_semaphore: Arc<Semaphore>,
1807 /// Admission permits bounding offers running on a worker or queued for one.
1808 fresh_offer_admission_semaphore: Arc<Semaphore>,
1809 /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1810 /// and turn honest senders' refusals into trust penalties on this node.
1811 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1812 /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1813 /// duplicates collapse onto one verification and one write.
1814 fresh_offer_in_flight: FreshOfferInFlight,
1815 /// Bounded worker permits for paid-list notification proof verification.
1816 paid_notify_worker_semaphore: Arc<Semaphore>,
1817 /// Admission permits bounding notifies on a worker or queued for one.
1818 paid_notify_admission_semaphore: Arc<Semaphore>,
1819 /// Per-source paid-notify counts for flood-fair admission.
1820 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1821 /// Resource controls for the HEAVY subtree-audit round 1: its own
1822 /// tight admission pool (so a burst of full-subtree hashing can't starve the
1823 /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1824 /// sessions binding a slice challenge to a matching round 1.
1825 subtree_round1: SubtreeRound1Limiter,
1826 /// Receiver for fresh-write events from the chunk PUT handler.
1827 ///
1828 /// When present, `start()` spawns the fresh-write drainer, which records
1829 /// paid-list evidence for each event immediately and forwards it to the
1830 /// offer dispatcher.
1831 fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1832 /// Pointer replication (ADR-0016), when this node stores pointers.
1833 pointers: Option<Arc<pointer::PointerReplication>>,
1834 /// Receiver for fresh pointer writes, taken by `start()`.
1835 pointer_fresh_rx: Option<mpsc::UnboundedReceiver<pointer::PointerFreshWrite>>,
1836 /// Sender for delayed possession-check events (ADR-0003). Sending a write's
1837 /// fresh offers (`fresh::send_fresh_offers`) pushes its responsible
1838 /// close-group peers here; the possession-check scheduler drains the paired
1839 /// receiver.
1840 possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1841 /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1842 possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1843 /// ADR-0004: sender the payment verifier clones to surface monetized pins
1844 /// for a deterministic first audit. The matching receiver is drained by
1845 /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1846 /// `try_send`s and drops on a full queue, so ingress memory is capped just
1847 /// like launches; a dropped nomination is penalty-free — the peer's
1848 /// gossiped commitments stay lottery-covered and its next settled payment
1849 /// re-nominates the paid pin.
1850 monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1851 /// ADR-0004: receiver half of the monetized-pin channel, taken by
1852 /// `start_first_audit_drainer`.
1853 monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1854 /// Counters shared with the first-audit drainer task, so the scheduler's
1855 /// decisions (queued / launched / self-target skipped / outcome) stay
1856 /// observable from the engine after the drainer takes the receiver.
1857 first_audit_observability: Arc<FirstAuditObservability>,
1858 /// Shutdown token.
1859 shutdown: CancellationToken,
1860 /// Background task handles.
1861 task_handles: Vec<JoinHandle<()>>,
1862 /// Tracks detached, short-lived work spawned by background producers.
1863 ///
1864 /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1865 /// tasks, and delayed possession checks may retain storage or P2P state
1866 /// after their producer exits, so shutdown drains them before those
1867 /// resources may be reopened.
1868 detached_task_tracker: TaskTracker,
1869}
1870
1871impl ReplicationEngine {
1872 /// Create a new replication engine.
1873 ///
1874 /// # Errors
1875 ///
1876 /// Returns an error if the `PaidList` LMDB environment cannot be opened
1877 /// or if the configuration fails validation.
1878 #[allow(clippy::too_many_arguments)]
1879 pub async fn new(
1880 config: ReplicationConfig,
1881 p2p_node: Arc<P2PNode>,
1882 storage: Arc<ChunkStore>,
1883 payment_verifier: Arc<PaymentVerifier>,
1884 identity: Arc<NodeIdentity>,
1885 root_dir: &Path,
1886 fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1887 shutdown: CancellationToken,
1888 ) -> Result<Self> {
1889 config.validate().map_err(Error::Config)?;
1890
1891 let paid_list = Arc::new(
1892 PaidList::new(root_dir)
1893 .await
1894 .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1895 );
1896
1897 let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1898 let config = Arc::new(config);
1899 let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1900
1901 // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1902 // Bounded (Amendment 2): every stage of the first-audit pipeline is
1903 // now capacity-limited — ingress queue here, pending set (LRU), and
1904 // launch rate (token bucket).
1905 let (monetized_pin_tx, monetized_pin_rx) =
1906 mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1907
1908 let engine = Self {
1909 config: Arc::clone(&config),
1910 p2p_node,
1911 storage,
1912 paid_list,
1913 payment_verifier,
1914 queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1915 sync_state: Arc::new(RwLock::new(initial_neighbors)),
1916 sync_history: Arc::new(RwLock::new(HashMap::new())),
1917 audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1918 gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1919 sync_cycle_epoch: Arc::new(RwLock::new(0)),
1920 repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1921 bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1922 is_bootstrapping: Arc::new(RwLock::new(true)),
1923 sync_trigger: Arc::new(Notify::new()),
1924 bootstrap_complete_notify: Arc::new(Notify::new()),
1925 identity,
1926 commitment_state: Arc::new(ResponderCommitmentState::new()),
1927 retention_path: root_dir.join("commitment_retention.bin"),
1928 last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1929 ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1930 recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1931 sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1932 send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1933 pending_offer_semaphore: Arc::new(Semaphore::new(MAX_PENDING_FRESH_OFFERS)),
1934 fresh_offers_dispatched: Arc::new(AtomicU64::new(0)),
1935 audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1936 audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1937 audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1938 audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1939 fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1940 FETCH_RESPONDER_WORKER_LIMIT,
1941 )),
1942 fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1943 FETCH_RESPONDER_MAX_OUTSTANDING,
1944 )),
1945 fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1946 verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1947 VERIFICATION_RESPONDER_WORKER_LIMIT,
1948 )),
1949 verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1950 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1951 )),
1952 verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1953 neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1954 NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1955 )),
1956 neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1957 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1958 )),
1959 neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1960 fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1961 fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1962 fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1963 fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1964 paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1965 paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1966 paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1967 subtree_round1: SubtreeRound1Limiter::new(
1968 config.subtree_round1_responder_cooldown,
1969 config.subtree_round1_max_concurrent,
1970 ),
1971 fresh_write_rx: Some(fresh_write_rx),
1972 pointers: None,
1973 pointer_fresh_rx: None,
1974 possession_check_tx,
1975 possession_check_rx: Some(possession_check_rx),
1976 monetized_pin_tx,
1977 monetized_pin_rx: Some(monetized_pin_rx),
1978 first_audit_observability: Arc::new(FirstAuditObservability::default()),
1979 shutdown,
1980 task_handles: Vec::new(),
1981 detached_task_tracker: TaskTracker::new(),
1982 };
1983 // ADR-0004 A1: reload persisted responder retention BEFORE any task
1984 // spawns, so an honest restarted node is answerable for its pre-restart
1985 // pins from the first audit it serves, and the persist loop never races
1986 // an empty snapshot over the good on-disk file.
1987 load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1988 Ok(engine)
1989 }
1990
1991 /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1992 /// (commitments that backed a payment) for a first audit. Cloneable; the
1993 /// engine drains the matching receiver. Bounded: senders must `try_send`
1994 /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1995 #[must_use]
1996 pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1997 self.monetized_pin_tx.clone()
1998 }
1999
2000 /// Get a reference to the `PaidList`.
2001 #[must_use]
2002 pub fn paid_list(&self) -> &Arc<PaidList> {
2003 &self.paid_list
2004 }
2005
2006 /// Get a reference to the responder's commitment state. Used by audit
2007 /// handlers to look up commitments by hash; used by the rotation tick
2008 /// to install fresh ones.
2009 #[must_use]
2010 pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
2011 &self.commitment_state
2012 }
2013
2014 /// Get a reference to the auditor's last-commitment-by-peer table.
2015 #[must_use]
2016 pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2017 &self.last_commitment_by_peer
2018 }
2019
2020 /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2021 /// will be read by quorum / paid-list eligibility checks.
2022 #[must_use]
2023 pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2024 &self.recent_provers
2025 }
2026
2027 /// Test-only: rebuild + rotate this node's storage commitment now over its
2028 /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2029 /// just stored without waiting for the rotation cadence.
2030 ///
2031 /// # Errors
2032 ///
2033 /// Propagates any error from reading the local key set or building/signing
2034 /// the commitment.
2035 #[cfg(any(test, feature = "test-utils"))]
2036 pub async fn rebuild_commitment_now(&self) -> Result<()> {
2037 rebuild_and_rotate_commitment(
2038 &self.storage,
2039 self.pointers.as_ref().map(|p| p.store()),
2040 &self.identity,
2041 &self.commitment_state,
2042 &self.p2p_node,
2043 &self.config,
2044 )
2045 .await
2046 }
2047
2048 /// Test-only: directly seed this node's cached commitment for `peer`,
2049 /// simulating "we received `peer`'s gossiped commitment" without depending
2050 /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2051 /// peer's commitment deterministically.
2052 #[cfg(any(feature = "test-utils", test))]
2053 pub async fn inject_peer_commitment_for_test(
2054 &self,
2055 peer: &PeerId,
2056 commitment: StorageCommitment,
2057 ) {
2058 let now = Instant::now();
2059 self.last_commitment_by_peer
2060 .write()
2061 .await
2062 .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2063 self.ever_capable_peers.write().await.insert(*peer);
2064 }
2065
2066 /// Test-only: isolate a monetized first audit of `peer` from live gossip
2067 /// audits. Suppresses new gossip lottery attempts for the current cooldown
2068 /// window and clears any shared cooldown stamped by an earlier gossip
2069 /// launch. The locks follow the production gossip-audit lock order.
2070 #[cfg(any(test, feature = "test-utils"))]
2071 pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2072 let now = Instant::now();
2073 let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2074 let mut launched = self.audit_on_gossip_cooldown.write().await;
2075 lottery_attempts.insert(*peer, now);
2076 launched.remove(peer);
2077 }
2078
2079 /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2080 /// commitment this node has cached for it (from gossip), over the live wire.
2081 /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2082 /// in a real two-node setting without waiting for the gossip cadence.
2083 ///
2084 /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2085 /// peer yet (gossip hasn't reached us). Gated to test builds.
2086 #[cfg(any(test, feature = "test-utils"))]
2087 pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2088 let target = {
2089 let map = self.last_commitment_by_peer.read().await;
2090 map.get(peer)
2091 .and_then(PeerCommitmentRecord::last_commitment)
2092 .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2093 };
2094 let Some((pin, key_count)) = target else {
2095 return audit::AuditTickResult::Idle;
2096 };
2097 let credit = storage_commitment_audit::AuditCredit {
2098 recent_provers: &self.recent_provers,
2099 };
2100 storage_commitment_audit::run_subtree_audit(
2101 &self.p2p_node,
2102 &self.config,
2103 peer,
2104 pin,
2105 key_count,
2106 Some(&credit),
2107 )
2108 .await
2109 }
2110
2111 /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2112 /// tests assert what the live drainer decided for an injected
2113 /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2114 #[cfg(any(test, feature = "test-utils"))]
2115 #[must_use]
2116 pub fn first_audit_stats(&self) -> FirstAuditStats {
2117 let o = &self.first_audit_observability;
2118 FirstAuditStats {
2119 received: o.received.load(Ordering::Relaxed),
2120 queued: o.queued.load(Ordering::Relaxed),
2121 self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2122 launched: o.launched.load(Ordering::Relaxed),
2123 passed: o.passed.load(Ordering::Relaxed),
2124 timed_out: o.timed_out.load(Ordering::Relaxed),
2125 failed: o.failed.load(Ordering::Relaxed),
2126 }
2127 }
2128
2129 /// Test-only: run the possession check immediately for `key` against
2130 /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2131 ///
2132 /// Penalises any peer that does not hold `key` at `AuditChallenge`
2133 /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2134 /// deterministically without waiting for the scheduled check.
2135 #[cfg(any(test, feature = "test-utils"))]
2136 pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2137 possession::run_possession_check(
2138 key,
2139 peers,
2140 &self.p2p_node,
2141 &self.storage,
2142 &self.config,
2143 &self.sync_state,
2144 &self.audit_challenge_coordinator,
2145 &self.shutdown,
2146 )
2147 .await;
2148 }
2149
2150 /// Test-only: place `key` directly into the fetch queue as though a
2151 /// verification cycle had just promoted it, with `sources` as its
2152 /// verified holders. Returns whether the key was enqueued.
2153 ///
2154 /// Bypasses admission, verification, and the promotion-time
2155 /// responsibility pre-filter, modelling a promotion decision that has
2156 /// since gone stale (topology churn between promotion and download).
2157 /// The only guard left standing is the per-attempt recheck inside
2158 /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2159 /// exercise.
2160 ///
2161 /// A replica hint for `key` that reached pending verification first is
2162 /// dropped, so the key enters the fetch queue as it would have without
2163 /// it. Callers host the chunk on a holder before calling this, which makes
2164 /// it advertisable, and a change to the holder's closest peers starts a
2165 /// neighbour-sync round at once. Left in place, the hint's entry made
2166 /// `enqueue_fetch` refuse the key, and with one holder and no paid-list
2167 /// entry it does not reach a quorum, so the key was not fetched that way
2168 /// either. A key already in the fetch queue or in flight, or a full fetch
2169 /// queue, still returns `false`.
2170 #[cfg(any(test, feature = "test-utils"))]
2171 pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2172 let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2173 let mut queues = self.queues.write().await;
2174 queues.remove_pending(&key);
2175 queues.enqueue_fetch(key, distance, sources)
2176 }
2177
2178 /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2179 /// (pending verification, fetch queue, or in-flight fetch).
2180 #[cfg(any(test, feature = "test-utils"))]
2181 pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2182 self.queues.read().await.contains_key(key)
2183 }
2184
2185 /// Test-only: whether `key` is in the fetch queue or in flight, which is
2186 /// where a candidate placed by [`Self::enqueue_fetch_for_test`] stays
2187 /// until it resolves.
2188 ///
2189 /// Such a candidate carries no verification retry metadata, so it is never
2190 /// requeued for verification: once it leaves these two stages it is done.
2191 /// Pending verification is left out on purpose. The chunk the test hosted
2192 /// stays advertisable, so a replica hint can put the key there after the
2193 /// candidate resolved, and counting that entry would hold a test's wait
2194 /// loop until its deadline.
2195 #[cfg(any(test, feature = "test-utils"))]
2196 pub async fn fetch_queued_or_in_flight_for_test(&self, key: &XorName) -> bool {
2197 self.queues.read().await.fetch_queued_or_in_flight(key)
2198 }
2199
2200 /// Test-only: place `key` into pending verification as though `hinter` had
2201 /// just advertised it with a replica hint. Returns whether it was admitted.
2202 ///
2203 /// Enters the pipeline one stage earlier than
2204 /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2205 /// decides about the key is observable.
2206 #[cfg(any(test, feature = "test-utils"))]
2207 pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2208 let now = Instant::now();
2209 let entry = VerificationEntry {
2210 state: VerificationState::PendingVerify,
2211 verified_sources: Vec::new(),
2212 tried_sources: HashSet::new(),
2213 created_at: now,
2214 next_verify_at: now,
2215 hint_sources: HashSet::from([hinter]),
2216 replica_hint_sources: HashSet::from([hinter]),
2217 unresolved_retries: 0,
2218 no_holder_reported: false,
2219 };
2220 self.queues
2221 .write()
2222 .await
2223 .add_pending_verify(key, entry)
2224 .admitted()
2225 }
2226
2227 /// Test-only: how far ahead `key`'s next verification round is scheduled,
2228 /// or `None` when the key is not pending verification.
2229 #[cfg(any(test, feature = "test-utils"))]
2230 pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2231 self.queues.read().await.get_pending(key).map(|entry| {
2232 entry
2233 .next_verify_at
2234 .saturating_duration_since(Instant::now())
2235 })
2236 }
2237
2238 /// Replicate pointers too (ADR-0016): the records in `store`, and the
2239 /// fresh writes the pointer PUT handler sends on `fresh_writes`.
2240 ///
2241 /// The PUT handler is not wired to ask this engine anything before it
2242 /// takes a final state (ADR-0018); [`Self::with_pointer_service`] wires
2243 /// both.
2244 ///
2245 /// Call before [`Self::start`].
2246 pub fn with_pointers(
2247 &mut self,
2248 store: PointerStore,
2249 fresh_writes: mpsc::UnboundedReceiver<pointer::PointerFreshWrite>,
2250 ) {
2251 self.pointers = Some(Arc::new(pointer::PointerReplication::new(
2252 store,
2253 Arc::clone(&self.storage),
2254 Arc::clone(&self.p2p_node),
2255 Arc::clone(&self.payment_verifier),
2256 Arc::clone(&self.config),
2257 Arc::clone(&self.is_bootstrapping),
2258 Arc::clone(&self.send_semaphore),
2259 self.shutdown.clone(),
2260 self.detached_task_tracker.clone(),
2261 )));
2262 self.pointer_fresh_rx = Some(fresh_writes);
2263 }
2264
2265 /// Replicate the pointers `service` stores (ADR-0016), and wire the
2266 /// service to this engine both ways: it hands each newly stored paid
2267 /// state here to be offered on, and asks here before it takes a final
2268 /// state (ADR-0018).
2269 ///
2270 /// Call before [`Self::start`].
2271 pub fn with_pointer_service(&mut self, service: &PointerService) {
2272 let (writes, fresh_writes) = mpsc::unbounded_channel();
2273 service.attach_fresh_writes(writes);
2274 self.with_pointers(service.store().clone(), fresh_writes);
2275 if let Some(replication) = &self.pointers {
2276 let witness: Arc<dyn FinalStateWitness> = replication.clone();
2277 service.attach_final_state_witness(witness);
2278 }
2279 }
2280
2281 /// The pointer replication, when enabled. Tests use it to drive rounds.
2282 #[cfg(any(test, feature = "test-utils"))]
2283 #[must_use]
2284 pub fn pointer_replication(&self) -> Option<&Arc<pointer::PointerReplication>> {
2285 self.pointers.as_ref()
2286 }
2287
2288 /// Test-only: pending-offer permits not currently held by an encoded
2289 /// fresh offer. Equals [`MAX_PENDING_FRESH_OFFERS`] when no fresh
2290 /// replication is in flight, which is how tests prove a burst of writes
2291 /// drained without leaking a permit.
2292 #[cfg(any(test, feature = "test-utils"))]
2293 #[must_use]
2294 pub fn pending_offer_permits_available(&self) -> usize {
2295 self.pending_offer_semaphore.available_permits()
2296 }
2297
2298 /// Test-only: fresh offers encoded and handed to their per-peer sends
2299 /// since the engine was created. A write skipped because its chunk is gone
2300 /// is not counted.
2301 #[cfg(any(test, feature = "test-utils"))]
2302 #[must_use]
2303 pub fn fresh_offers_dispatched(&self) -> u64 {
2304 self.fresh_offers_dispatched.load(Ordering::Relaxed)
2305 }
2306
2307 /// Test-only: take every outbound replication send permit. Until the
2308 /// returned permit is dropped, encoded fresh offers wait behind the send
2309 /// stage, so a test can fill the pending-offer budget deterministically.
2310 /// The send semaphore is never closed, so this returns `Some`.
2311 #[cfg(any(test, feature = "test-utils"))]
2312 pub async fn hold_replication_sends(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
2313 let all = u32::try_from(MAX_CONCURRENT_REPLICATION_SENDS).ok()?;
2314 Arc::clone(&self.send_semaphore)
2315 .acquire_many_owned(all)
2316 .await
2317 .ok()
2318 }
2319
2320 /// Start all background tasks.
2321 ///
2322 /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2323 /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2324 /// missed by the bootstrap-sync gate.
2325 pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2326 if !self.task_handles.is_empty() {
2327 error!("ReplicationEngine::start() called while already running — ignoring");
2328 return;
2329 }
2330 info!("Starting replication engine");
2331
2332 self.start_message_handler();
2333 // Takes out of service the rotted chunks that round-1 proofs report.
2334 self.start_corrupt_recheck_worker();
2335 self.start_neighbor_sync_loop();
2336 self.start_self_lookup_loop();
2337 // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2338 // chunks they SHOULD store (responsibility + prior hint).
2339 self.start_audit_loop();
2340 // Audit #1 (storage-commitment) is gossip-triggered in the message
2341 // handler when a peer's commitment is ingested, not on a periodic tick.
2342 self.start_commitment_rotation_loop();
2343 self.start_retention_persist_loop();
2344 self.start_fetch_worker();
2345 self.start_verification_worker();
2346 self.start_bootstrap_sync(dht_events);
2347 self.start_fresh_replication();
2348 self.start_possession_check_scheduler();
2349 if let Some(pointers) = &self.pointers {
2350 self.task_handles.push(pointers.start_verification_loop());
2351 if let Some(writes) = self.pointer_fresh_rx.take() {
2352 self.task_handles.push(pointers.start_fresh_drainer(writes));
2353 }
2354 }
2355 // ADR-0004: deterministic first audit of commitments that backed a
2356 // payment (surfaced by the verifier cross-check).
2357 self.start_first_audit_drainer();
2358 // V2-623: periodic cumulative per-variant traffic accounting.
2359 self.start_traffic_summary_loop();
2360 // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2361 #[cfg(feature = "logging")]
2362 self.start_bootstrap_state_snapshot_loop();
2363 #[cfg(feature = "logging")]
2364 self.start_audit_responder_summary_loop();
2365
2366 info!(
2367 "Replication engine started with {} background tasks",
2368 self.task_handles.len()
2369 );
2370 }
2371
2372 /// Returns `true` if the node is still in the replication bootstrap phase.
2373 ///
2374 /// During bootstrap, audit challenges return `Bootstrapping` instead of
2375 /// digests, and neighbor sync responses carry `bootstrapping: true`.
2376 pub async fn is_bootstrapping(&self) -> bool {
2377 *self.is_bootstrapping.read().await
2378 }
2379
2380 /// Wait until the replication bootstrap phase completes.
2381 ///
2382 /// Returns immediately if bootstrap has already completed. Useful for
2383 /// readiness probes, health checks, and test harnesses that need the
2384 /// node to be fully operational before proceeding.
2385 ///
2386 /// Returns `true` if bootstrap completed within the timeout, `false`
2387 /// if the timeout elapsed first.
2388 pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2389 // Register the notification future *before* checking the flag so that
2390 // a transition between the read and the await is not missed.
2391 let notified = self.bootstrap_complete_notify.notified();
2392 tokio::pin!(notified);
2393 notified.as_mut().enable();
2394
2395 if !*self.is_bootstrapping.read().await {
2396 return true;
2397 }
2398
2399 tokio::time::timeout(timeout, notified).await.is_ok()
2400 }
2401
2402 /// Cancel all background tasks and wait for them to terminate.
2403 ///
2404 /// This must be awaited before dropping the engine when the caller needs
2405 /// the `Arc<ChunkStore>` references held by background tasks to be
2406 /// released (e.g. before reopening the same store).
2407 ///
2408 /// When this returns, no engine-spawned task still holds
2409 /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no blocking storage operation
2410 /// (read or write, against either the chunk store or the paid-list LMDB
2411 /// environment) is still running. Engine tasks race their work against
2412 /// the shutdown token; a dropped future may leave a `spawn_blocking`
2413 /// operation running detached, so this method additionally waits
2414 /// for both storage layers to go quiescent before returning.
2415 pub async fn shutdown(&mut self) {
2416 self.shutdown.cancel();
2417 for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2418 match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2419 Ok(Ok(())) => {}
2420 Ok(Err(e)) if e.is_cancelled() => {}
2421 Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2422 Err(_) => {
2423 warn!(
2424 "Replication task {i} did not stop within {}s, aborting",
2425 SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2426 );
2427 handle.abort();
2428 // `abort` only requests cancellation. Await the handle so
2429 // synchronous sections finish and the task drops every
2430 // storage/P2P clone before we claim producer quiescence.
2431 match handle.await {
2432 Ok(()) => {}
2433 Err(e) if e.is_cancelled() => {}
2434 Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2435 }
2436 }
2437 }
2438 }
2439
2440 // Close the responder worker pools. Detached tasks still queued for a
2441 // worker take the `Err` arm of `acquire_owned()` and exit immediately
2442 // rather than waiting for a slot that will never free up — without
2443 // this, work admitted just before shutdown would queue behind the last
2444 // in-flight batch and hold the drain below open for its full duration.
2445 self.fresh_offer_worker_semaphore.close();
2446 self.paid_notify_worker_semaphore.close();
2447 self.fetch_responder_worker_semaphore.close();
2448 self.verification_responder_worker_semaphore.close();
2449 self.neighbor_sync_responder_worker_semaphore.close();
2450
2451 // All producers have stopped, so close and drain their detached work.
2452 // A started storage operation must run to completion: dropping an async
2453 // waiter does not cancel `spawn_blocking`, and would let shutdown return
2454 // while a blocking storage operation is still running.
2455 //
2456 // Deliberately unbounded: every worker has to release its
2457 // `Arc<ChunkStore>` before the caller may reopen the store, whose lock
2458 // admits one process at a time, and a timeout here could return with one
2459 // still held.
2460 // What makes that safe is that every detached task is now guaranteed to
2461 // finish — the pools above are closed, stale work is shed at dequeue,
2462 // and the one genuinely unbounded await (payment verification) races
2463 // `self.shutdown` via `verify_payment_until_shutdown`.
2464 self.detached_task_tracker.close();
2465 self.detached_task_tracker.wait().await;
2466
2467 // Every producer is gone, but a select! racing the shutdown token may
2468 // have dropped a future while it awaited a storage `spawn_blocking` op
2469 // (fetch `storage.put`, prune `storage.delete` /
2470 // `paid_list.remove_batch`, verification `paid_list.insert`). The
2471 // detached blocking closure owns a cloned `Env`; wait for both
2472 // environments to go quiescent — bounded by one in-flight transaction
2473 // per op — so the caller may reopen them.
2474 self.storage.wait_idle().await;
2475 self.paid_list.wait_idle().await;
2476 }
2477
2478 /// Trigger an early neighbor sync round.
2479 ///
2480 /// Useful after topology changes (new nodes joining, network heal after
2481 /// partition) when the caller wants replication to converge faster than
2482 /// the regular 10-20 minute cadence.
2483 pub fn trigger_neighbor_sync(&self) {
2484 self.sync_trigger.notify_one();
2485 }
2486
2487 /// Execute fresh replication for a newly stored record: announce it, then
2488 /// send its offers and schedule the delayed possession check for the
2489 /// responsible close-group peers (ADR-0003), as the PUT path does.
2490 ///
2491 /// Unlike the PUT path, this waits for a pending-offer permit before
2492 /// returning, and it offers the caller's bytes rather than reading them
2493 /// back from storage.
2494 pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2495 fresh::announce_paid_write(
2496 key,
2497 proof_of_payment,
2498 &self.paid_list,
2499 &self.p2p_node,
2500 &self.config,
2501 )
2502 .await;
2503 // Never closed, so this cannot fail; the arm keeps the call panic-free.
2504 let Ok(pending_offer) = Arc::clone(&self.pending_offer_semaphore)
2505 .acquire_owned()
2506 .await
2507 else {
2508 return;
2509 };
2510 fresh::send_fresh_offers(
2511 &self.fresh_offer_context(),
2512 key,
2513 data.to_vec(),
2514 proof_of_payment.to_vec(),
2515 pending_offer,
2516 )
2517 .await;
2518 }
2519
2520 /// Handles the offer dispatcher and the direct entry point share.
2521 fn fresh_offer_context(&self) -> fresh::FreshOfferContext {
2522 fresh::FreshOfferContext {
2523 p2p_node: Arc::clone(&self.p2p_node),
2524 config: Arc::clone(&self.config),
2525 send_semaphore: Arc::clone(&self.send_semaphore),
2526 possession_check_tx: self.possession_check_tx.clone(),
2527 dispatched: Arc::clone(&self.fresh_offers_dispatched),
2528 }
2529 }
2530
2531 // =======================================================================
2532 // Background task launchers
2533 // =======================================================================
2534
2535 /// Spawn fresh replication's two stages, joined by an unbounded FIFO of
2536 /// key + proof events: the drainer, which announces every write at arrival
2537 /// rate, and the offer dispatcher, the only permit-gated stage.
2538 fn start_fresh_replication(&mut self) {
2539 let Some(writes) = self.fresh_write_rx.take() else {
2540 return;
2541 };
2542 let (offer_tx, offer_rx) = mpsc::unbounded_channel();
2543 self.start_fresh_write_drainer(writes, offer_tx.clone());
2544 self.start_fresh_offer_dispatcher(offer_rx, offer_tx);
2545 }
2546
2547 /// Spawn a task that drains the fresh-write channel: it announces each
2548 /// newly-stored chunk and hands it to the offer dispatcher.
2549 fn start_fresh_write_drainer(
2550 &mut self,
2551 mut rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
2552 offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2553 ) {
2554 let p2p = Arc::clone(&self.p2p_node);
2555 let paid_list = Arc::clone(&self.paid_list);
2556 let config = Arc::clone(&self.config);
2557 let shutdown = self.shutdown.clone();
2558
2559 let handle = tokio::spawn(async move {
2560 loop {
2561 let event = tokio::select! {
2562 () = shutdown.cancelled() => break,
2563 event = rx.recv() => {
2564 let Some(event) = event else { break };
2565 event
2566 }
2567 };
2568 // Stage one never waits for chunk back-pressure: the paid-list
2569 // entry and PaidNotify are what let peers repair the key later,
2570 // so every queued write gets them at arrival rate.
2571 fresh::announce_paid_write(
2572 &event.key,
2573 &event.payment_proof,
2574 &paid_list,
2575 &p2p,
2576 &config,
2577 )
2578 .await;
2579 if offer_tx
2580 .send(fresh::FreshOfferEvent {
2581 key: event.key,
2582 payment_proof: event.payment_proof,
2583 read_attempts: 0,
2584 })
2585 .is_err()
2586 {
2587 break;
2588 }
2589 }
2590 debug!("Fresh-write drainer shut down");
2591 });
2592 self.task_handles.push(handle);
2593 }
2594
2595 /// Spawn the fresh-offer dispatcher: the only stage of fresh replication
2596 /// that waits for a pending-offer permit.
2597 ///
2598 /// For each forwarded write it acquires a permit, reads the chunk back
2599 /// from storage and dispatches the offers. A missing chunk is skipped; a
2600 /// failed read is retried up to `MAX_FRESH_READ_ATTEMPTS` times, backing
2601 /// off over about a minute with the permit released in between, so a
2602 /// transient I/O fault does not lose the write's replication. The retry
2603 /// waits on its own task, never on the dispatcher.
2604 fn start_fresh_offer_dispatcher(
2605 &mut self,
2606 mut rx: mpsc::UnboundedReceiver<fresh::FreshOfferEvent>,
2607 offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2608 ) {
2609 let storage = Arc::clone(&self.storage);
2610 let pending_offer_semaphore = Arc::clone(&self.pending_offer_semaphore);
2611 let ctx = self.fresh_offer_context();
2612 let shutdown = self.shutdown.clone();
2613 let retries = self.detached_task_tracker.clone();
2614
2615 let handle = tokio::spawn(async move {
2616 loop {
2617 let event = tokio::select! {
2618 () = shutdown.cancelled() => break,
2619 event = rx.recv() => {
2620 let Some(event) = event else { break };
2621 event
2622 }
2623 };
2624 // Wait for a pending-offer permit before touching the chunk so a
2625 // send backlog holds queued events, not encoded chunk buffers.
2626 let pending_offer = tokio::select! {
2627 () = shutdown.cancelled() => break,
2628 permit = Arc::clone(&pending_offer_semaphore).acquire_owned() => {
2629 let Ok(permit) = permit else { break };
2630 permit
2631 }
2632 };
2633 let key_hex = hex::encode(event.key);
2634 // The same verified read the fetch path serves from. The bytes
2635 // were content-checked when they were stored, but they come
2636 // off disk now, possibly long after, and every receiver
2637 // charges the sender for an offer that does not hash to its
2638 // key. A chunk that fails verification is quarantined by this
2639 // read, so its retry finds it gone and skips it.
2640 let data = match storage.get(&event.key).await {
2641 Ok(Some(data)) => data,
2642 Ok(None) => {
2643 debug!("Chunk {key_hex} no longer stored, skipping fresh replication");
2644 continue;
2645 }
2646 Err(e) => {
2647 // The permit is released as this iteration ends, well
2648 // before any retry is due.
2649 let attempts = event.read_attempts + 1;
2650 if attempts >= MAX_FRESH_READ_ATTEMPTS {
2651 warn!(
2652 "Giving up fresh replication of {key_hex} after {attempts} failed reads: {e}"
2653 );
2654 continue;
2655 }
2656 // One warning per write: a store-wide fault fails the
2657 // whole backlog, once per retry.
2658 if attempts == 1 {
2659 warn!(
2660 "Failed to read chunk {key_hex} for fresh replication; will retry: {e}"
2661 );
2662 } else {
2663 debug!(
2664 "Failed to read chunk {key_hex} for fresh replication (attempt {attempts}): {e}"
2665 );
2666 }
2667 // Wait on a task of its own: a read fault is often
2668 // shared (exhausted descriptors), and sleeping here
2669 // would hold every healthy write queued behind this
2670 // one for the whole delay, once per failed read. The
2671 // delay grows, so a store-wide fault spends a write's
2672 // attempts over about a minute rather than seconds.
2673 let retry_tx = offer_tx.clone();
2674 let retry_shutdown = shutdown.clone();
2675 let delay = fresh_read_retry_delay(attempts);
2676 retries.spawn(async move {
2677 tokio::select! {
2678 () = retry_shutdown.cancelled() => {}
2679 () = tokio::time::sleep(delay) => {
2680 let _ = retry_tx.send(fresh::FreshOfferEvent {
2681 read_attempts: attempts,
2682 ..event
2683 });
2684 }
2685 }
2686 });
2687 continue;
2688 }
2689 };
2690 fresh::send_fresh_offers(
2691 &ctx,
2692 &event.key,
2693 data,
2694 event.payment_proof,
2695 pending_offer,
2696 )
2697 .await;
2698 }
2699 debug!("Fresh-offer dispatcher shut down");
2700 });
2701 self.task_handles.push(handle);
2702 }
2703
2704 /// Spawn the possession-check scheduler (ADR-0003).
2705 ///
2706 /// Drains scheduled possession-check events and, for each, waits a
2707 /// randomised 5-15 minute settle delay before probing every responsible
2708 /// peer for actual possession. A peer that fails to prove possession or does
2709 /// not answer is penalised at `AuditChallenge` severity.
2710 fn start_possession_check_scheduler(&mut self) {
2711 let Some(mut rx) = self.possession_check_rx.take() else {
2712 return;
2713 };
2714 let p2p = Arc::clone(&self.p2p_node);
2715 let storage = Arc::clone(&self.storage);
2716 let config = Arc::clone(&self.config);
2717 let sync_state = Arc::clone(&self.sync_state);
2718 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2719 let shutdown = self.shutdown.clone();
2720 let detached_task_tracker = self.detached_task_tracker.clone();
2721
2722 let handle = tokio::spawn(async move {
2723 loop {
2724 tokio::select! {
2725 () = shutdown.cancelled() => break,
2726 event = rx.recv() => {
2727 let Some(event) = event else { break };
2728 // Spawn a per-chunk delayed check so the drain loop
2729 // keeps pace with the write rate. Each check sleeps the
2730 // randomised settle delay, then probes every peer.
2731 let p2p = Arc::clone(&p2p);
2732 let storage = Arc::clone(&storage);
2733 let config = Arc::clone(&config);
2734 let sync_state = Arc::clone(&sync_state);
2735 let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2736 let shutdown = shutdown.clone();
2737 let delay_min = config.possession_check_delay_min;
2738 let delay_max = config.possession_check_delay_max;
2739 detached_task_tracker.spawn(async move {
2740 let delay = possession::random_delay(delay_min, delay_max);
2741 // Race shutdown against the whole settle-then-probe
2742 // sequence, not just the sleep. Once a check starts it
2743 // may park on the per-target audit coordinator, which
2744 // has no deadline of its own: with the settle delay
2745 // inside the branch BODY the select is already resolved,
2746 // so those waiters would drain only at the probe timeout
2747 // (roughly `queued / per-target-limit` probes deep) while
2748 // `detached_task_tracker.wait()` — deliberately unbounded
2749 // for the storage contract — held shutdown open.
2750 //
2751 // Dropping this future mid-probe is safe and is the same
2752 // shape the neighbor-sync round uses: a parked coordinator
2753 // acquire releases its counted reference via
2754 // `ReferenceGuard`, and a dropped storage `spawn_blocking` is
2755 // covered by the storage-quiescence wait in `shutdown`.
2756 tokio::select! {
2757 () = shutdown.cancelled() => {}
2758 () = async {
2759 tokio::time::sleep(delay).await;
2760 possession::run_possession_check(
2761 event.key,
2762 event.peers,
2763 &p2p,
2764 &storage,
2765 &config,
2766 &sync_state,
2767 &audit_challenge_coordinator,
2768 &shutdown,
2769 )
2770 .await;
2771 } => {}
2772 }
2773 });
2774 }
2775 }
2776 }
2777 debug!("Possession-check scheduler shut down");
2778 });
2779 self.task_handles.push(handle);
2780 }
2781
2782 /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2783 /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2784 /// as the gossip path, under the same per-peer cooldown and concurrency
2785 /// caps, but with the probability lottery BYPASSED (the lottery governs
2786 /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2787 /// deterministic first audit; a peer minting fresh pins faster than the
2788 /// cooldown forfeits the older ones' coverage, never the newest's (the
2789 /// channel surfaces newest pins as they are monetized).
2790 #[allow(clippy::too_many_lines)]
2791 fn start_first_audit_drainer(&mut self) {
2792 let Some(mut rx) = self.monetized_pin_rx.take() else {
2793 return;
2794 };
2795 let gossip_audit = GossipAuditTrigger {
2796 p2p_node: Arc::clone(&self.p2p_node),
2797 config: Arc::clone(&self.config),
2798 recent_provers: Arc::clone(&self.recent_provers),
2799 sync_state: Arc::clone(&self.sync_state),
2800 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2801 detached_task_tracker: self.detached_task_tracker.clone(),
2802 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2803 };
2804 let shutdown = self.shutdown.clone();
2805 let observability = Arc::clone(&self.first_audit_observability);
2806 let self_peer = *self.p2p_node.peer_id();
2807
2808 let handle = tokio::spawn(async move {
2809 // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2810 // scheduler. Payments only NOMINATE pins; the token bucket launches
2811 // them at a fixed per-node rate, and durable suppression is stamped
2812 // only at PROMOTION (after an authoritative post-jitter answerability
2813 // + cooldown check), so a cancelled reservation leaves nothing behind.
2814 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2815 // Periodic retry tick so budget/cooldown-deferred pins get retried
2816 // even when no new nomination arrives. `Skip` collapses a backlog.
2817 let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2818 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2819 let mut last_summary = Instant::now();
2820 loop {
2821 // The reservation's jitter deadline is a wake source: if a
2822 // reservation is outstanding, sleep until it is due; otherwise
2823 // a far-future deadline effectively disables that arm and only
2824 // shutdown/rx/tick wake the loop. Recreated each iteration so a
2825 // newly reserved (earlier) deadline is honoured next turn.
2826 let promotion_due = scheduler
2827 .reserved_ready_at()
2828 .unwrap_or_else(first_audit_far_future);
2829 tokio::select! {
2830 () = shutdown.cancelled() => break,
2831 event = rx.recv() => match event {
2832 Some(e) => {
2833 observability.received.fetch_add(1, Ordering::Relaxed);
2834 // Pre-overflow reservation opportunity: before an
2835 // arrival may displace a DIFFERENT peer, let the
2836 // queue launch — a successful reservation frees the
2837 // slot without eviction. One reservation can be
2838 // outstanding at a time, so this consumes at most
2839 // one slot per jitter window; arrivals beyond it
2840 // fall through to random displacement (ADR-0004
2841 // Amendment 4).
2842 if scheduler.would_displace(&e) {
2843 open_first_audit_reservation(
2844 &mut scheduler,
2845 &gossip_audit.cooldown,
2846 &observability,
2847 )
2848 .await;
2849 }
2850 scheduler.enqueue(e, &observability);
2851 // Drain a bounded burst so a flood cannot starve the
2852 // launch phase.
2853 let mut drained = 1usize;
2854 while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2855 match rx.try_recv() {
2856 Ok(e) => {
2857 observability.received.fetch_add(1, Ordering::Relaxed);
2858 if scheduler.would_displace(&e) {
2859 open_first_audit_reservation(
2860 &mut scheduler,
2861 &gossip_audit.cooldown,
2862 &observability,
2863 )
2864 .await;
2865 }
2866 scheduler.enqueue(e, &observability);
2867 drained += 1;
2868 }
2869 Err(_) => break,
2870 }
2871 }
2872 }
2873 None => break,
2874 },
2875 _ = tick.tick() => {}
2876 () = tokio::time::sleep_until(promotion_due.into()) => {}
2877 }
2878
2879 // 1) Promote a due reservation. Resolved after EVERY wake (not
2880 // only when the timer arm wins) so a continuously-ready `rx`
2881 // cannot indefinitely delay a due promotion. The authoritative
2882 // answerability + cooldown check-and-stamp happens here under
2883 // the shared cooldown write lock, immediately before the send.
2884 if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2885 let promoted = {
2886 let mut cooldown = gossip_audit.cooldown.write().await;
2887 scheduler.resolve(
2888 reservation,
2889 SystemTime::now(),
2890 Instant::now(),
2891 &mut cooldown,
2892 &observability,
2893 )
2894 };
2895 if let Some((event, inflight_slot)) = promoted {
2896 debug!(
2897 "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2898 event.peer, hex::encode(event.pin), event.key_count,
2899 observability.inflight.load(Ordering::Relaxed)
2900 );
2901 let trigger = gossip_audit.clone();
2902 let audit_observability = Arc::clone(&observability);
2903 // Track the launch so `shutdown()`'s detached drain
2904 // covers it. This task outlives the drainer loop that
2905 // spawned it — the loop breaks on the shutdown token
2906 // while the audit is still awaiting its response — so a
2907 // bare spawn would let an in-flight subtree audit keep
2908 // running, and keep its `Arc<P2PNode>`, past the point
2909 // `shutdown()` claims every engine task has stopped.
2910 let tracker = trigger.detached_task_tracker.clone();
2911 tracker.spawn(async move {
2912 // The jitter already elapsed as the reservation's
2913 // timer; the slot is held for the audit's duration
2914 // and released on drop (panic-safe).
2915 let inflight_slot = inflight_slot;
2916 let started = Instant::now();
2917 let credit = storage_commitment_audit::AuditCredit {
2918 recent_provers: &trigger.recent_provers,
2919 };
2920 let result = storage_commitment_audit::run_subtree_audit(
2921 &trigger.p2p_node,
2922 &trigger.config,
2923 &event.peer,
2924 event.pin,
2925 event.key_count,
2926 Some(&credit),
2927 )
2928 .await;
2929 let outcome = first_audit_terminal_outcome(&result);
2930 match outcome {
2931 FirstAuditTerminalOutcome::Passed => {
2932 audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2933 }
2934 FirstAuditTerminalOutcome::Timeout => {
2935 audit_observability
2936 .timed_out
2937 .fetch_add(1, Ordering::Relaxed);
2938 }
2939 FirstAuditTerminalOutcome::Failed => {
2940 audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2941 }
2942 FirstAuditTerminalOutcome::BootstrapClaim => {
2943 audit_observability
2944 .bootstrap_claims
2945 .fetch_add(1, Ordering::Relaxed);
2946 }
2947 FirstAuditTerminalOutcome::Idle => {
2948 audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2949 }
2950 FirstAuditTerminalOutcome::InsufficientKeys => {
2951 audit_observability
2952 .insufficient_keys
2953 .fetch_add(1, Ordering::Relaxed);
2954 }
2955 }
2956 drop(inflight_slot);
2957 debug!(
2958 "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2959 outcome.as_str(),
2960 event.peer, hex::encode(event.pin), event.key_count,
2961 started.elapsed().as_millis(),
2962 audit_observability.inflight.load(Ordering::Relaxed)
2963 );
2964 handle_subtree_audit_result(
2965 &result,
2966 &trigger.p2p_node,
2967 &trigger.sync_state,
2968 &trigger.recent_provers,
2969 &trigger.config,
2970 )
2971 .await;
2972 });
2973 }
2974 }
2975
2976 // 2) Open the single reservation from the pending queue if none
2977 // is outstanding (read-only cooldown snapshot; the
2978 // authoritative stamp is at promotion). Serializing
2979 // reservations preserves per-launch lane alternation and keeps
2980 // at most one jitter timer live.
2981 open_first_audit_reservation(
2982 &mut scheduler,
2983 &gossip_audit.cooldown,
2984 &observability,
2985 )
2986 .await;
2987
2988 if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2989 // Token-independent hygiene: collect entries that aged past
2990 // the answerability horizon while the budget gate kept the
2991 // reserve scan from running, so the summary below reports
2992 // only live work.
2993 let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2994 if swept > 0 {
2995 debug!(
2996 "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2997 scheduler.pending_len()
2998 );
2999 }
3000 info!(
3001 "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={}",
3002 FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
3003 observability.received.load(Ordering::Relaxed),
3004 observability.queued.load(Ordering::Relaxed),
3005 observability.coalesced.load(Ordering::Relaxed),
3006 observability.suppressed_lower.load(Ordering::Relaxed),
3007 observability.duplicates.load(Ordering::Relaxed),
3008 observability.capacity_evicted.load(Ordering::Relaxed),
3009 observability.self_target_skipped.load(Ordering::Relaxed),
3010 observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
3011 observability.rate_deferred_attempts.load(Ordering::Relaxed),
3012 observability.window_deduped.load(Ordering::Relaxed),
3013 observability.launched.load(Ordering::Relaxed),
3014 observability.passed.load(Ordering::Relaxed),
3015 observability.timed_out.load(Ordering::Relaxed),
3016 observability.failed.load(Ordering::Relaxed),
3017 observability.bootstrap_claims.load(Ordering::Relaxed),
3018 observability.idle.load(Ordering::Relaxed),
3019 observability.insufficient_keys.load(Ordering::Relaxed),
3020 observability.outside_answerability_window.load(Ordering::Relaxed),
3021 scheduler.pending_len(),
3022 FIRST_AUDIT_PENDING_CAP,
3023 u8::from(scheduler.has_reservation()),
3024 scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
3025 observability.inflight.load(Ordering::Relaxed),
3026 scheduler.tokens(),
3027 );
3028 last_summary = Instant::now();
3029 }
3030 }
3031 debug!("First-audit drainer shut down");
3032 });
3033 self.task_handles.push(handle);
3034 }
3035
3036 #[allow(clippy::too_many_lines)]
3037 fn start_message_handler(&mut self) {
3038 let mut p2p_events = self.p2p_node.subscribe_events();
3039 let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
3040 let p2p = Arc::clone(&self.p2p_node);
3041 let storage = Arc::clone(&self.storage);
3042 let paid_list = Arc::clone(&self.paid_list);
3043 let payment_verifier = Arc::clone(&self.payment_verifier);
3044 let queues = Arc::clone(&self.queues);
3045 let config = Arc::clone(&self.config);
3046 let shutdown = self.shutdown.clone();
3047 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3048 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3049 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3050 let sync_history = Arc::clone(&self.sync_history);
3051 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3052 let repair_proofs = Arc::clone(&self.repair_proofs);
3053 let sync_trigger = Arc::clone(&self.sync_trigger);
3054 let my_commitment_state = Arc::clone(&self.commitment_state);
3055 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3056 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3057 let recent_provers = Arc::clone(&self.recent_provers);
3058 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3059 let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
3060 let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
3061 let sync_state = Arc::clone(&self.sync_state);
3062 let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
3063 let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
3064 let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
3065 let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
3066 let fetch_responder_admission_semaphore =
3067 Arc::clone(&self.fetch_responder_admission_semaphore);
3068 let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
3069 let verification_responder_worker_semaphore =
3070 Arc::clone(&self.verification_responder_worker_semaphore);
3071 let verification_responder_admission_semaphore =
3072 Arc::clone(&self.verification_responder_admission_semaphore);
3073 let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
3074 let neighbor_sync_responder_worker_semaphore =
3075 Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
3076 let neighbor_sync_responder_admission_semaphore =
3077 Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
3078 let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
3079 let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
3080 let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
3081 let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
3082 let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
3083 let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
3084 let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
3085 let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
3086 let detached_task_tracker = self.detached_task_tracker.clone();
3087 let subtree_round1 = self.subtree_round1.clone();
3088
3089 // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
3090 // commitment can spawn a probabilistic, cooldown-gated subtree audit.
3091 let gossip_audit = GossipAuditTrigger {
3092 p2p_node: Arc::clone(&p2p),
3093 config: Arc::clone(&config),
3094 recent_provers: Arc::clone(&recent_provers),
3095 sync_state: Arc::clone(&sync_state),
3096 cooldown: Arc::clone(&audit_on_gossip_cooldown),
3097 detached_task_tracker: detached_task_tracker.clone(),
3098 lottery_attempts: Arc::clone(&gossip_lottery_attempts),
3099 };
3100
3101 let handler_context = ReplicationMessageHandlerContext {
3102 p2p_node: Arc::clone(&p2p),
3103 storage,
3104 paid_list,
3105 payment_verifier,
3106 queues,
3107 config: Arc::clone(&config),
3108 is_bootstrapping,
3109 bootstrap_state,
3110 sync_history,
3111 sync_cycle_epoch,
3112 repair_proofs: Arc::clone(&repair_proofs),
3113 last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
3114 ever_capable_peers,
3115 sig_verify_attempts: Arc::clone(&sig_verify_attempts),
3116 my_commitment_state,
3117 gossip_audit,
3118 audit_responder_semaphore,
3119 audit_responder_inflight,
3120 audit_responder_metrics,
3121 subtree_round1,
3122 fetch_responder_worker_semaphore,
3123 fetch_responder_admission_semaphore,
3124 fetch_responder_inflight,
3125 verification_responder_worker_semaphore,
3126 verification_responder_admission_semaphore,
3127 verification_responder_inflight,
3128 neighbor_sync_responder_worker_semaphore,
3129 neighbor_sync_responder_admission_semaphore,
3130 neighbor_sync_responder_inflight,
3131 fresh_offer_worker_semaphore,
3132 fresh_offer_admission_semaphore,
3133 fresh_offer_responder_inflight,
3134 fresh_offer_in_flight,
3135 paid_notify_worker_semaphore,
3136 paid_notify_admission_semaphore,
3137 paid_notify_responder_inflight,
3138 pointers: self.pointers.clone(),
3139 shutdown: shutdown.clone(),
3140 detached_task_tracker,
3141 };
3142
3143 let (replication_tx, mut replication_rx) =
3144 mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
3145 let serial_context = handler_context.clone();
3146 let serial_shutdown = shutdown.clone();
3147 let serial_handle = tokio::spawn(async move {
3148 loop {
3149 tokio::select! {
3150 () = serial_shutdown.cancelled() => break,
3151 inbound = replication_rx.recv() => {
3152 let Some(inbound) = inbound else { break };
3153 let source = inbound.source;
3154 match handle_replication_message(
3155 &source,
3156 inbound.msg,
3157 &serial_context,
3158 inbound.received_at,
3159 inbound.rr_message_id.as_deref(),
3160 )
3161 .await
3162 {
3163 Ok(()) => {}
3164 Err(e) => {
3165 debug!("Replication message from {source} error: {e}");
3166 }
3167 }
3168 }
3169 }
3170 }
3171 debug!("Replication non-audit serial handler shut down");
3172 });
3173 self.task_handles.push(serial_handle);
3174
3175 let handle = tokio::spawn(async move {
3176 loop {
3177 tokio::select! {
3178 () = shutdown.cancelled() => break,
3179 event = p2p_events.recv() => {
3180 let event = match event {
3181 Ok(event) => event,
3182 Err(error) => match handle_replication_event_recv_error(&error) {
3183 ControlFlow::Continue(()) => continue,
3184 ControlFlow::Break(()) => break,
3185 },
3186 };
3187 let Some((source, payload, inbound_protocol, rr_message_id)) =
3188 replication_payload_from_event(event)
3189 else {
3190 continue;
3191 };
3192 let received_at = Instant::now();
3193 let msg = match ReplicationMessage::decode(&payload) {
3194 Ok(msg) => msg,
3195 Err(e) => {
3196 debug!("Replication message from {source} decode error: {e}");
3197 continue;
3198 }
3199 };
3200 if !body_matches_protocol(&msg.body, inbound_protocol) {
3201 debug!(
3202 "Dropping replication body (variant {}) on protocol \
3203 {inbound_protocol}: wrong id for its family \
3204 (cross-version or misrouted)",
3205 msg.body.variant_index()
3206 );
3207 continue;
3208 }
3209 if let Some(class) = audit_responder_class(&msg.body) {
3210 handler_context
3211 .audit_responder_metrics
3212 .record_received(source, class);
3213 }
3214 let inbound = InboundReplicationMessage {
3215 source,
3216 msg,
3217 rr_message_id,
3218 received_at,
3219 };
3220 if matches!(
3221 inbound.msg.body,
3222 ReplicationMessageBody::AuditChallenge(_)
3223 | ReplicationMessageBody::SubtreeAuditChallenge(_)
3224 | ReplicationMessageBody::SubtreeSliceChallenge(_)
3225 ) {
3226 let source = inbound.source;
3227 match handle_replication_message(
3228 &source,
3229 inbound.msg,
3230 &handler_context,
3231 inbound.received_at,
3232 inbound.rr_message_id.as_deref(),
3233 )
3234 .await
3235 {
3236 Ok(()) => {}
3237 Err(e) => {
3238 debug!("Replication message from {source} error: {e}");
3239 }
3240 }
3241 continue;
3242 }
3243 if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
3244 if dropped.audit_responder_class.is_some() {
3245 handler_context
3246 .audit_responder_metrics
3247 .record_serial_queue_drop(dropped.source);
3248 }
3249 // Every serial-lane class has protocol recovery: syncs rerun,
3250 // fetches retry, verification re-asks, and a dropped fresh
3251 // offer is refilled by neighbor sync (the possession check
3252 // penalises the absence but never re-offers). Responses are
3253 // covered by their requester's deadline/retry path. Never run
3254 // a bulk handler here: event receipt must remain non-blocking.
3255 warn!(
3256 message_class = dropped.message_class,
3257 source = %dropped.source,
3258 queue_depth = dropped.queue_depth,
3259 reason = dropped.reason.as_str(),
3260 "Replication serial-queue message dropped"
3261 );
3262 }
3263 }
3264 // Gap 4: Topology churn handling (Section 13).
3265 //
3266 // The DHT routing table emits KClosestPeersChanged when the
3267 // K-closest peer set actually changes, which is the precise
3268 // signal for triggering neighbor sync. This replaces the
3269 // previous approach of checking every PeerConnected /
3270 // PeerDisconnected event against the close group.
3271 dht_event = dht_events.recv() => {
3272 let dht_event = match dht_event {
3273 Ok(event) => event,
3274 Err(RecvError::Lagged(missed)) => {
3275 // Under heavy churn the broadcast buffer can overflow
3276 // and drop routing-table events — the moment
3277 // convergence matters most. A dropped
3278 // KClosestPeersChanged means its entrants were never
3279 // queued and its departures were never pruned, so
3280 // draining priority_order cannot recover either.
3281 // Resync from ground truth instead: snapshot the
3282 // current close-peer set, prune pending peers that
3283 // left it during the lost window (retain_sync_peers,
3284 // as the normal topology-change path does), and queue
3285 // every member. Dedup (queue_priority_peers) and
3286 // per-peer cooldown (select_next_sync_peer) drop peers
3287 // already queued or recently synced, so only genuine
3288 // entrants surface.
3289 warn!(
3290 "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3291 );
3292 let self_id = *p2p.peer_id();
3293 let neighbors = neighbor_sync::snapshot_close_neighbors(
3294 &p2p,
3295 &self_id,
3296 config.neighbor_sync_scope,
3297 )
3298 .await;
3299 let neighbor_set =
3300 neighbors.iter().copied().collect::<HashSet<_>>();
3301 let (requeued, sync_removals) = {
3302 let mut state = sync_state.write().await;
3303 let sync_removals =
3304 state.retain_sync_peers(&neighbor_set);
3305 let requeued = state.queue_priority_peers(neighbors);
3306 (requeued, sync_removals)
3307 };
3308 if sync_removals > 0 {
3309 debug!(
3310 "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3311 );
3312 }
3313 if requeued > 0 {
3314 debug!(
3315 "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3316 );
3317 sync_trigger.notify_one();
3318 }
3319 continue;
3320 }
3321 Err(RecvError::Closed) => {
3322 // A closed broadcast channel never yields again;
3323 // continuing would spin the select! loop forever.
3324 warn!(
3325 "DHT event stream closed on replication branch; stopping message handler"
3326 );
3327 break;
3328 }
3329 };
3330 match dht_event {
3331 DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3332 let old_peers = old
3333 .iter()
3334 .take(config.neighbor_sync_scope)
3335 .copied()
3336 .collect::<HashSet<_>>();
3337 let new_scoped = new
3338 .iter()
3339 .take(config.neighbor_sync_scope)
3340 .copied()
3341 .collect::<Vec<_>>();
3342 let new_peers =
3343 new_scoped.iter().copied().collect::<HashSet<_>>();
3344 let entrants = new_scoped
3345 .iter()
3346 .copied()
3347 .filter(|peer| !old_peers.contains(peer))
3348 .collect::<Vec<_>>();
3349 let entrant_count = entrants.len();
3350 let (priority_insertions, sync_removals) = {
3351 let mut state = sync_state.write().await;
3352 let sync_removals = state.retain_sync_peers(&new_peers);
3353 let priority_insertions = state.queue_priority_peers(entrants);
3354 (priority_insertions, sync_removals)
3355 };
3356 if priority_insertions > 0 {
3357 debug!(
3358 "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3359 );
3360 } else {
3361 debug!(
3362 "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3363 );
3364 }
3365 sync_trigger.notify_one();
3366 }
3367 DhtNetworkEvent::PeerRemoved { peer_id } => {
3368 sync_state.write().await.remove_peer(&peer_id);
3369 repair_proofs.write().await.remove_peer(&peer_id);
3370 if let Some(pointers) = &handler_context.pointers {
3371 pointers.forget_peer(&peer_id);
3372 }
3373 update_bootstrap_after_peer_removed(
3374 &peer_id,
3375 &handler_context.bootstrap_state,
3376 &handler_context.queues,
3377 &handler_context.is_bootstrapping,
3378 &bootstrap_complete_notify,
3379 )
3380 .await;
3381 // v12: drop the commitment bytes and the
3382 // recent-prover credit so a churn / sybil
3383 // attacker cannot leave behind one
3384 // StorageCommitment per identity in
3385 // `last_commitment_by_peer`. Also drop the
3386 // sig-verify rate-limit timestamp.
3387 last_commitment_by_peer.write().await.remove(&peer_id);
3388 recent_provers.write().await.forget_peer(&peer_id);
3389 sig_verify_attempts.write().await.remove(&peer_id);
3390 // Same for the gossip-audit cooldown (ADR-0002)
3391 // and the lottery-attempt window.
3392 audit_on_gossip_cooldown.write().await.remove(&peer_id);
3393 gossip_lottery_attempts.write().await.remove(&peer_id);
3394 // The sticky `commitment_capable` flag is
3395 // preserved orthogonally via
3396 // `ever_capable_peers` — even after this
3397 // removal, a re-joining peer continues to
3398 // be treated as v12-capable rather than
3399 // legacy (§3 shield).
3400 }
3401 _ => {}
3402 }
3403 }
3404 }
3405 }
3406 debug!("Replication message handler shut down");
3407 });
3408 self.task_handles.push(handle);
3409 }
3410
3411 fn start_neighbor_sync_loop(&mut self) {
3412 let pointers = self.pointers.clone();
3413 let p2p = Arc::clone(&self.p2p_node);
3414 let storage = Arc::clone(&self.storage);
3415 let paid_list = Arc::clone(&self.paid_list);
3416 let queues = Arc::clone(&self.queues);
3417 let config = Arc::clone(&self.config);
3418 let shutdown = self.shutdown.clone();
3419 let sync_state = Arc::clone(&self.sync_state);
3420 let sync_history = Arc::clone(&self.sync_history);
3421 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3422 let repair_proofs = Arc::clone(&self.repair_proofs);
3423 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3424 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3425 let sync_trigger = Arc::clone(&self.sync_trigger);
3426 let commitment_state = Arc::clone(&self.commitment_state);
3427 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3428 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3429 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3430 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3431 let detached_task_tracker = self.detached_task_tracker.clone();
3432 // ADR-0028: one disk-pressure state per node, shared by the chunk and
3433 // pointer prune passes, which only this loop runs.
3434 let disk_pressure = retention::DiskPressure::default();
3435 // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3436 // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3437 // here too so a peer that only ever answers — never initiates sync —
3438 // is still audited; otherwise it could fully evade auditing.
3439 let gossip_audit = GossipAuditTrigger {
3440 p2p_node: Arc::clone(&p2p),
3441 config: Arc::clone(&config),
3442 recent_provers: Arc::clone(&self.recent_provers),
3443 sync_state: Arc::clone(&sync_state),
3444 cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3445 detached_task_tracker,
3446 lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3447 };
3448
3449 let handle = tokio::spawn(async move {
3450 loop {
3451 // Park for the periodic tick or an explicit trigger ONLY when no
3452 // priority (topology-change) peers are queued. `sync_trigger` is a
3453 // coalescing `Notify`, so a churn burst that queues many entrants
3454 // produces a single wakeup; parking after draining one batch would
3455 // leave the rest waiting up to a full periodic tick. `priority_order`
3456 // is the durable record of pending work, so drain it back-to-back —
3457 // each round removes the peers it selects (`select_next_sync_peer`),
3458 // so the drain terminates once the queue empties.
3459 if !sync_state.read().await.has_priority_peers() {
3460 let interval = config.random_neighbor_sync_interval();
3461 tokio::select! {
3462 () = shutdown.cancelled() => break,
3463 () = tokio::time::sleep(interval) => {}
3464 () = sync_trigger.notified() => {
3465 debug!("Neighbor sync triggered by topology change");
3466 }
3467 }
3468 }
3469 // Wrap the sync round in a select so shutdown cancels
3470 // in-progress network operations rather than waiting for
3471 // the full round to complete.
3472 tokio::select! {
3473 () = shutdown.cancelled() => break,
3474 () = run_neighbor_sync_round(
3475 &p2p,
3476 &storage,
3477 &paid_list,
3478 &queues,
3479 &config,
3480 &sync_state,
3481 &sync_history,
3482 &sync_cycle_epoch,
3483 &repair_proofs,
3484 &is_bootstrapping,
3485 &bootstrap_state,
3486 &commitment_state,
3487 &last_commitment_by_peer,
3488 &ever_capable_peers,
3489 &sig_verify_attempts,
3490 &audit_challenge_coordinator,
3491 &gossip_audit,
3492 &disk_pressure,
3493 pointers.as_ref(),
3494 ) => {}
3495 }
3496 }
3497 debug!("Neighbor sync loop shut down");
3498 });
3499 self.task_handles.push(handle);
3500 }
3501
3502 fn start_self_lookup_loop(&mut self) {
3503 let p2p = Arc::clone(&self.p2p_node);
3504 let config = Arc::clone(&self.config);
3505 let shutdown = self.shutdown.clone();
3506
3507 let handle = tokio::spawn(async move {
3508 loop {
3509 let interval = config.random_self_lookup_interval();
3510 tokio::select! {
3511 () = shutdown.cancelled() => break,
3512 () = tokio::time::sleep(interval) => {
3513 if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3514 debug!("Self-lookup failed: {e}");
3515 }
3516 }
3517 }
3518 }
3519 debug!("Self-lookup loop shut down");
3520 });
3521 self.task_handles.push(handle);
3522 }
3523
3524 /// Spawn the one task that takes chunks audits found rotted out of service.
3525 ///
3526 /// One, so that the rechecks hold at most one blocking thread between them however
3527 /// many audits report rot; see [`ChunkStore::run_corrupt_rechecks`]. Tracked with
3528 /// the detached storage work rather than the engine's loops, because shutdown aborts
3529 /// a loop that outlasts its drain timeout and a recheck must not be dropped part-way.
3530 /// The worker itself stops at the shutdown token, between rechecks.
3531 fn start_corrupt_recheck_worker(&self) {
3532 let storage = Arc::clone(&self.storage);
3533 let shutdown = self.shutdown.clone();
3534 self.detached_task_tracker.spawn(async move {
3535 storage.run_corrupt_rechecks(&shutdown).await;
3536 debug!("Corrupt-chunk recheck worker shut down");
3537 });
3538 }
3539
3540 /// Periodic responsible-chunk audit loop (audit #2): every
3541 /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3542 /// eligible close peer for the chunks it *should* be storing (by
3543 /// responsibility and prior repair hint), independent of the gossip-triggered
3544 /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3545 /// immediately and periodically thereafter.
3546 fn start_audit_loop(&mut self) {
3547 let p2p = Arc::clone(&self.p2p_node);
3548 let storage = Arc::clone(&self.storage);
3549 let paid_list = Arc::clone(&self.paid_list);
3550 let config = Arc::clone(&self.config);
3551 let shutdown = self.shutdown.clone();
3552 let sync_history = Arc::clone(&self.sync_history);
3553 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3554 let repair_proofs = Arc::clone(&self.repair_proofs);
3555 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3556 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3557 let sync_state = Arc::clone(&self.sync_state);
3558 let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3559
3560 let handle = tokio::spawn(async move {
3561 // Invariant 19: wait for bootstrap to drain before starting audits.
3562 loop {
3563 tokio::select! {
3564 () = shutdown.cancelled() => return,
3565 () = tokio::time::sleep(
3566 std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3567 ) => {
3568 if bootstrap_state.read().await.is_drained() {
3569 break;
3570 }
3571 }
3572 }
3573 }
3574
3575 // Run one audit tick immediately after bootstrap drain.
3576 {
3577 let bootstrapping = *is_bootstrapping.read().await;
3578 let result = {
3579 let history = sync_history.read().await;
3580 let current_sync_epoch = *sync_cycle_epoch.read().await;
3581 audit::audit_tick_with_repair_proofs(
3582 &p2p,
3583 &storage,
3584 &paid_list,
3585 &config,
3586 &history,
3587 &repair_proofs,
3588 &audit_challenge_coordinator,
3589 current_sync_epoch,
3590 bootstrapping,
3591 )
3592 .await
3593 };
3594 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3595 }
3596
3597 // Then run periodically.
3598 loop {
3599 let interval = config.random_audit_tick_interval();
3600 tokio::select! {
3601 () = shutdown.cancelled() => break,
3602 () = tokio::time::sleep(interval) => {
3603 let bootstrapping = *is_bootstrapping.read().await;
3604 let result = {
3605 let history = sync_history.read().await;
3606 let current_sync_epoch = *sync_cycle_epoch.read().await;
3607 audit::audit_tick_with_repair_proofs(
3608 &p2p,
3609 &storage,
3610 &paid_list,
3611 &config,
3612 &history,
3613 &repair_proofs,
3614 &audit_challenge_coordinator,
3615 current_sync_epoch,
3616 bootstrapping,
3617 )
3618 .await
3619 };
3620 handle_audit_result(&result, &p2p, &sync_state, &config).await;
3621 }
3622 }
3623 }
3624 debug!("Audit loop shut down");
3625 });
3626 self.task_handles.push(handle);
3627 }
3628
3629 /// Periodically rebuild + sign + rotate the responder's storage
3630 /// commitment.
3631 ///
3632 /// Phase 3 of the v12 storage-bound audit. Once per
3633 /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3634 /// current key set, builds a Merkle tree (for content-addressed
3635 /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3636 /// the root with the node's `MlDsaSecretKey`, and rotates the result
3637 /// into `commitment_state`. Old `previous` slot is dropped by the
3638 /// rotate (per `ResponderCommitmentState::rotate`).
3639 ///
3640 /// Skips if the key set is empty (no commitment to make) — the
3641 /// auditor side falls back to the legacy plain-digest path for
3642 /// peers that have never gossiped a commitment.
3643 fn start_commitment_rotation_loop(&mut self) {
3644 let storage = Arc::clone(&self.storage);
3645 let identity = Arc::clone(&self.identity);
3646 let commitment_state = Arc::clone(&self.commitment_state);
3647 let shutdown = self.shutdown.clone();
3648 let p2p = Arc::clone(&self.p2p_node);
3649 let config = Arc::clone(&self.config);
3650 let sync_trigger = Arc::clone(&self.sync_trigger);
3651 let recent_provers = Arc::clone(&self.recent_provers);
3652 let pointer_store = self.pointers.as_ref().map(|p| p.store().clone());
3653
3654 let handle = tokio::spawn(async move {
3655 // Build the first commitment immediately on startup so a
3656 // restarted node can answer commitment-bound audits right
3657 // away — otherwise current() stays None for a full rotation
3658 // interval and audits silently fall back to legacy.
3659 //
3660 // After the first build, trigger an immediate neighbor-sync
3661 // round so the new commitment gossips out within seconds.
3662 // Without this, after a restart remote auditors keep pinning
3663 // the pre-restart (rotated-away) hash until their normal
3664 // sync cadence elapses — up to 1 h in the worst case,
3665 // during which time commitment-bound audits hit "unknown
3666 // commitment hash" -> Idle no-ops.
3667 // ML-DSA signatures are randomized so we cannot reproduce
3668 // the pre-restart hash; the only honest path to recovery
3669 // is fast re-gossip.
3670 // ADR-0004 A1: retention was reloaded in `new()` (before any task
3671 // spawned), so this initial rebuild no-ops when the key set is
3672 // unchanged — preserving the reloaded current pin; otherwise the
3673 // reloaded roots stay answerable as retained slots until their gossip
3674 // TTL lapses. Persistence is handled by the retention-persist loop.
3675 if let Err(e) = rebuild_and_rotate_commitment(
3676 &storage,
3677 pointer_store.as_ref(),
3678 &identity,
3679 &commitment_state,
3680 &p2p,
3681 &config,
3682 )
3683 .await
3684 {
3685 warn!("Initial commitment build failed: {e}");
3686 } else {
3687 sync_trigger.notify_one();
3688 }
3689 loop {
3690 tokio::select! {
3691 () = shutdown.cancelled() => break,
3692 () = tokio::time::sleep(
3693 std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3694 ) => {
3695 if let Err(e) = rebuild_and_rotate_commitment(
3696 &storage,
3697 pointer_store.as_ref(),
3698 &identity,
3699 &commitment_state,
3700 &p2p,
3701 &config,
3702 ).await {
3703 warn!("Commitment rotation failed: {e}");
3704 }
3705 // Piggyback a sweep of expired recent_provers
3706 // entries on the rotation tick (same cadence,
3707 // 1 h). is_credited_holder already honours the
3708 // TTL on read, but the sweep reclaims memory
3709 // for entries we'll never re-read.
3710 let dropped = recent_provers.write().await.sweep_expired(
3711 std::time::Instant::now()
3712 );
3713 if dropped > 0 {
3714 debug!("recent_provers: swept {dropped} expired entries");
3715 }
3716 }
3717 }
3718 }
3719 debug!("Commitment rotation loop shut down");
3720 });
3721 self.task_handles.push(handle);
3722 }
3723
3724 /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3725 /// (write-on-change) so answerability — including gossip-stamp refreshes and
3726 /// rotations — survives a restart. Flushes once immediately, then every
3727 /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3728 fn start_retention_persist_loop(&mut self) {
3729 let commitment_state = Arc::clone(&self.commitment_state);
3730 let retention_path = self.retention_path.clone();
3731 let shutdown = self.shutdown.clone();
3732 let handle = tokio::spawn(async move {
3733 let mut last: Option<Vec<u8>> = None;
3734 persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3735 loop {
3736 tokio::select! {
3737 () = shutdown.cancelled() => {
3738 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3739 .await;
3740 break;
3741 }
3742 () = tokio::time::sleep(std::time::Duration::from_secs(
3743 RETENTION_PERSIST_INTERVAL_SECS,
3744 )) => {
3745 persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3746 .await;
3747 }
3748 }
3749 }
3750 debug!("Commitment retention persist loop shut down");
3751 });
3752 self.task_handles.push(handle);
3753 }
3754
3755 /// Periodically emit the cumulative replication traffic summaries: the
3756 /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3757 /// (V2-684). Both read process-global counter tables maintained by the
3758 /// encode/decode and serve choke points in [`protocol`]; needs no engine
3759 /// state.
3760 fn start_traffic_summary_loop(&mut self) {
3761 let shutdown = self.shutdown.clone();
3762 let handle = tokio::spawn(async move {
3763 loop {
3764 tokio::select! {
3765 () = shutdown.cancelled() => break,
3766 () = tokio::time::sleep(std::time::Duration::from_secs(
3767 TRAFFIC_SUMMARY_INTERVAL_SECS,
3768 )) => {
3769 protocol::log_traffic_summary();
3770 protocol::log_served_peers_summary();
3771 protocol::log_audit_outcome_summary();
3772 audit_metrics::log_responder_admission_summary();
3773 // V2-834 Part D: chunk RPC, upgrade and EVM RPC attribution
3774 // ride the same cadence.
3775 crate::storage::traffic::log_chunk_rpc_traffic_summary();
3776 crate::upgrade::traffic::log_upgrade_traffic_summary();
3777 crate::payment::traffic::log_evm_rpc_summary();
3778 }
3779 }
3780 }
3781 debug!("Replication traffic summary loop shut down");
3782 });
3783 self.task_handles.push(handle);
3784 }
3785
3786 /// Periodically expose the state that gates bootstrap completion and prune
3787 /// admission. The state counts are copied before reading `is_bootstrapping`
3788 /// so this diagnostic path never nests async locks.
3789 #[cfg(feature = "logging")]
3790 fn start_bootstrap_state_snapshot_loop(&mut self) {
3791 let shutdown = self.shutdown.clone();
3792 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3793 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3794 let started_at = Instant::now();
3795 let handle = tokio::spawn(async move {
3796 loop {
3797 tokio::select! {
3798 () = shutdown.cancelled() => break,
3799 () = tokio::time::sleep(Duration::from_secs(
3800 BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3801 )) => {
3802 let (
3803 drained,
3804 pending_peer_requests,
3805 pending_keys,
3806 capacity_rejected_sources,
3807 ) = {
3808 let state = bootstrap_state.read().await;
3809 (
3810 state.drained,
3811 state.pending_peer_requests,
3812 state.pending_keys.len(),
3813 state.capacity_rejected_sources.len(),
3814 )
3815 };
3816 let bootstrapping = *is_bootstrapping.read().await;
3817 let snapshot_state = if drained && !bootstrapping {
3818 "healthy"
3819 } else if drained {
3820 "drained_waiting_for_bootstrap_flag"
3821 } else {
3822 "pending"
3823 };
3824 info!(
3825 drained,
3826 pending_peer_requests,
3827 pending_keys,
3828 capacity_rejected_sources,
3829 is_bootstrapping = bootstrapping,
3830 snapshot_state,
3831 uptime_secs = started_at.elapsed().as_secs(),
3832 "Replication bootstrap state snapshot"
3833 );
3834 if drained && !bootstrapping {
3835 info!(
3836 "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3837 );
3838 break;
3839 }
3840 }
3841 }
3842 }
3843 debug!("Bootstrap state snapshot loop shut down");
3844 });
3845 self.task_handles.push(handle);
3846 }
3847
3848 /// Periodically rank remote peers using the shared audit responder pool and
3849 /// report handler-only versus end-to-end latency. Windowed values make a
3850 /// burst visible even after a long-running node has accumulated traffic.
3851 #[cfg(feature = "logging")]
3852 fn start_audit_responder_summary_loop(&mut self) {
3853 let shutdown = self.shutdown.clone();
3854 let metrics = Arc::clone(&self.audit_responder_metrics);
3855 let semaphore = Arc::clone(&self.audit_responder_semaphore);
3856 let handle = tokio::spawn(async move {
3857 let mut window_started = Instant::now();
3858 loop {
3859 tokio::select! {
3860 () = shutdown.cancelled() => {
3861 log_audit_responder_summary(
3862 &metrics,
3863 &semaphore,
3864 window_started.elapsed(),
3865 );
3866 break;
3867 }
3868 () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3869 log_audit_responder_summary(
3870 &metrics,
3871 &semaphore,
3872 window_started.elapsed(),
3873 );
3874 window_started = Instant::now();
3875 }
3876 }
3877 }
3878 debug!("Audit responder summary loop shut down");
3879 });
3880 self.task_handles.push(handle);
3881 }
3882
3883 #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3884 fn start_fetch_worker(&mut self) {
3885 let p2p = Arc::clone(&self.p2p_node);
3886 let storage = Arc::clone(&self.storage);
3887 let queues = Arc::clone(&self.queues);
3888 let config = Arc::clone(&self.config);
3889 let shutdown = self.shutdown.clone();
3890 let bootstrap_state = Arc::clone(&self.bootstrap_state);
3891 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3892 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3893 let detached_task_tracker = self.detached_task_tracker.clone();
3894 let concurrency = max_parallel_fetch();
3895
3896 info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3897
3898 let handle = tokio::spawn(async move {
3899 // Each in-flight future yields (key, Option<FetchOutcome>) so we
3900 // always recover the key — even if the inner task panics.
3901 let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3902
3903 loop {
3904 // Fill up to `concurrency` slots from the queue.
3905 {
3906 let mut q = queues.write().await;
3907 while in_flight.len() < concurrency {
3908 let Some(candidate) = q.dequeue_fetch() else {
3909 break;
3910 };
3911 let fetch_key = candidate.key;
3912 let Some(&source) = candidate.sources.first() else {
3913 warn!(
3914 "Fetch candidate {} has no sources; requeueing for verification",
3915 hex::encode(fetch_key)
3916 );
3917 let _ = q.requeue_candidate_for_verification(
3918 candidate,
3919 config.verification_request_timeout,
3920 );
3921 continue;
3922 };
3923 q.start_dequeued_fetch(candidate, source);
3924
3925 let p2p = Arc::clone(&p2p);
3926 let storage = Arc::clone(&storage);
3927 let config = Arc::clone(&config);
3928 let token = shutdown.clone();
3929 let tracker = detached_task_tracker.clone();
3930 in_flight.push(Box::pin(async move {
3931 // Tracked so shutdown() still awaits the task if
3932 // this awaiter is dropped (e.g. the worker is
3933 // aborted): it holds Arc<ChunkStore> and must
3934 // not outlive the engine.
3935 let handle = tracker.spawn(async move {
3936 // Cancel-aware: abort when the engine shuts down.
3937 tokio::select! {
3938 () = token.cancelled() => FetchOutcome {
3939 key: fetch_key,
3940 result: FetchResult::SourceFailed,
3941 },
3942 outcome = execute_single_fetch(
3943 p2p, storage, config, fetch_key, source,
3944 ) => outcome,
3945 }
3946 });
3947 match handle.await {
3948 Ok(outcome) => (outcome.key, Some(outcome)),
3949 Err(e) => {
3950 error!(
3951 "Fetch task for {} panicked: {e}",
3952 hex::encode(fetch_key)
3953 );
3954 (fetch_key, None)
3955 }
3956 }
3957 }));
3958 }
3959 } // release queues write lock
3960
3961 if in_flight.is_empty() {
3962 // No work — wait for new items or shutdown.
3963 tokio::select! {
3964 () = shutdown.cancelled() => break,
3965 () = tokio::time::sleep(
3966 std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3967 ) => continue,
3968 }
3969 }
3970
3971 // Wait for the next fetch to complete and process the result.
3972 tokio::select! {
3973 () = shutdown.cancelled() => break,
3974 Some((key, maybe_outcome)) = in_flight.next() => {
3975 let mut q = queues.write().await;
3976 let terminal = if let Some(outcome) = maybe_outcome {
3977 match apply_fetch_result(
3978 &mut q,
3979 &key,
3980 &outcome.result,
3981 config.verification_request_timeout,
3982 ) {
3983 FetchFollowUp::Terminal => true,
3984 FetchFollowUp::RequeuedForVerification => false,
3985 FetchFollowUp::RetryFrom(next_peer) => {
3986 // Spawn a new fetch task for the next source.
3987 let p2p = Arc::clone(&p2p);
3988 let storage = Arc::clone(&storage);
3989 let config = Arc::clone(&config);
3990 let token = shutdown.clone();
3991 let tracker = detached_task_tracker.clone();
3992 let fetch_key = key;
3993 in_flight.push(Box::pin(async move {
3994 // Tracked for the same reason as the
3995 // initial fetch spawn above.
3996 let handle = tracker.spawn(async move {
3997 tokio::select! {
3998 () = token.cancelled() => FetchOutcome {
3999 key: fetch_key,
4000 result: FetchResult::SourceFailed,
4001 },
4002 outcome = execute_single_fetch(
4003 p2p, storage, config, fetch_key, next_peer,
4004 ) => outcome,
4005 }
4006 });
4007 match handle.await {
4008 Ok(outcome) => (outcome.key, Some(outcome)),
4009 Err(e) => {
4010 error!(
4011 "Fetch task for {} panicked: {e}",
4012 hex::encode(fetch_key)
4013 );
4014 (fetch_key, None)
4015 }
4016 }
4017 }));
4018 false
4019 }
4020 }
4021 } else {
4022 // Task panicked — retry verification when this was
4023 // a verified repair, otherwise reclaim the slot.
4024 !q.requeue_fetch_for_verification(
4025 &key,
4026 config.verification_request_timeout,
4027 )
4028 };
4029
4030 // Shrink bootstrap pending set on terminal exit.
4031 if terminal {
4032 drop(q); // release queues lock before acquiring bootstrap_state
4033 if !bootstrap_state.read().await.is_drained() {
4034 bootstrap_state.write().await.remove_key(&key);
4035 let q = queues.read().await;
4036 if bootstrap::check_bootstrap_drained(
4037 &bootstrap_state,
4038 &q,
4039 )
4040 .await
4041 {
4042 complete_bootstrap(
4043 &is_bootstrapping,
4044 &bootstrap_complete_notify,
4045 ).await;
4046 }
4047 }
4048 }
4049 }
4050 }
4051 }
4052
4053 // Cancel and drain remaining in-flight fetches on shutdown.
4054 // The CancellationToken is already cancelled by this point, so
4055 // spawned tasks will see cancellation via their select! branches.
4056 while in_flight.next().await.is_some() {}
4057 debug!("Fetch worker shut down");
4058 });
4059 self.task_handles.push(handle);
4060 }
4061
4062 fn start_verification_worker(&mut self) {
4063 let p2p = Arc::clone(&self.p2p_node);
4064 let storage = Arc::clone(&self.storage);
4065 let queues = Arc::clone(&self.queues);
4066 let paid_list = Arc::clone(&self.paid_list);
4067 let config = Arc::clone(&self.config);
4068 let shutdown = self.shutdown.clone();
4069 let bootstrap_state = Arc::clone(&self.bootstrap_state);
4070 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4071 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4072 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4073 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4074 let recent_provers = Arc::clone(&self.recent_provers);
4075
4076 let handle = tokio::spawn(async move {
4077 loop {
4078 tokio::select! {
4079 () = shutdown.cancelled() => break,
4080 () = tokio::time::sleep(
4081 std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
4082 ) => {
4083 let ctx = VerificationCycleContext {
4084 p2p_node: &p2p,
4085 paid_list: &paid_list,
4086 storage: &storage,
4087 queues: &queues,
4088 config: &config,
4089 bootstrap_state: &bootstrap_state,
4090 is_bootstrapping: &is_bootstrapping,
4091 bootstrap_complete_notify: &bootstrap_complete_notify,
4092 last_commitment_by_peer: &last_commitment_by_peer,
4093 ever_capable_peers: &ever_capable_peers,
4094 recent_provers: &recent_provers,
4095 };
4096 run_verification_cycle(ctx).await;
4097 }
4098 }
4099 }
4100 debug!("Verification worker shut down");
4101 });
4102 self.task_handles.push(handle);
4103 }
4104
4105 /// Gap 3: Run a one-shot bootstrap sync on startup.
4106 ///
4107 /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
4108 /// (indicating the routing table is populated) before snapshotting
4109 /// close neighbors. Falls back after a timeout so bootstrap nodes
4110 /// (which have no peers and therefore never receive the event) still
4111 /// proceed.
4112 ///
4113 /// After the gate, finds close neighbors, syncs with each in
4114 /// round-robin batches, admits returned hints into the verification
4115 /// pipeline, and tracks discovered keys for bootstrap drain detection.
4116 #[allow(clippy::too_many_lines)]
4117 fn start_bootstrap_sync(
4118 &mut self,
4119 dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
4120 ) {
4121 let p2p = Arc::clone(&self.p2p_node);
4122 let storage = Arc::clone(&self.storage);
4123 let paid_list = Arc::clone(&self.paid_list);
4124 let queues = Arc::clone(&self.queues);
4125 let config = Arc::clone(&self.config);
4126 let shutdown = self.shutdown.clone();
4127 let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4128 let bootstrap_state = Arc::clone(&self.bootstrap_state);
4129 let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4130 let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
4131 let repair_proofs = Arc::clone(&self.repair_proofs);
4132 let my_commitment_state = Arc::clone(&self.commitment_state);
4133 let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4134 let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4135 let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
4136
4137 let handle = tokio::spawn(async move {
4138 // Wait for DHT bootstrap to complete before snapshotting
4139 // neighbors. The routing table is empty until saorsa-core
4140 // finishes its FIND_NODE rounds and bucket refreshes.
4141 let gate = bootstrap::wait_for_bootstrap_complete(
4142 dht_events,
4143 config.bootstrap_complete_timeout_secs,
4144 &shutdown,
4145 )
4146 .await;
4147
4148 if gate == bootstrap::BootstrapGateResult::Shutdown {
4149 return;
4150 }
4151
4152 let self_id = *p2p.peer_id();
4153 let neighbors =
4154 neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
4155 .await;
4156
4157 if neighbors.is_empty() {
4158 info!("Bootstrap sync: no close neighbors found, marking drained");
4159 bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
4160 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4161 return;
4162 }
4163
4164 let neighbor_count = neighbors.len();
4165 info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
4166
4167 // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
4168 for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
4169 if shutdown.is_cancelled() {
4170 break;
4171 }
4172
4173 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
4174 batch,
4175 &storage,
4176 &paid_list,
4177 &p2p,
4178 config.close_group_size,
4179 config.paid_list_close_group_size,
4180 )
4181 .await;
4182
4183 // Keep the batch outstanding until every response has been
4184 // admitted and bootstrap accounting is updated. The verification
4185 // worker uses this counter as a batch barrier, so it cannot race
4186 // the source aggregation below.
4187 bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
4188 let bootstrapping = *is_bootstrapping.read().await;
4189
4190 let sync_futures = batch.iter().map(|peer| {
4191 let peer = *peer;
4192 let hints = hints_by_peer.remove(&peer).unwrap_or_default();
4193 // Atomically snapshot + mark-gossiped for each emitted
4194 // bootstrap request so we remain answerable for it.
4195 let commitment = my_commitment_state
4196 .current_for_gossip()
4197 .map(|binding| binding.commitment().clone());
4198 let p2p = &p2p;
4199 let config = &config;
4200 async move {
4201 let outcome = neighbor_sync::sync_with_peer_with_hints(
4202 &peer,
4203 p2p,
4204 config,
4205 bootstrapping,
4206 hints,
4207 commitment,
4208 )
4209 .await;
4210 (peer, outcome)
4211 }
4212 });
4213 let completed = join_all(sync_futures).await;
4214
4215 // Process response metadata before exposing any of this batch's
4216 // hints to verification.
4217 for (peer, outcome) in &completed {
4218 if let Some(outcome) = outcome {
4219 // Ingest the peer's piggybacked commitment from the
4220 // response (same verification as the request path).
4221 // Bootstrap is the FIRST gossip we receive from most
4222 // peers, so this populates last_commitment_by_peer.
4223 //
4224 // We intentionally do NOT trigger a gossip-audit here:
4225 // during bootstrap this node may itself still be
4226 // bootstrapping (audits are gated on that), and the
4227 // close-group/RT view is not yet stable. The peer is
4228 // audited on the first STEADY-STATE neighbor-sync round
4229 // after bootstrap drains (request + response paths both
4230 // trigger), which is within one sync cycle — so caching
4231 // the commitment here is sufficient and there is no
4232 // coverage gap (ADR-0002).
4233 ingest_peer_commitment(
4234 peer,
4235 outcome.response.commitment.as_ref(),
4236 &p2p,
4237 &last_commitment_by_peer,
4238 &ever_capable_peers,
4239 &sig_verify_attempts,
4240 )
4241 .await; // sig_verify_attempts in scope from line ~1080
4242
4243 if !outcome.response.bootstrapping {
4244 record_sent_replica_hints(
4245 peer,
4246 &outcome.sent_replica_hints,
4247 &repair_proofs,
4248 &sync_cycle_epoch,
4249 )
4250 .await;
4251 }
4252 }
4253 }
4254
4255 let pending_keys: HashSet<XorName> = {
4256 let q = queues.read().await;
4257 q.pending_keys().into_iter().collect()
4258 };
4259 let admission_futures = completed.iter().map(async |(_, outcome)| match outcome {
4260 Some(outcome) if !outcome.response.bootstrapping => Some(
4261 admission::admit_hints(
4262 &self_id,
4263 &outcome.response.replica_hints,
4264 &outcome.response.paid_hints,
4265 &p2p,
4266 &config,
4267 &storage,
4268 &paid_list,
4269 &pending_keys,
4270 )
4271 .await,
4272 ),
4273 _ => None,
4274 });
4275 let admitted = join_all(admission_futures).await;
4276
4277 // Queue every peer's admitted hints under one write lock. Once
4278 // released, source-count ordering sees the complete batch.
4279 let (batch_outcomes, batch_discovered) = {
4280 let mut q = queues.write().await;
4281 let outcomes = completed
4282 .iter()
4283 .zip(admitted)
4284 .filter_map(|((peer, _), admitted)| {
4285 admitted.map(|admitted| {
4286 (
4287 *peer,
4288 queue_admitted_hints(peer, admitted, &storage, &mut q),
4289 )
4290 })
4291 })
4292 .collect::<Vec<_>>();
4293 let live_discovered = outcomes
4294 .iter()
4295 .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
4296 .filter(|key| q.contains_key(key))
4297 .collect::<HashSet<_>>();
4298 (outcomes, live_discovered)
4299 };
4300
4301 publish_bootstrap_admission_outcomes(
4302 &bootstrap_state,
4303 &batch_outcomes,
4304 &batch_discovered,
4305 )
4306 .await;
4307
4308 bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4309 }
4310
4311 // Check drain condition.
4312 {
4313 let q = queues.read().await;
4314 if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4315 complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4316 }
4317 }
4318
4319 info!("Bootstrap sync completed");
4320 });
4321 self.task_handles.push(handle);
4322 }
4323}
4324
4325// ===========================================================================
4326// Free functions for background tasks
4327// ===========================================================================
4328
4329#[cfg(feature = "logging")]
4330fn log_audit_responder_summary(
4331 metrics: &AuditResponderMetrics,
4332 semaphore: &Semaphore,
4333 window: Duration,
4334) {
4335 let snapshot = metrics.take_snapshot();
4336 if snapshot.origins.is_empty() {
4337 return;
4338 }
4339
4340 let total = snapshot.total;
4341 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4342 total.received_by_class;
4343 let global_inflight =
4344 MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4345 info!(
4346 target: "ant_node::replication::audit_responder",
4347 window_ms = window.as_millis(),
4348 source_count = snapshot.origins.len(),
4349 received = total.received(),
4350 digest_received,
4351 subtree_received,
4352 byte_received,
4353 commitment_pin_received,
4354 admitted = total.admitted,
4355 global_pool_drops = total.global_pool_drops,
4356 per_peer_cap_drops = total.per_peer_cap_drops,
4357 serial_queue_drops = total.serial_queue_drops,
4358 completed = total.completed,
4359 send_failures = total.send_failures,
4360 processing_avg_ms = total.processing_avg_ms(),
4361 processing_max_ms = total.processing_max_ms,
4362 total_avg_ms = total.total_avg_ms(),
4363 total_max_ms = total.total_max_ms,
4364 global_inflight,
4365 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4366 peak_global_inflight = total.peak_global_inflight,
4367 "Audit responder summary"
4368 );
4369
4370 for (index, origin) in snapshot
4371 .origins
4372 .iter()
4373 .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4374 .enumerate()
4375 {
4376 let Some(source) = origin.source else {
4377 continue;
4378 };
4379 let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4380 origin.received_by_class;
4381 info!(
4382 target: "ant_node::replication::audit_responder",
4383 rank = index + 1,
4384 source = %source,
4385 received = origin.received(),
4386 digest_received,
4387 subtree_received,
4388 byte_received,
4389 commitment_pin_received,
4390 admitted = origin.admitted,
4391 global_pool_drops = origin.global_pool_drops,
4392 per_peer_cap_drops = origin.per_peer_cap_drops,
4393 serial_queue_drops = origin.serial_queue_drops,
4394 completed = origin.completed,
4395 send_failures = origin.send_failures,
4396 processing_avg_ms = origin.processing_avg_ms(),
4397 processing_max_ms = origin.processing_max_ms,
4398 total_avg_ms = origin.total_avg_ms(),
4399 total_max_ms = origin.total_max_ms,
4400 peak_global_inflight = origin.peak_global_inflight,
4401 peak_peer_inflight = origin.peak_peer_inflight,
4402 "Audit responder top origin"
4403 );
4404 }
4405}
4406
4407/// Which ceiling rejected an audit-responder admission attempt.
4408///
4409/// Stable, machine-readable so a production log-scrape can bucket drops by
4410/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4411/// single opaque "capacity reached" line; this splits the two distinct causes
4412/// so the next such investigation can tell a global-pool exhaustion (the whole
4413/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4414/// without re-instrumenting.
4415///
4416/// This branch runs a SINGLE shared audit-responder pool for all challenge
4417/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4418/// pool to distinguish here — the `kind=` log field already separates the
4419/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4420/// dedicated slow pool is later split out, add its variants here.
4421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4422enum ResponderRejectReason {
4423 /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4424 /// free; the per-peer cap was not the binding constraint.
4425 GlobalPoolFull,
4426 /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4427 /// share, so the global permit was never attempted.
4428 PerPeerCapFull,
4429}
4430
4431impl ResponderRejectReason {
4432 /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4433 /// frozen — production log tooling greps for them.
4434 fn as_str(self) -> &'static str {
4435 match self {
4436 Self::GlobalPoolFull => "global_pool_full",
4437 Self::PerPeerCapFull => "per_peer_cap_full",
4438 }
4439 }
4440}
4441
4442impl From<ResponderRejectReason> for AuditResponderDropReason {
4443 fn from(reason: ResponderRejectReason) -> Self {
4444 match reason {
4445 ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4446 ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4447 }
4448 }
4449}
4450
4451impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4452 fn from(reason: ResponderRejectReason) -> Self {
4453 match reason {
4454 ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4455 ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4456 }
4457 }
4458}
4459
4460/// Cumulative fresh-offer admission refusals in this process.
4461///
4462/// **Expected value in healthy operation is zero.** A node that refuses a
4463/// legitimate fresh offer does not merely shed load: the sender transmits
4464/// offers one-way and never reads the refusal, so the chunk's absence
4465/// resurfaces at the sender's delayed possession check and is charged to the
4466/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4467/// means the node is either under-provisioned for its offered load or its
4468/// admission share is mis-sized — and is accruing unearned trust damage either
4469/// way. Operators should alarm on any sustained non-zero rate.
4470///
4471/// Process-global rather than per-engine, which is exactly right in production
4472/// (one node per process) and adequate in multi-node test harnesses, where the
4473/// useful assertion is that *no* node in the fleet refused.
4474#[must_use]
4475pub fn fresh_offer_admission_refusals() -> u64 {
4476 audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4477}
4478
4479/// Cumulative paid-list notification admission refusals in this process.
4480///
4481/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4482/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4483/// paid-list evidence outright rather than pushing work back onto a requester.
4484#[must_use]
4485pub fn paid_notify_admission_refusals() -> u64 {
4486 audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4487}
4488
4489/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4490///
4491/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4492/// different things: this one says the node was saturated across all sources
4493/// and is genuinely under-provisioned for its offered load.
4494#[must_use]
4495pub fn fresh_offer_refusals_global_pool() -> u64 {
4496 audit_metrics::responder_admission_drops_by_ceiling(
4497 ReplicationResponderClass::FreshOffer,
4498 ResponderAdmissionCeiling::GlobalPool,
4499 )
4500}
4501
4502/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4503///
4504/// For fresh offers this usually indicts the *share's size* rather than the
4505/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4506/// node handling a client's PUT and fanning it out — so a share sized for
4507/// request/response traffic will refuse ordinary uploads.
4508#[must_use]
4509pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4510 audit_metrics::responder_admission_drops_by_ceiling(
4511 ReplicationResponderClass::FreshOffer,
4512 ResponderAdmissionCeiling::PerPeerShare,
4513 )
4514}
4515
4516/// Why an audit-responder admission attempt failed, with the decision-time
4517/// capacity counters that let a drop be logged with full context.
4518///
4519/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4520/// decision was made (the two ceilings are read under different locks, so they
4521/// are not a single atomic view), but they are exact enough to tell a saturated
4522/// node from a single self-throttling flooder.
4523#[derive(Debug, Clone, Copy)]
4524struct ResponderAdmissionFailure {
4525 reason: ResponderRejectReason,
4526 /// Global permits in use across the whole engine at decision time.
4527 global_inflight: usize,
4528 /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4529 global_limit: usize,
4530 /// In-flight audit responders already held for `source` at decision time.
4531 peer_inflight: u32,
4532 /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4533 peer_limit: u32,
4534}
4535
4536impl fmt::Display for ResponderAdmissionFailure {
4537 /// Renders the stable `reason=... global_inflight=... global_limit=...
4538 /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4540 write!(
4541 f,
4542 "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4543 self.reason.as_str(),
4544 self.global_inflight,
4545 self.global_limit,
4546 self.peer_inflight,
4547 self.peer_limit,
4548 )
4549 }
4550}
4551
4552/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4553/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4554/// spawned task ties both bounds to the task's exact lifetime — no manual
4555/// decrement to forget on an early return or panic.
4556struct ResponderGuard {
4557 _permit: tokio::sync::OwnedSemaphorePermit,
4558 _peer_slot: PeerResponderSlot,
4559 global_inflight: usize,
4560 peer_inflight: u32,
4561}
4562
4563type AuditResponderGuard = ResponderGuard;
4564type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4565
4566/// Provisional or admitted per-peer responder slot.
4567///
4568/// The slot is claimed before the global permit is attempted. Keeping that
4569/// claim under RAII means cancellation while rolling a failed admission back
4570/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4571/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4572struct PeerResponderSlot {
4573 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4574 peer: PeerId,
4575}
4576
4577#[derive(Clone)]
4578struct ReplicationMessageHandlerContext {
4579 p2p_node: Arc<P2PNode>,
4580 storage: Arc<ChunkStore>,
4581 paid_list: Arc<PaidList>,
4582 payment_verifier: Arc<PaymentVerifier>,
4583 queues: Arc<RwLock<ReplicationQueues>>,
4584 config: Arc<ReplicationConfig>,
4585 is_bootstrapping: Arc<RwLock<bool>>,
4586 bootstrap_state: Arc<RwLock<BootstrapState>>,
4587 sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4588 sync_cycle_epoch: Arc<RwLock<u64>>,
4589 repair_proofs: Arc<RwLock<RepairProofs>>,
4590 last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4591 ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4592 sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4593 my_commitment_state: Arc<ResponderCommitmentState>,
4594 gossip_audit: GossipAuditTrigger,
4595 audit_responder_semaphore: Arc<Semaphore>,
4596 audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4597 audit_responder_metrics: Arc<AuditResponderMetrics>,
4598 subtree_round1: SubtreeRound1Limiter,
4599 fetch_responder_worker_semaphore: Arc<Semaphore>,
4600 fetch_responder_admission_semaphore: Arc<Semaphore>,
4601 fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4602 verification_responder_worker_semaphore: Arc<Semaphore>,
4603 verification_responder_admission_semaphore: Arc<Semaphore>,
4604 verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4605 neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4606 neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4607 neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4608 fresh_offer_worker_semaphore: Arc<Semaphore>,
4609 fresh_offer_admission_semaphore: Arc<Semaphore>,
4610 fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4611 fresh_offer_in_flight: FreshOfferInFlight,
4612 paid_notify_worker_semaphore: Arc<Semaphore>,
4613 paid_notify_admission_semaphore: Arc<Semaphore>,
4614 paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4615 /// Pointer replication, when this node stores pointers.
4616 pointers: Option<Arc<pointer::PointerReplication>>,
4617 /// The engine's shutdown token, for detached responder work.
4618 ///
4619 /// Workers on [`Self::detached_task_tracker`] race this around their
4620 /// *network* phase only — never around a storage `spawn_blocking` await,
4621 /// where dropping the awaiter would detach a live transaction. This is
4622 /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4623 /// terminate: the wait stays safe because it is now guaranteed finite.
4624 shutdown: CancellationToken,
4625 /// Shared tracker for detached work so `shutdown()` can await release of
4626 /// storage and P2P resources after all producer tasks have stopped.
4627 detached_task_tracker: TaskTracker,
4628}
4629
4630struct InboundReplicationMessage {
4631 source: PeerId,
4632 msg: ReplicationMessage,
4633 rr_message_id: Option<String>,
4634 received_at: Instant,
4635}
4636
4637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4638enum SerialQueueDropReason {
4639 Full,
4640 Closed,
4641}
4642
4643#[cfg(feature = "logging")]
4644impl SerialQueueDropReason {
4645 const fn as_str(self) -> &'static str {
4646 match self {
4647 Self::Full => "full",
4648 Self::Closed => "closed",
4649 }
4650 }
4651}
4652
4653#[derive(Debug, Clone, Copy)]
4654#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4655struct SerialQueueDrop {
4656 source: PeerId,
4657 message_class: &'static str,
4658 audit_responder_class: Option<AuditResponderClass>,
4659 queue_depth: usize,
4660 reason: SerialQueueDropReason,
4661}
4662
4663fn try_enqueue_serial_message(
4664 sender: &mpsc::Sender<InboundReplicationMessage>,
4665 inbound: InboundReplicationMessage,
4666) -> std::result::Result<(), SerialQueueDrop> {
4667 let source = inbound.source;
4668 let message_class = replication_message_class(&inbound.msg.body);
4669 let audit_responder_class = audit_responder_class(&inbound.msg.body);
4670 let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4671 sender.try_send(inbound).map_err(|error| {
4672 let (reason, dropped) = match error {
4673 mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4674 mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4675 };
4676 audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4677 SerialQueueDrop {
4678 source,
4679 message_class,
4680 audit_responder_class,
4681 queue_depth,
4682 reason,
4683 }
4684 })
4685}
4686
4687const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4688 match body {
4689 ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4690 ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4691 ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4692 ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4693 ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4694 ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4695 ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4696 ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4697 ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4698 ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4699 ReplicationMessageBody::AuditResponse(_) => "audit_response",
4700 ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4701 ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4702 ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4703 ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4704 ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4705 ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4706 ReplicationMessageBody::PointerFreshOffer(_) => "pointer_fresh_offer",
4707 ReplicationMessageBody::PointerHints(_) => "pointer_hints",
4708 ReplicationMessageBody::PointerFetchRequest(_) => "pointer_fetch_request",
4709 ReplicationMessageBody::PointerFetchResponse(_) => "pointer_fetch_response",
4710 ReplicationMessageBody::PointerStateRequest(_) => "pointer_state_request",
4711 ReplicationMessageBody::PointerStateResponse(_) => "pointer_state_response",
4712 }
4713}
4714
4715const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4716 match body {
4717 ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4718 ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4719 ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4720 ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4721 _ => None,
4722 }
4723}
4724
4725impl AuditResponderClass {
4726 const fn per_peer_limit(self) -> u32 {
4727 match self {
4728 Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4729 Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4730 }
4731 }
4732}
4733
4734fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4735 match error {
4736 RecvError::Lagged(missed) => {
4737 audit_metrics::record_replication_event_lagged(*missed);
4738 warn!(
4739 "Missed {missed} P2P events on replication branch (broadcast lag); \
4740 replication messages may have been dropped before dispatch"
4741 );
4742 ControlFlow::Continue(())
4743 }
4744 RecvError::Closed => {
4745 // A closed broadcast channel never yields again, so the branch
4746 // would otherwise be immediately ready on every select! iteration.
4747 warn!("P2P event stream closed on replication branch; stopping message handler");
4748 ControlFlow::Break(())
4749 }
4750 }
4751}
4752
4753fn replication_payload_from_event(
4754 event: P2PEvent,
4755) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4756 let P2PEvent::Message {
4757 topic,
4758 source: Some(source),
4759 data,
4760 ..
4761 } = event
4762 else {
4763 return None;
4764 };
4765
4766 let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4767 if !is_rr {
4768 return Some((source, data, matched_id, None));
4769 }
4770 if is_rr {
4771 return P2PNode::parse_request_envelope(&data)
4772 .filter(|(_, is_resp, _)| !is_resp)
4773 .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4774 }
4775 None
4776}
4777
4778impl Drop for PeerResponderSlot {
4779 fn drop(&mut self) {
4780 // Decrement (and prune to keep the map bounded) without blocking the
4781 // async runtime: a short lock on a tiny map.
4782 //
4783 // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4784 // with no spawn. Otherwise defer to a task — but only if a runtime is
4785 // actually current, so `Drop` during shutdown (no runtime) can never
4786 // panic. A missed decrement at shutdown is harmless: the whole map is
4787 // being dropped with the engine.
4788 let peer = self.peer;
4789 if let Ok(mut map) = self.inflight.try_write() {
4790 if let Some(n) = map.get_mut(&peer) {
4791 *n = n.saturating_sub(1);
4792 if *n == 0 {
4793 map.remove(&peer);
4794 }
4795 }
4796 return;
4797 }
4798 if let Ok(handle) = tokio::runtime::Handle::try_current() {
4799 let inflight = Arc::clone(&self.inflight);
4800 handle.spawn(async move {
4801 let mut map = inflight.write().await;
4802 if let Some(n) = map.get_mut(&peer) {
4803 *n = n.saturating_sub(1);
4804 if *n == 0 {
4805 map.remove(&peer);
4806 }
4807 }
4808 });
4809 }
4810 }
4811}
4812
4813/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4814/// and then a global permit. The limits are parameters so independent responder
4815/// classes can reuse the same flood-fair admission and cancellation semantics.
4816async fn admit_bounded_responder(
4817 semaphore: &Arc<Semaphore>,
4818 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4819 source: &PeerId,
4820 global_limit: usize,
4821 peer_limit: u32,
4822) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4823 let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4824
4825 let admitted_peer_inflight = {
4826 let mut map = inflight.write().await;
4827 let entry = map.entry(*source).or_insert(0);
4828 if *entry >= peer_limit {
4829 let peer_inflight = *entry;
4830 drop(map);
4831 return Err(ResponderAdmissionFailure {
4832 reason: ResponderRejectReason::PerPeerCapFull,
4833 global_inflight: global_inflight(semaphore),
4834 global_limit,
4835 peer_inflight,
4836 peer_limit,
4837 });
4838 }
4839 *entry += 1;
4840 *entry
4841 };
4842
4843 let peer_slot = PeerResponderSlot {
4844 inflight: Arc::clone(inflight),
4845 peer: *source,
4846 };
4847 let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4848 return Err(ResponderAdmissionFailure {
4849 reason: ResponderRejectReason::GlobalPoolFull,
4850 global_inflight: global_inflight(semaphore),
4851 global_limit,
4852 peer_inflight: admitted_peer_inflight.saturating_sub(1),
4853 peer_limit,
4854 });
4855 };
4856
4857 Ok(ResponderGuard {
4858 _permit: permit,
4859 _peer_slot: peer_slot,
4860 global_inflight: global_inflight(semaphore),
4861 peer_inflight: admitted_peer_inflight,
4862 })
4863}
4864
4865/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4866struct SubtreeSession {
4867 commitment_hash: [u8; 32],
4868 nonce: [u8; 32],
4869 inserted: Instant,
4870 /// What round 1 bound for each pointer it proved, so round 2 serves that
4871 /// record however many updates land in between (ADR-0019).
4872 pointer_bindings: PointerBindings,
4873}
4874
4875/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4876/// read and hash, refilled continuously at
4877/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4878/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4879///
4880/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4881/// identity may ask, so it is refilled by acquiring more identities; this is
4882/// charged for work done regardless of who asked, so it is not.
4883///
4884/// Charged after the fact, with the bytes the proof actually covered: the cost
4885/// of a request is not known until the pinned commitment has been resolved and
4886/// its subtree selected, both of which happen inside the handler. Admission
4887/// therefore asks only whether the balance is positive, and a proof that costs
4888/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4889/// Carrying the debt is what makes the bound real: without it a maximal proof
4890/// would cost the same as a trivial one, since either way the next request only
4891/// has to wait for the balance to climb back above zero. With it, sustained
4892/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4893/// admitted proportionally less often.
4894struct Round1WorkBudget {
4895 /// Signed, so an over-large proof leaves debt to work off.
4896 balance: i64,
4897 last_refill: Instant,
4898}
4899
4900impl Round1WorkBudget {
4901 /// Deepest debt carried, so one huge proof cannot lock out honest audits
4902 /// for longer than the burst takes to refill.
4903 const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4904 /// Nanoseconds per second, for the sub-second part of a refill.
4905 const NANOS_PER_SEC: i64 = 1_000_000_000;
4906
4907 fn new() -> Self {
4908 Self {
4909 balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4910 last_refill: Instant::now(),
4911 }
4912 }
4913
4914 /// Add the tokens accrued since the last touch, capped at the burst size.
4915 fn refill(&mut self, now: Instant) {
4916 let elapsed = now.saturating_duration_since(self.last_refill);
4917 self.last_refill = now;
4918 let whole_secs = i64::try_from(elapsed.as_secs())
4919 .unwrap_or(i64::MAX)
4920 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4921 let sub_sec = i64::from(elapsed.subsec_nanos())
4922 .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4923 / Self::NANOS_PER_SEC;
4924 self.balance = self
4925 .balance
4926 .saturating_add(whole_secs.saturating_add(sub_sec))
4927 .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4928 }
4929
4930 /// Whether budget remains for a new round-1 proof.
4931 fn has_budget(&mut self, now: Instant) -> bool {
4932 self.refill(now);
4933 self.balance > 0
4934 }
4935
4936 /// Charge `bytes` of completed proof work, carrying debt down to
4937 /// [`Self::MAX_DEBT`].
4938 fn charge(&mut self, bytes: i64, now: Instant) {
4939 self.refill(now);
4940 self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4941 }
4942}
4943
4944/// Resource controls for the HEAVY subtree-audit round 1: a tight
4945/// admission pool separate from the light responsible/slice audits, a per-peer
4946/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4947/// challenge is only served after a matching round 1.
4948///
4949/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4950/// bounds not keyed by peer identity, and so the only one that bounds sustained
4951/// work rather than concurrency or per-identity frequency.
4952#[derive(Clone)]
4953struct SubtreeRound1Limiter {
4954 semaphore: Arc<Semaphore>,
4955 /// Global ceiling on concurrent round-1 proofs (config-driven;
4956 /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4957 /// semaphore because the per-peer admission helper needs the same number.
4958 max_concurrent: usize,
4959 inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4960 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4961 /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4962 /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4963 cooldown_interval: Duration,
4964 sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4965 /// Identity-independent ceiling on sustained round-1 work.
4966 work: Arc<RwLock<Round1WorkBudget>>,
4967}
4968
4969impl SubtreeRound1Limiter {
4970 /// `max_concurrent` of 0 would wedge the responder into refusing every
4971 /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4972 /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4973 /// rather than to off.
4974 fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4975 let max_concurrent = max_concurrent.max(1);
4976 Self {
4977 semaphore: Arc::new(Semaphore::new(max_concurrent)),
4978 max_concurrent,
4979 inflight: Arc::new(RwLock::new(HashMap::new())),
4980 cooldown: Arc::new(RwLock::new(HashMap::new())),
4981 cooldown_interval,
4982 sessions: Arc::new(RwLock::new(HashMap::new())),
4983 work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4984 }
4985 }
4986
4987 /// Charge completed round-1 proof work against the responder-wide budget.
4988 async fn charge_work(&self, content_bytes: i64) {
4989 self.work
4990 .write()
4991 .await
4992 .charge(content_bytes, Instant::now());
4993 }
4994
4995 /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4996 /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4997 /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4998 /// drops the challenge (the remote auditor applies its own graced-timeout
4999 /// policy).
5000 async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
5001 let guard = admit_bounded_responder(
5002 &self.semaphore,
5003 &self.inflight,
5004 source,
5005 self.max_concurrent,
5006 MAX_SUBTREE_ROUND1_PER_PEER,
5007 )
5008 .await
5009 .ok()?;
5010 // Checked before the per-peer cooldown is stamped, so a peer refused for
5011 // want of budget is not also charged its next allowance.
5012 if !self.work.write().await.has_budget(Instant::now()) {
5013 return None; // guard drops here, releasing the permit + slot
5014 }
5015 let now = Instant::now();
5016 let mut cooldown = self.cooldown.write().await;
5017 if let Some(&last) = cooldown.get(source) {
5018 if now.duration_since(last) < self.cooldown_interval {
5019 return None; // guard drops here, releasing the permit + slot
5020 }
5021 }
5022 // Evict lapsed entries (their cooldown has expired, so they no longer
5023 // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
5024 cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
5025 if cooldown.len() >= MAX_SUBTREE_SESSIONS {
5026 if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
5027 cooldown.remove(&oldest);
5028 }
5029 }
5030 cooldown.insert(*source, now);
5031 Some(guard)
5032 }
5033
5034 /// Record a single-use session once a round-1 proof is built and about to be
5035 /// sent, so the matching round 2 is admitted exactly once.
5036 ///
5037 /// The session keeps what round 1 bound for each pointer it proved, while
5038 /// every live session together holds no more than
5039 /// [`MAX_SESSION_POINTER_BINDINGS`] of them. A session whose bindings do
5040 /// not fit is not opened and `false` is returned, so its proof is not
5041 /// sent and round 1 is answered `Transient` instead: the bindings of
5042 /// sessions already answered are never given up, because their round 2 is
5043 /// owed them (ADR-0019).
5044 async fn open_session(
5045 &self,
5046 source: PeerId,
5047 challenge_id: u64,
5048 commitment_hash: [u8; 32],
5049 nonce: [u8; 32],
5050 pointer_bindings: PointerBindings,
5051 ) -> bool {
5052 let now = Instant::now();
5053 let mut sessions = self.sessions.write().await;
5054 sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
5055 // Checked before anything is evicted, so a session refused here costs
5056 // no other session its place.
5057 let held: usize = sessions.values().map(|e| e.pointer_bindings.len()).sum();
5058 if held.saturating_add(pointer_bindings.len()) > MAX_SESSION_POINTER_BINDINGS {
5059 return false;
5060 }
5061 if sessions.len() >= MAX_SUBTREE_SESSIONS {
5062 if let Some(oldest) = sessions
5063 .iter()
5064 .min_by_key(|(_, e)| e.inserted)
5065 .map(|(k, _)| *k)
5066 {
5067 sessions.remove(&oldest);
5068 }
5069 }
5070 sessions.insert(
5071 (source, challenge_id),
5072 SubtreeSession {
5073 commitment_hash,
5074 nonce,
5075 inserted: now,
5076 pointer_bindings,
5077 },
5078 );
5079 true
5080 }
5081
5082 /// Atomically consume the round-2 session for this exchange. `Some` iff a
5083 /// live session matching `(source, challenge_id, commitment_hash, nonce)`
5084 /// existed (and is now removed), carrying what its round 1 bound for each
5085 /// pointer; a miss silently drops round 2 to the graced timeout lane
5086 /// (sessions are ephemeral and can be lost across a restart).
5087 async fn consume_session(
5088 &self,
5089 source: &PeerId,
5090 challenge_id: u64,
5091 commitment_hash: &[u8; 32],
5092 nonce: &[u8; 32],
5093 ) -> Option<PointerBindings> {
5094 let mut sessions = self.sessions.write().await;
5095 let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
5096 Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
5097 && &e.commitment_hash == commitment_hash
5098 && &e.nonce == nonce
5099 });
5100 if matches {
5101 sessions
5102 .remove(&(*source, challenge_id))
5103 .map(|e| e.pointer_bindings)
5104 } else {
5105 None
5106 }
5107 }
5108}
5109
5110/// Outcome of admitting a round-2 slice challenge.
5111enum SliceAdmission {
5112 /// Admitted: the guard holds the global permit and the per-peer slot, and
5113 /// the single-use round-1 session has been consumed, yielding what its
5114 /// round 1 bound for each pointer.
5115 Admitted(AuditResponderGuard, PointerBindings),
5116 /// Refused at a responder ceiling. The round-1 session is left INTACT.
5117 Capacity(AuditResponderAdmissionFailure),
5118 /// No live round-1 session matched this challenge.
5119 NoSession,
5120}
5121
5122/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
5123/// the single-use round-1 session.
5124///
5125/// The order is the point: a single-use token must not be spent on work that is
5126/// then refused. Consuming first and testing admission second leaves the session
5127/// destroyed by a purely local capacity drop, so the refusal is not recoverable
5128/// even in principle.
5129///
5130/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
5131/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
5132/// auditor does not currently re-send round 2 within an audit. The preserved
5133/// session is therefore not yet *recovering* an audit — it keeps a refusal
5134/// truthful (temporary means temporary) and keeps the invariant available for a
5135/// retry, rather than baking "capacity drop is permanent" into the state
5136/// machine. If an application-level retry is ruled out for good, this ordering
5137/// still costs nothing over the alternative.
5138///
5139/// Cost of the ordering: the permit and per-peer slot are held across the
5140/// session probe, which is one in-memory map lookup and no chunk work. The
5141/// per-peer cap still bounds a peer sending unsessioned challenges to the same
5142/// share it could already occupy with well-formed ones, so the admission
5143/// surface is unchanged.
5144async fn admit_slice_challenge(
5145 semaphore: &Arc<Semaphore>,
5146 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5147 round1: &SubtreeRound1Limiter,
5148 source: &PeerId,
5149 challenge: &protocol::SubtreeSliceChallenge,
5150) -> SliceAdmission {
5151 let guard =
5152 match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
5153 Ok(guard) => guard,
5154 Err(failure) => return SliceAdmission::Capacity(failure),
5155 };
5156 let Some(pointer_bindings) = round1
5157 .consume_session(
5158 source,
5159 challenge.challenge_id,
5160 &challenge.expected_commitment_hash,
5161 &challenge.nonce,
5162 )
5163 .await
5164 else {
5165 // Release the permit and per-peer slot before the caller replies: no
5166 // chunk work follows, so holding them would shrink the pool for nothing.
5167 drop(guard);
5168 return SliceAdmission::NoSession;
5169 };
5170 SliceAdmission::Admitted(guard, pointer_bindings)
5171}
5172
5173/// Try to admit one audit-responder task for `source`: take a global permit AND
5174/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
5175/// its decision-time counters (caller drops the challenge, leaving the remote
5176/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
5177/// so one flooder can neither exhaust the global pool's effect on others nor
5178/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
5179/// log exactly WHY the drop happened rather than a single opaque "capacity
5180/// reached".
5181async fn admit_audit_responder(
5182 semaphore: &Arc<Semaphore>,
5183 inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5184 source: &PeerId,
5185 class: AuditResponderClass,
5186) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
5187 let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
5188 let peer_limit = class.per_peer_limit();
5189 admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
5190}
5191
5192/// Handle an incoming replication protocol message.
5193///
5194/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
5195/// request-response path and the response must be sent via `send_response`
5196/// so saorsa-core can route it back to the waiting `send_request` caller.
5197#[allow(clippy::too_many_lines)]
5198async fn handle_replication_message(
5199 source: &PeerId,
5200 msg: ReplicationMessage,
5201 ctx: &ReplicationMessageHandlerContext,
5202 received_at: Instant,
5203 rr_message_id: Option<&str>,
5204) -> Result<()> {
5205 match msg.body {
5206 ReplicationMessageBody::FreshReplicationOffer(offer) => {
5207 dispatch_fresh_offer(
5208 *source,
5209 offer,
5210 ctx,
5211 msg.request_id,
5212 received_at,
5213 rr_message_id,
5214 )
5215 .await
5216 }
5217 ReplicationMessageBody::PaidNotify(notify) => {
5218 dispatch_paid_notify(*source, notify, ctx, received_at).await
5219 }
5220 ReplicationMessageBody::NeighborSyncRequest(request) => {
5221 let bootstrapping = *ctx.is_bootstrapping.read().await;
5222 // Phase-3 storage-bound audit: store the sender's
5223 // commitment for use as `expected_commitment_hash` in
5224 // future audits. Verify signature before storing so a peer
5225 // cannot inject a forged commitment for someone else.
5226 if let Some(target) = ingest_peer_commitment(
5227 source,
5228 request.commitment.as_ref(),
5229 &ctx.p2p_node,
5230 &ctx.last_commitment_by_peer,
5231 &ctx.ever_capable_peers,
5232 &ctx.sig_verify_attempts,
5233 )
5234 .await
5235 {
5236 maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
5237 }
5238 dispatch_neighbor_sync_request(
5239 *source,
5240 request,
5241 ctx,
5242 bootstrapping,
5243 // Atomically snapshot + mark-gossiped: emitted in the sync
5244 // response, so we must stay answerable for it (ADR-0002).
5245 ctx.my_commitment_state
5246 .current_for_gossip()
5247 .map(|b| b.commitment().clone()),
5248 msg.request_id,
5249 received_at,
5250 rr_message_id,
5251 )
5252 .await
5253 }
5254 ReplicationMessageBody::VerificationRequest(request) => {
5255 dispatch_verification_request(
5256 *source,
5257 request,
5258 ctx,
5259 msg.request_id,
5260 received_at,
5261 rr_message_id,
5262 )
5263 .await
5264 }
5265 ReplicationMessageBody::FetchRequest(request) => {
5266 dispatch_fetch_request(
5267 *source,
5268 request,
5269 ctx,
5270 msg.request_id,
5271 received_at,
5272 rr_message_id,
5273 )
5274 .await
5275 }
5276 ReplicationMessageBody::AuditChallenge(challenge) => {
5277 // Responsible-chunk audit (audit #2) responder: answer with per-key
5278 // possession digests. This same handler also answers the
5279 // prune-confirmation audit, which sends the same `AuditChallenge`
5280 // wire message.
5281 //
5282 // Answering digests the stored bytes of every challenged key, so —
5283 // like the subtree/byte audits below — run it on a detached task off
5284 // this serial message loop. Handling it inline lets one challenge
5285 // block all other replication traffic until its digests complete
5286 // (head-of-line blocking). The same flood-fair admission applies: a
5287 // global ceiling AND a per-peer cap, dropping the challenge if either
5288 // is hit. A dropped challenge reads as a penalised timeout to the
5289 // auditor, so the caps must remain high enough for honest audit load;
5290 // the per-peer share still prevents one flooder from starving others.
5291 let class = AuditResponderClass::Digest;
5292 let guard = match admit_audit_responder(
5293 &ctx.audit_responder_semaphore,
5294 &ctx.audit_responder_inflight,
5295 source,
5296 class,
5297 )
5298 .await
5299 {
5300 Ok(guard) => guard,
5301 Err(failure) => {
5302 protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
5303 audit_metrics::record_admission_drop(class);
5304 ctx.audit_responder_metrics
5305 .record_drop(*source, failure.reason.into());
5306 warn!(
5307 target: "ant_node::replication::audit_responder",
5308 event = "admission_dropped",
5309 kind = "responsible",
5310 responder_class = class.as_str(),
5311 source = %source,
5312 challenge_id = challenge.challenge_id,
5313 key_count = challenge.keys.len(),
5314 request_response = rr_message_id.is_some(),
5315 dispatch_ms = received_at.elapsed().as_millis(),
5316 reason = failure.reason.as_str(),
5317 global_inflight = failure.global_inflight,
5318 global_limit = failure.global_limit,
5319 peer_inflight = failure.peer_inflight,
5320 peer_limit = failure.peer_limit,
5321 "Audit responder admission dropped"
5322 );
5323 return Ok(());
5324 }
5325 };
5326 let admission_global_inflight = guard.global_inflight;
5327 let admission_peer_inflight = guard.peer_inflight;
5328 ctx.audit_responder_metrics.record_admitted(
5329 *source,
5330 admission_global_inflight,
5331 admission_peer_inflight,
5332 );
5333 info!(
5334 target: "ant_node::replication::audit_responder",
5335 event = "admitted",
5336 kind = "responsible",
5337 responder_class = class.as_str(),
5338 source = %source,
5339 challenge_id = challenge.challenge_id,
5340 key_count = challenge.keys.len(),
5341 request_response = rr_message_id.is_some(),
5342 dispatch_ms = received_at.elapsed().as_millis(),
5343 global_inflight = admission_global_inflight,
5344 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5345 peer_inflight = admission_peer_inflight,
5346 peer_limit = class.per_peer_limit(),
5347 "Audit responder request admitted"
5348 );
5349 let bootstrapping = *ctx.is_bootstrapping.read().await;
5350 let dispatch_latency = received_at.elapsed();
5351 audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5352 debug!(
5353 audit_type = "digest_responder",
5354 dispatch_latency_ms = dispatch_latency.as_millis(),
5355 source = %source,
5356 "Audit challenge dispatch latency measured"
5357 );
5358 let storage = Arc::clone(&ctx.storage);
5359 let p2p_node = Arc::clone(&ctx.p2p_node);
5360 let source = *source;
5361 let request_id = msg.request_id;
5362 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5363 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5364 ctx.detached_task_tracker.spawn(async move {
5365 let _guard = guard; // global permit + per-peer slot, held until done
5366 let worker_started = Instant::now();
5367 match handle_audit_challenge_msg(
5368 &source,
5369 &challenge,
5370 &storage,
5371 &p2p_node,
5372 bootstrapping,
5373 ReplyRoute {
5374 request_id,
5375 rr_message_id: rr_message_id.as_deref(),
5376 protocol: REPLICATION_PROTOCOL_ID,
5377 },
5378 )
5379 .await
5380 {
5381 Ok(completion) => log_audit_responder_completion(
5382 &responder_metrics,
5383 source,
5384 class,
5385 "responsible",
5386 challenge.challenge_id,
5387 challenge.keys.len(),
5388 completion.response_kind,
5389 completion.sent,
5390 received_at,
5391 worker_started,
5392 completion.processing,
5393 completion.response_send,
5394 ),
5395 Err(e) => debug!("Audit challenge from {source} error: {e}"),
5396 }
5397 });
5398 Ok(())
5399 }
5400 ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5401 // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5402 // responder rebuilds the WHOLE nonce-selected subtree, reading every
5403 // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5404 // detached task so this serial message loop is never blocked on disk
5405 // I/O — otherwise one audit stalls all replication traffic (§5).
5406 //
5407 // A bounded, flood-fair admission restores backpressure (codex#1 +
5408 // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5409 // we drop this challenge. Subtree auditors grace timeout
5410 // non-responses, so capacity drops throttle flooders without turning
5411 // into trust penalties (and one source cannot starve other peers,
5412 // since its share is capped per-peer).
5413 let class = AuditResponderClass::Subtree;
5414 info!(
5415 "Audit challenge received: kind=subtree source={source} request_response={}",
5416 rr_message_id.is_some(),
5417 );
5418 // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5419 // so it uses its own tight admission pool + per-peer rate cooldown,
5420 // separate from the light responsible/slice audits, and a miss silently
5421 // drops (subtree auditors grace timeouts).
5422 let Some(guard) = ctx.subtree_round1.admit(source).await else {
5423 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5424 warn!(
5425 target: "ant_node::replication::audit_responder",
5426 event = "admission_dropped",
5427 kind = "subtree",
5428 responder_class = class.as_str(),
5429 source = %source,
5430 challenge_id = challenge.challenge_id,
5431 request_response = rr_message_id.is_some(),
5432 dispatch_ms = received_at.elapsed().as_millis(),
5433 reason = "heavy_pool_cooldown_or_work_budget",
5434 "Audit responder admission dropped"
5435 );
5436 return Ok(());
5437 };
5438 let admission_global_inflight = guard.global_inflight;
5439 let admission_peer_inflight = guard.peer_inflight;
5440 ctx.audit_responder_metrics.record_admitted(
5441 *source,
5442 admission_global_inflight,
5443 admission_peer_inflight,
5444 );
5445 info!(
5446 target: "ant_node::replication::audit_responder",
5447 event = "admitted",
5448 kind = "subtree",
5449 responder_class = class.as_str(),
5450 source = %source,
5451 challenge_id = challenge.challenge_id,
5452 request_response = rr_message_id.is_some(),
5453 dispatch_ms = received_at.elapsed().as_millis(),
5454 global_inflight = admission_global_inflight,
5455 global_limit = ctx.subtree_round1.max_concurrent,
5456 peer_inflight = admission_peer_inflight,
5457 peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5458 "Audit responder request admitted"
5459 );
5460 let bootstrapping = *ctx.is_bootstrapping.read().await;
5461 let storage = Arc::clone(&ctx.storage);
5462 let p2p_node = Arc::clone(&ctx.p2p_node);
5463 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5464 let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5465 let source = *source;
5466 let request_id = msg.request_id;
5467 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5468 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5469 let subtree_round1 = ctx.subtree_round1.clone();
5470 ctx.detached_task_tracker.spawn(async move {
5471 let _guard = guard; // global permit + per-peer slot, held until done
5472 let worker_started = Instant::now();
5473 let processing_started = Instant::now();
5474 let storage_commitment_audit::Round1Work {
5475 response,
5476 content_bytes,
5477 corrupt_keys,
5478 } = storage_commitment_audit::handle_subtree_challenge_measured_with_pointers(
5479 &challenge,
5480 &storage,
5481 pointer_store.as_ref(),
5482 p2p_node.peer_id(),
5483 bootstrapping,
5484 Some(&my_commitment_state),
5485 )
5486 .await;
5487 let processing = processing_started.elapsed();
5488 // Committed chunks this proof found rotted go to the chunk store's
5489 // single recheck worker. Queueing never waits, so no number of
5490 // audits over a rotted chunk can pile up cleanup work outside this
5491 // task's admission.
5492 storage.report_corrupt(&corrupt_keys);
5493 // Charge the work actually done, on EVERY outcome.
5494 //
5495 // This used to charge only the `Proof` arm, reasoning that the
5496 // rejecting paths either read nothing or reflected this node's
5497 // own broken storage. The second half of that was wrong: a
5498 // retained commitment containing one unreadable key still costs
5499 // a full run of reads and keyed-BLAKE3 passes over every leaf
5500 // before it, and then rejects. An attacker who finds such a
5501 // commitment could replay subtrees over it indefinitely for
5502 // free. The per-peer cooldown does not catch that either, since
5503 // it is escapable by rotating identity — the responder-wide
5504 // budget is the only bound that applies, so it has to see the
5505 // work. A zero charge is a no-op, so the untouched paths are
5506 // unaffected.
5507 subtree_round1.charge_work(content_bytes).await;
5508 // A round-1 proof authorizes exactly one matching round 2: open a
5509 // single-use session so a slice challenge cannot be served without
5510 // a live round-1 exchange.
5511 let mut response = response;
5512 if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5513 {
5514 let opened = subtree_round1
5515 .open_session(
5516 source,
5517 challenge.challenge_id,
5518 challenge.expected_commitment_hash,
5519 challenge.nonce,
5520 storage_commitment_audit::pointer_bindings(&response),
5521 )
5522 .await;
5523 // A proof round 2 could not be answered for is not sent.
5524 // The node says so instead, as for a local read error: the
5525 // auditor's timeout lane, with no trust penalty, where
5526 // silence would read as a peer that did not answer
5527 // (ADR-0019).
5528 if !opened {
5529 protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5530 warn!(
5531 target: "ant_node::replication::audit_responder",
5532 event = "admission_dropped",
5533 kind = "subtree",
5534 responder_class = class.as_str(),
5535 source = %source,
5536 challenge_id = challenge.challenge_id,
5537 request_response = rr_message_id.is_some(),
5538 reason = "pointer_binding_budget",
5539 "Audit responder admission dropped"
5540 );
5541 response = crate::replication::protocol::SubtreeAuditResponse::Rejected {
5542 challenge_id: challenge.challenge_id,
5543 kind: protocol::RejectKind::Transient,
5544 reason: "pointer binding budget full".to_string(),
5545 };
5546 }
5547 }
5548 let response_kind = subtree_audit_response_kind(&response);
5549 let work_items = subtree_audit_response_work_items(&response);
5550 let response_send_started = Instant::now();
5551 let sent = send_replication_response_checked(
5552 &source,
5553 &p2p_node,
5554 request_id,
5555 ReplicationMessageBody::SubtreeAuditResponse(response),
5556 rr_message_id.as_deref(),
5557 None,
5558 )
5559 .await;
5560 let response_send = response_send_started.elapsed();
5561 log_audit_responder_completion(
5562 &responder_metrics,
5563 source,
5564 class,
5565 "subtree",
5566 challenge.challenge_id,
5567 work_items,
5568 response_kind,
5569 sent,
5570 received_at,
5571 worker_started,
5572 processing,
5573 response_send,
5574 );
5575 });
5576 Ok(())
5577 }
5578 ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5579 // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5580 // block of each auditor-selected spot-check key with a Bao verified
5581 // slice + nonced block-tree opening. Reads chunk bytes from disk to
5582 // build the proofs, so it runs off the serial loop under the light
5583 // audit pool's global and per-peer ceilings.
5584 let class = AuditResponderClass::Byte;
5585 info!(
5586 "Audit challenge received: kind=slice source={source} request_response={}",
5587 rr_message_id.is_some(),
5588 );
5589 let (guard, pointer_bindings) = match admit_slice_challenge(
5590 &ctx.audit_responder_semaphore,
5591 &ctx.audit_responder_inflight,
5592 &ctx.subtree_round1,
5593 source,
5594 &challenge,
5595 )
5596 .await
5597 {
5598 SliceAdmission::Admitted(guard, pointer_bindings) => (guard, pointer_bindings),
5599 SliceAdmission::Capacity(failure) => {
5600 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5601 audit_metrics::record_admission_drop(class);
5602 ctx.audit_responder_metrics
5603 .record_drop(*source, failure.reason.into());
5604 warn!(
5605 target: "ant_node::replication::audit_responder",
5606 event = "admission_dropped",
5607 kind = "byte",
5608 responder_class = class.as_str(),
5609 source = %source,
5610 challenge_id = challenge.challenge_id,
5611 key_count = challenge.openings.len(),
5612 request_response = rr_message_id.is_some(),
5613 dispatch_ms = received_at.elapsed().as_millis(),
5614 reason = failure.reason.as_str(),
5615 global_inflight = failure.global_inflight,
5616 global_limit = failure.global_limit,
5617 peer_inflight = failure.peer_inflight,
5618 peer_limit = failure.peer_limit,
5619 "Audit responder admission dropped"
5620 );
5621 return Ok(());
5622 }
5623 // No live round-1 session: reply with a cheap `Transient` rejection
5624 // rather than dropping silently. Sessions are ephemeral (an honest
5625 // responder that restarts between rounds loses its session), and an
5626 // unanswered `send_request` would make saorsa-core record a
5627 // transport trust failure against that honest responder — an
5628 // ongoing effect, not just a rollout-window one. A `Transient`
5629 // reply routes the auditor to the graced timeout lane (no trust
5630 // penalty; the responder re-earns pinned credit on the next audit)
5631 // and does no chunk work, so it is not a DoS lever.
5632 SliceAdmission::NoSession => {
5633 protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5634 debug!(
5635 "Slice challenge without a live round-1 session source={source} \
5636 challenge_id={} → Transient reject",
5637 challenge.challenge_id
5638 );
5639 send_replication_response_checked(
5640 source,
5641 &ctx.p2p_node,
5642 msg.request_id,
5643 ReplicationMessageBody::SubtreeSliceResponse(
5644 protocol::SubtreeSliceResponse::Rejected {
5645 challenge_id: challenge.challenge_id,
5646 kind: protocol::RejectKind::Transient,
5647 reason: "no live round-1 session".to_string(),
5648 },
5649 ),
5650 rr_message_id,
5651 None,
5652 )
5653 .await;
5654 return Ok(());
5655 }
5656 };
5657 let admission_global_inflight = guard.global_inflight;
5658 let admission_peer_inflight = guard.peer_inflight;
5659 ctx.audit_responder_metrics.record_admitted(
5660 *source,
5661 admission_global_inflight,
5662 admission_peer_inflight,
5663 );
5664 info!(
5665 target: "ant_node::replication::audit_responder",
5666 event = "admitted",
5667 kind = "byte",
5668 responder_class = class.as_str(),
5669 source = %source,
5670 challenge_id = challenge.challenge_id,
5671 key_count = challenge.openings.len(),
5672 request_response = rr_message_id.is_some(),
5673 dispatch_ms = received_at.elapsed().as_millis(),
5674 global_inflight = admission_global_inflight,
5675 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5676 peer_inflight = admission_peer_inflight,
5677 peer_limit = class.per_peer_limit(),
5678 "Audit responder request admitted"
5679 );
5680 let bootstrapping = *ctx.is_bootstrapping.read().await;
5681 let storage = Arc::clone(&ctx.storage);
5682 let p2p_node = Arc::clone(&ctx.p2p_node);
5683 let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5684 let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5685 let source = *source;
5686 let request_id = msg.request_id;
5687 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5688 let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5689 ctx.detached_task_tracker.spawn(async move {
5690 let _guard = guard; // global permit + per-peer slot, held until done
5691 let worker_started = Instant::now();
5692 let processing_started = Instant::now();
5693 let response =
5694 storage_commitment_audit::handle_subtree_slice_challenge_with_pointer_bindings(
5695 &challenge,
5696 &storage,
5697 pointer_store.as_ref(),
5698 &pointer_bindings,
5699 p2p_node.peer_id(),
5700 bootstrapping,
5701 Some(&my_commitment_state),
5702 )
5703 .await;
5704 let processing = processing_started.elapsed();
5705 let response_kind = subtree_slice_response_kind(&response);
5706 let response_send_started = Instant::now();
5707 let sent = send_replication_response_checked(
5708 &source,
5709 &p2p_node,
5710 request_id,
5711 ReplicationMessageBody::SubtreeSliceResponse(response),
5712 rr_message_id.as_deref(),
5713 None,
5714 )
5715 .await;
5716 let response_send = response_send_started.elapsed();
5717 log_audit_responder_completion(
5718 &responder_metrics,
5719 source,
5720 class,
5721 "byte",
5722 challenge.challenge_id,
5723 challenge.openings.len(),
5724 response_kind,
5725 sent,
5726 received_at,
5727 worker_started,
5728 processing,
5729 response_send,
5730 );
5731 });
5732 Ok(())
5733 }
5734 ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5735 // ADR-0004: answer a commitment-by-pin fetch from the retained set
5736 // only. `lookup_by_hash` is an allocation-light read over the
5737 // bounded slot set; it returns the live current commitment or any
5738 // still-answerable recently-gossiped/quoted one. A miss is reported
5739 // as `NotRetained` (graced, never confirmed) rather than an error,
5740 // so an aged-out pin can never brand an honest node.
5741 //
5742 // Reuse the audit-responder admission guard (global ceiling + per-peer
5743 // cap) so a flood of fetches cannot drive unbounded commitment
5744 // clone/encode/send work; over-limit is dropped, which the fetching
5745 // peer graces exactly like a missed audit response.
5746 let class = AuditResponderClass::CommitmentPin;
5747 let guard = match admit_audit_responder(
5748 &ctx.audit_responder_semaphore,
5749 &ctx.audit_responder_inflight,
5750 source,
5751 class,
5752 )
5753 .await
5754 {
5755 Ok(guard) => guard,
5756 Err(failure) => {
5757 audit_metrics::record_admission_drop(class);
5758 ctx.audit_responder_metrics
5759 .record_drop(*source, failure.reason.into());
5760 warn!(
5761 target: "ant_node::replication::audit_responder",
5762 event = "admission_dropped",
5763 kind = "commitment_pin",
5764 responder_class = class.as_str(),
5765 source = %source,
5766 challenge_id = msg.request_id,
5767 request_response = rr_message_id.is_some(),
5768 dispatch_ms = received_at.elapsed().as_millis(),
5769 reason = failure.reason.as_str(),
5770 global_inflight = failure.global_inflight,
5771 global_limit = failure.global_limit,
5772 peer_inflight = failure.peer_inflight,
5773 peer_limit = failure.peer_limit,
5774 "Audit responder admission dropped"
5775 );
5776 return Ok(());
5777 }
5778 };
5779 ctx.audit_responder_metrics.record_admitted(
5780 *source,
5781 guard.global_inflight,
5782 guard.peer_inflight,
5783 );
5784 info!(
5785 target: "ant_node::replication::audit_responder",
5786 event = "admitted",
5787 kind = "commitment_pin",
5788 responder_class = class.as_str(),
5789 source = %source,
5790 challenge_id = msg.request_id,
5791 request_response = rr_message_id.is_some(),
5792 dispatch_ms = received_at.elapsed().as_millis(),
5793 global_inflight = guard.global_inflight,
5794 global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5795 peer_inflight = guard.peer_inflight,
5796 peer_limit = class.per_peer_limit(),
5797 "Audit responder request admitted"
5798 );
5799 let worker_started = Instant::now();
5800 let processing_started = Instant::now();
5801 let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5802 protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5803 |built| protocol::GetCommitmentByPinResponse::Found {
5804 commitment: built.commitment().clone(),
5805 },
5806 );
5807 let processing = processing_started.elapsed();
5808 let response_kind = commitment_pin_response_kind(&response);
5809 let response_send_started = Instant::now();
5810 let sent = send_replication_response_checked(
5811 source,
5812 &ctx.p2p_node,
5813 msg.request_id,
5814 ReplicationMessageBody::GetCommitmentByPinResponse(response),
5815 rr_message_id,
5816 None,
5817 )
5818 .await;
5819 let response_send = response_send_started.elapsed();
5820 log_audit_responder_completion(
5821 &ctx.audit_responder_metrics,
5822 *source,
5823 class,
5824 "commitment_pin",
5825 msg.request_id,
5826 1,
5827 response_kind,
5828 sent,
5829 received_at,
5830 worker_started,
5831 processing,
5832 response_send,
5833 );
5834 drop(guard);
5835 Ok(())
5836 }
5837 // Pointers (ADR-0016). A node that does not store pointers ignores
5838 // them, and so is never marked capable and never asked anything.
5839 ReplicationMessageBody::PointerFreshOffer(offer) => {
5840 if let Some(pointers) = &ctx.pointers {
5841 pointers.accept_offer_detached(*source, offer);
5842 }
5843 Ok(())
5844 }
5845 ReplicationMessageBody::PointerHints(hints) => {
5846 if let Some(pointers) = &ctx.pointers {
5847 pointers.handle_hints(*source, hints.hints).await;
5848 }
5849 Ok(())
5850 }
5851 ReplicationMessageBody::PointerFetchRequest(request) => {
5852 if let Some(pointers) = &ctx.pointers {
5853 pointers
5854 .serve_fetch_detached(
5855 *source,
5856 request,
5857 msg.request_id,
5858 rr_message_id.map(ToOwned::to_owned),
5859 )
5860 .await;
5861 }
5862 Ok(())
5863 }
5864 ReplicationMessageBody::PointerStateRequest(request) => {
5865 if let Some(pointers) = &ctx.pointers {
5866 pointers
5867 .serve_state_detached(
5868 *source,
5869 request,
5870 msg.request_id,
5871 rr_message_id.map(ToOwned::to_owned),
5872 )
5873 .await;
5874 }
5875 Ok(())
5876 }
5877 // Response messages are handled by their respective request initiators.
5878 ReplicationMessageBody::FreshReplicationResponse(_)
5879 | ReplicationMessageBody::NeighborSyncResponse(_)
5880 | ReplicationMessageBody::VerificationResponse(_)
5881 | ReplicationMessageBody::FetchResponse(_)
5882 | ReplicationMessageBody::AuditResponse(_)
5883 | ReplicationMessageBody::SubtreeAuditResponse(_)
5884 | ReplicationMessageBody::SubtreeSliceResponse(_)
5885 | ReplicationMessageBody::GetCommitmentByPinResponse(_)
5886 | ReplicationMessageBody::PointerFetchResponse(_)
5887 | ReplicationMessageBody::PointerStateResponse(_) => Ok(()),
5888 }
5889}
5890
5891// ---------------------------------------------------------------------------
5892// Per-message-type handlers
5893// ---------------------------------------------------------------------------
5894
5895/// Verify a payment proof, yielding early if the engine is shutting down.
5896///
5897/// Returns `None` when shutdown won the race, meaning no verdict was reached
5898/// and the caller must abandon the message without storing or penalising.
5899///
5900/// Payment verification is pure network I/O — an EVM round trip and, on the
5901/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5902/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5903/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5904/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5905/// is guaranteed to end.
5906///
5907/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5908/// dropping its awaiter would detach a live storage operation and break the
5909/// very contract the unbounded wait exists to uphold.
5910async fn verify_payment_until_shutdown(
5911 payment_verifier: &Arc<PaymentVerifier>,
5912 key: &XorName,
5913 proof_of_payment: &[u8],
5914 context: VerificationContext,
5915 shutdown: &CancellationToken,
5916) -> Option<Result<crate::payment::PaymentStatus>> {
5917 tokio::select! {
5918 () = shutdown.cancelled() => None,
5919 result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5920 Some(result)
5921 }
5922 }
5923}
5924
5925/// A fresh offer rejected on payload shape alone.
5926struct FreshOfferRejection {
5927 /// Wire-visible reason returned to the sender.
5928 reason: String,
5929 /// Whether the sender is charged for it. Reserved for offers no honest
5930 /// node would construct, so an ordinary capacity refusal stays free.
5931 penalise: bool,
5932}
5933
5934/// Reject a fresh offer on payload shape, or return `None` to admit it.
5935///
5936/// Pure and non-blocking by construction: these are the checks answerable from
5937/// the payload alone, run on the serial message loop *before* the in-flight
5938/// claim and the admission permit, so a malformed offer can neither lock an
5939/// honest offer out of its key nor occupy one of the scarce
5940/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5941/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5942/// verification — stays on the worker.
5943///
5944/// The content-address hash is deliberately included despite costing real CPU
5945/// on the loop: it is what makes the entry below *earned* rather than merely
5946/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5947/// arrive at link speed, so a flooder can never make this loop hash faster than
5948/// it can deliver the bytes, and delivering them already cost it more than the
5949/// hash costs us. The receive path has in any case already deserialised the
5950/// same buffer.
5951///
5952/// Every rejection here is penalised. These are the conditions no honest sender
5953/// can produce — an absent, undersized, oversized, or non-matching payload — as
5954/// distinct from a capacity refusal, which is this node's own state and stays
5955/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5956/// proof that fails to verify may simply have been read against a lagging chain
5957/// view, and penalising that would charge honest senders in correlated bursts.
5958fn fresh_offer_structural_rejection(
5959 key: &XorName,
5960 data: &[u8],
5961 proof_of_payment: &[u8],
5962) -> Option<FreshOfferRejection> {
5963 // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5964 // and an absent proof is the cheapest possible slot-filler, so this is the
5965 // first thing checked.
5966 if proof_of_payment.is_empty() {
5967 return Some(FreshOfferRejection {
5968 reason: "Missing proof of payment".to_string(),
5969 penalise: true,
5970 });
5971 }
5972
5973 // Bound the proof before it can be queued. The verifier applies the same
5974 // limits, but only once the offer reaches a worker — too late here, because
5975 // an entry retains a proof per queued sender, and a proof is capped on the
5976 // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5977 // a byte of data and a 10 MiB "proof" would be admitted, and
5978 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5979 // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5980 // admission bound exists to enforce.
5981 if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5982 return Some(FreshOfferRejection {
5983 reason: format!(
5984 "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5985 proof_of_payment.len(),
5986 ),
5987 penalise: true,
5988 });
5989 }
5990 if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5991 return Some(FreshOfferRejection {
5992 reason: format!(
5993 "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5994 proof_of_payment.len(),
5995 ),
5996 penalise: true,
5997 });
5998 }
5999
6000 // Enforce chunk size invariant: the normal PUT path rejects data larger
6001 // than MAX_CHUNK_SIZE; the replication receive path must do the same to
6002 // prevent peers from pushing oversized records through replication.
6003 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
6004 return Some(FreshOfferRejection {
6005 reason: format!(
6006 "Data size {} exceeds maximum chunk size {}",
6007 data.len(),
6008 crate::ant_protocol::MAX_CHUNK_SIZE,
6009 ),
6010 penalise: true,
6011 });
6012 }
6013
6014 // Mirror the normal PUT path: the advertised key must be the content
6015 // address of the supplied bytes. Ordered last so an oversized payload is
6016 // refused without being hashed.
6017 //
6018 // This is the check that makes the entry safe to open, and safe for later
6019 // offers to be folded into. Until it passes, the sender has only *asserted*
6020 // an association between the key and the bytes. Opening an entry on an
6021 // assertion would let any peer that knows a key — every recipient of its
6022 // `PaidNotify`, not just the close group — seize it with junk; folding a
6023 // later offer into an entry on an assertion would be worse still, since the
6024 // handler tries each queued proof against the *opener's* bytes and would be
6025 // storing bytes nobody offered for that proof.
6026 let computed_key = crate::client::compute_address(data);
6027 if computed_key != *key {
6028 return Some(FreshOfferRejection {
6029 reason: format!(
6030 "Content address mismatch: expected {}, computed {}",
6031 hex::encode(key),
6032 hex::encode(computed_key),
6033 ),
6034 penalise: true,
6035 });
6036 }
6037
6038 None
6039}
6040
6041/// Tell `source` its offer for `key` was not taken.
6042///
6043/// Note the sender does not currently read this: `fresh::send_fresh_offers` uses
6044/// one-way `send_message`, so the refusal is observed only as a later absence by
6045/// the delayed possession check. Recorded in ADR-0005 as a known gap.
6046async fn refuse_fresh_offer(
6047 source: &PeerId,
6048 key: XorName,
6049 reason: String,
6050 ctx: &ReplicationMessageHandlerContext,
6051 request_id: u64,
6052 rr_message_id: Option<&str>,
6053) {
6054 send_replication_response(
6055 source,
6056 &ctx.p2p_node,
6057 request_id,
6058 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6059 key,
6060 reason,
6061 }),
6062 rr_message_id,
6063 )
6064 .await;
6065}
6066
6067/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
6068/// the sender when the defect is one no honest node could produce.
6069///
6070/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
6071/// two say opposite things: this is the sender's fault, that one is ours.
6072async fn refuse_malformed_fresh_offer(
6073 source: &PeerId,
6074 key: XorName,
6075 rejection: FreshOfferRejection,
6076 ctx: &ReplicationMessageHandlerContext,
6077 request_id: u64,
6078 rr_message_id: Option<&str>,
6079) {
6080 if rejection.penalise {
6081 warn!(
6082 "Rejecting fresh offer for key {} from {source}: {}",
6083 hex::encode(key),
6084 rejection.reason
6085 );
6086 ctx.p2p_node
6087 .report_trust_event(
6088 source,
6089 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6090 )
6091 .await;
6092 } else {
6093 debug!(
6094 "Fresh offer for {} from {source} refused before admission: {}",
6095 hex::encode(key),
6096 rejection.reason
6097 );
6098 }
6099 refuse_fresh_offer(
6100 source,
6101 key,
6102 rejection.reason,
6103 ctx,
6104 request_id,
6105 rr_message_id,
6106 )
6107 .await;
6108}
6109
6110/// Tell senders whose proofs joined an entry that was torn down before a handler
6111/// ever ran for it.
6112///
6113/// Only reachable in the window between opening an entry and failing to take an
6114/// admission permit. Their proofs are answered rather than dropped with the
6115/// entry, so the refusal count reflects what actually happened.
6116async fn refuse_stranded_fresh_offers(
6117 key: XorName,
6118 stranded: Vec<FreshOfferAttempt>,
6119 ctx: &ReplicationMessageHandlerContext,
6120) {
6121 for attempt in stranded {
6122 refuse_fresh_offer(
6123 &attempt.source,
6124 key,
6125 "Receiver at fresh-offer capacity".to_string(),
6126 ctx,
6127 attempt.request_id,
6128 attempt.rr_message_id.as_deref(),
6129 )
6130 .await;
6131 }
6132}
6133
6134/// Admit a fresh offer for handling on a worker, or refuse it.
6135///
6136/// This runs on the serial non-audit message loop, so it must stay cheap: every
6137/// path here is a set insert, a permit try, or a small response send. The offer
6138/// itself — an on-chain payment verification and a multi-MiB write — always
6139/// runs on a tracked worker task, never inline, because stalling this loop backs
6140/// up the inbound queue and ultimately drops replication messages wholesale.
6141///
6142/// Admission is bounded **per source** as well as globally
6143/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
6144/// hold every slot, and since a refusal is later read as absence by the
6145/// sender's delayed possession check, the resulting refusals land as
6146/// audit-severity penalties on this node rather than on the flooder.
6147///
6148/// The structurally-invalid checks run **before** the entry is opened and before
6149/// the permit is taken, so junk can neither seize a key nor occupy a slot for
6150/// the duration of a payment verification.
6151///
6152/// Only the offer that *opens* an entry costs a permit and a worker. Later
6153/// offers for the same key contribute their proof and are answered by whatever
6154/// the opener's handler concludes, which is what keeps the routine
6155/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
6156/// one verification per key.
6157async fn dispatch_fresh_offer(
6158 source: PeerId,
6159 offer: protocol::FreshReplicationOffer,
6160 ctx: &ReplicationMessageHandlerContext,
6161 request_id: u64,
6162 received_at: Instant,
6163 rr_message_id: Option<&str>,
6164) -> Result<()> {
6165 if let Some(rejection) =
6166 fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
6167 {
6168 refuse_malformed_fresh_offer(
6169 &source,
6170 offer.key,
6171 rejection,
6172 ctx,
6173 request_id,
6174 rr_message_id,
6175 )
6176 .await;
6177 return Ok(());
6178 }
6179
6180 // Join the work already in flight for this key before taking an admission
6181 // permit, so the duplicates a single client PUT produces cost one permit
6182 // between them rather than one each.
6183 //
6184 // Reaching this point means `fresh_offer_structural_rejection` has confirmed
6185 // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
6186 // already held for the key. That is what lets its payload be dropped here
6187 // and only its proof retained: the handler will try that proof against the
6188 // bytes it already has.
6189 let key = offer.key;
6190 let admission_outcome = FreshOfferEntryGuard::admit(
6191 &ctx.fresh_offer_in_flight,
6192 offer,
6193 source,
6194 request_id,
6195 rr_message_id.map(ToOwned::to_owned),
6196 received_at,
6197 );
6198 let mut entry = match admission_outcome {
6199 FreshOfferAdmission::Opened(entry) => entry,
6200 FreshOfferAdmission::Joined => {
6201 // No response yet: this proof has not been judged. The handler that
6202 // owns the key answers every queued sender once it settles.
6203 debug!(
6204 "Fresh offer for {} from {source} queued behind the handler already \
6205 holding the key",
6206 hex::encode(key)
6207 );
6208 return Ok(());
6209 }
6210 // Surplus, not suspect: the proofs already queued are enough to place
6211 // the record, so neither case is charged as misbehaviour.
6212 surplus => {
6213 debug!(
6214 "Fresh offer for {} from {source} refused: {}",
6215 hex::encode(key),
6216 surplus.surplus_reason()
6217 );
6218 refuse_fresh_offer(
6219 &source,
6220 key,
6221 "Duplicate offer already in flight".to_string(),
6222 ctx,
6223 request_id,
6224 rr_message_id,
6225 )
6226 .await;
6227 return Ok(());
6228 }
6229 };
6230
6231 let admission = match admit_bounded_responder(
6232 &ctx.fresh_offer_admission_semaphore,
6233 &ctx.fresh_offer_responder_inflight,
6234 &source,
6235 FRESH_OFFER_MAX_OUTSTANDING,
6236 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
6237 )
6238 .await
6239 {
6240 Ok(guard) => guard,
6241 Err(failure) => {
6242 audit_metrics::record_responder_admission_drop(
6243 ReplicationResponderClass::FreshOffer,
6244 failure.reason.into(),
6245 );
6246 // WARN, not DEBUG: a healthy node should never refuse a legitimate
6247 // fresh offer. The sender does not read this refusal, so it
6248 // resurfaces as a missing key at the delayed possession check and
6249 // is charged to US at audit severity. Log the binding ceiling
6250 // locally; the wire reason stays generic so a probing peer cannot
6251 // map out this node's live occupancy.
6252 warn!(
6253 responder_class = "fresh_offer",
6254 source = %source,
6255 key = %hex::encode(key),
6256 "Fresh offer refused at admission; this node will be penalised for the \
6257 resulting absence: {failure}"
6258 );
6259 // Release the key explicitly rather than on drop, so the next offer
6260 // opens a fresh entry rather than queueing behind a handler that was
6261 // never spawned — and so any proof that joined in the window between
6262 // opening the entry and failing here is answered rather than
6263 // discarded with it.
6264 let stranded = entry.release();
6265 refuse_fresh_offer(
6266 &source,
6267 key,
6268 "Receiver at fresh-offer capacity".to_string(),
6269 ctx,
6270 request_id,
6271 rr_message_id,
6272 )
6273 .await;
6274 refuse_stranded_fresh_offers(key, stranded, ctx).await;
6275 return Ok(());
6276 }
6277 };
6278
6279 let ctx = ctx.clone();
6280 // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
6281 // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
6282 // those references be released before the caller reopens the environment.
6283 ctx.detached_task_tracker
6284 .clone()
6285 .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
6286 Ok(())
6287}
6288
6289/// Body of one tracked fresh-offer worker: drive one key to a verdict.
6290///
6291/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
6292/// A started handler is never cancelled: `storage.put()` awaits
6293/// `spawn_blocking`, and dropping that awaiter would detach the live storage
6294/// transaction. Shutdown responsiveness comes from the closed worker semaphore
6295/// and from `handle_fresh_offer` racing the token around payment verification.
6296///
6297/// Works down the key's queued proofs rather than judging the key on the first
6298/// one. A proof that fails to establish payment disqualifies its *sender*, not
6299/// the record: the bytes are content-addressed and identical across every offer,
6300/// so the next sender's proof is tried against the copy already in hand — no
6301/// second payload, no second permit, no refetch. Only when a failure is about
6302/// the key itself (not responsible, no capacity, shutting down) does rotating
6303/// become pointless, because every remaining proof would meet the same wall.
6304async fn run_fresh_offer_worker(
6305 key: XorName,
6306 mut entry: Box<FreshOfferEntryGuard>,
6307 ctx: ReplicationMessageHandlerContext,
6308 admission: ResponderGuard,
6309) {
6310 // The admission permit is released on completion, freeing the payload's
6311 // memory budget and the opening source's per-peer share. The entry releases
6312 // the key itself, either as the queue empties or on drop.
6313 let _admission = admission;
6314 let received_at = entry.received_at();
6315 // Wait for a worker slot here rather than in the caller. The worker bound
6316 // caps concurrent EVM and storage pressure; making the message loop wait on
6317 // it is what put that pressure back on the loop.
6318 //
6319 // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
6320 // path for offers still queued behind a worker when the engine stops — not
6321 // dead code.
6322 let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
6323 .acquire_owned()
6324 .await
6325 else {
6326 debug!(
6327 "Fresh offer for {} dropped: worker pool shut down",
6328 hex::encode(key)
6329 );
6330 return;
6331 };
6332 // Fresh offers are fire-and-forget (`send_message`), so there is no
6333 // requester deadline to honour and a late store is still genuinely useful.
6334 // The threshold is the point past which the offer has already cost us what
6335 // it was going to cost: the possession check (ADR-0003) has run by then and
6336 // charged the absence to this node, and it does not re-offer the key —
6337 // repair comes later from neighbor sync. Shedding here trades a copy that
6338 // would have arrived after the penalty for the multi-MiB payload it is
6339 // holding, and keeps a backlog from outliving its own admission bound.
6340 //
6341 // Note this is a memory-pressure decision, not a redundancy one: the copy
6342 // is late, not useless, so on a node with headroom finishing it would still
6343 // beat waiting for neighbor sync.
6344 if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
6345 debug!(
6346 responder_class = "fresh_offer",
6347 key = %hex::encode(key),
6348 request_age_ms = received_at.elapsed().as_millis(),
6349 "Superseded fresh offer shed at dequeue"
6350 );
6351 return;
6352 }
6353
6354 let mut verdict = FreshOfferOutcome::Abandoned;
6355 while let Some(attempt) = entry.next_attempt() {
6356 match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
6357 Ok(outcome) => {
6358 verdict = outcome;
6359 match outcome {
6360 // Settled: the record is down and every remaining sender
6361 // wanted exactly that. Abandoned: the key cannot be placed
6362 // by anyone right now, so the proofs behind this one would
6363 // fail identically. Either way there is nothing left to try.
6364 FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
6365 // This sender's claim to have paid did not hold up. Say so
6366 // to that sender alone and try the next proof.
6367 FreshOfferOutcome::ProofRejected => {}
6368 }
6369 }
6370 Err(e) => {
6371 debug!(
6372 "Fresh replication offer for {} from {} error: {e}",
6373 hex::encode(key),
6374 attempt.source
6375 );
6376 verdict = FreshOfferOutcome::Abandoned;
6377 break;
6378 }
6379 }
6380 }
6381
6382 // Answer the senders whose proofs were never reached. A stored record is
6383 // what they were asking for, so it is an acceptance even though their own
6384 // proof went untested.
6385 let unreached = entry.release();
6386 if unreached.is_empty() {
6387 return;
6388 }
6389 let response = match verdict {
6390 FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
6391 FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
6392 FreshReplicationResponse::Rejected {
6393 key,
6394 reason: "Record could not be stored from any offered proof".to_string(),
6395 }
6396 }
6397 };
6398 for attempt in unreached {
6399 send_replication_response(
6400 &attempt.source,
6401 &ctx.p2p_node,
6402 attempt.request_id,
6403 ReplicationMessageBody::FreshReplicationResponse(response.clone()),
6404 attempt.rr_message_id.as_deref(),
6405 )
6406 .await;
6407 }
6408}
6409
6410/// What one proof concluded, and whether another proof for the same key is worth
6411/// trying.
6412///
6413/// The distinction the worker acts on is *what the failure was about*. A
6414/// rejected proof is a statement about its sender; anything else is a statement
6415/// about the key or this node, which no other sender's proof can change.
6416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6417enum FreshOfferOutcome {
6418 /// The record is stored. The key is done.
6419 Settled,
6420 /// This proof did not establish payment. A different sender's proof for the
6421 /// same bytes may still succeed.
6422 ProofRejected,
6423 /// Nothing about this key can succeed right now — not responsible, no disk,
6424 /// shutting down, or a write that failed. Rotating repeats the failure.
6425 Abandoned,
6426}
6427
6428// A linear sequence of protocol steps — structural recheck, responsibility,
6429// capacity, payment, write — each with its own refusal response. Splitting it
6430// would scatter one decision across several functions.
6431#[allow(clippy::too_many_lines)]
6432async fn handle_fresh_offer(
6433 key: &XorName,
6434 data: &[u8],
6435 attempt: &FreshOfferAttempt,
6436 ctx: &ReplicationMessageHandlerContext,
6437) -> Result<FreshOfferOutcome> {
6438 let source = &attempt.source;
6439 let request_id = attempt.request_id;
6440 let rr_message_id = attempt.rr_message_id.as_deref();
6441 let p2p_node = &ctx.p2p_node;
6442 let config = &ctx.config;
6443 let self_id = *p2p_node.peer_id();
6444
6445 // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6446 // proof, bad proof size, oversized payload, content-address mismatch —
6447 // before opening the entry or taking an admission permit, so nothing
6448 // reaching a worker should trip them. Kept so the handler is correct in
6449 // isolation. Note this re-checks the *pairing* actually being used: these
6450 // bytes against this attempt's proof.
6451 if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6452 {
6453 if rejection.penalise {
6454 warn!(
6455 "Rejecting fresh offer for key {}: {}",
6456 hex::encode(key),
6457 rejection.reason
6458 );
6459 p2p_node
6460 .report_trust_event(
6461 source,
6462 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6463 )
6464 .await;
6465 }
6466 send_replication_response(
6467 source,
6468 p2p_node,
6469 request_id,
6470 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6471 key: *key,
6472 reason: rejection.reason,
6473 }),
6474 rr_message_id,
6475 )
6476 .await;
6477 // Structurally invalid is a fact about this attempt, not the key.
6478 return Ok(FreshOfferOutcome::ProofRejected);
6479 }
6480
6481 // Rule 7: check storage admission. Fresh chunk receivers accept across the
6482 // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6483 // the same width client PUTs use), not just the close group plus a small
6484 // margin (ADR-0003). During full-node shunning a healthy replica's routing
6485 // table may still list closer full nodes it hasn't evicted yet, ranking it
6486 // outside the narrow window in its own view; the wider accept window absorbs
6487 // that transient skew so the chunk still lands. Retention (pruning) stays at
6488 // `storage_admission_width`, so steady-state replication is unchanged.
6489 if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6490 {
6491 send_replication_response(
6492 source,
6493 p2p_node,
6494 request_id,
6495 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6496 key: *key,
6497 reason: "Not in storage-admission range for this key".to_string(),
6498 }),
6499 rr_message_id,
6500 )
6501 .await;
6502 // About the key and this node's place in the routing table, not about
6503 // the sender: every queued proof would be refused identically.
6504 return Ok(FreshOfferOutcome::Abandoned);
6505 }
6506
6507 // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6508 // never store this record, so reject it before the expensive payment
6509 // verification (EVM on-chain query / merkle pool work) rather than verifying
6510 // and only then failing at `storage.put` below. Reuses the cached capacity
6511 // check (passing results only, so freed space is detected promptly), and the
6512 // store path keeps its own check as defence-in-depth.
6513 if let Err(e) = ctx.storage.check_capacity() {
6514 info!(
6515 target: "ant_node::storage::disk_precheck",
6516 key = %hex::encode(key),
6517 "Rejecting fresh replication offer before payment verification: {e}"
6518 );
6519 send_replication_response(
6520 source,
6521 p2p_node,
6522 request_id,
6523 ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6524 key: *key,
6525 reason: e.to_string(),
6526 }),
6527 rr_message_id,
6528 )
6529 .await;
6530 // A full disk is this node's condition, not the sender's.
6531 return Ok(FreshOfferOutcome::Abandoned);
6532 }
6533
6534 // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6535 // part of the immediate write fan-out: this receiver is about to store the
6536 // record as if the client had PUT it here directly. Storage admission
6537 // was checked above before proof work. FreshReplication verification is
6538 // identical to ClientPut — store-strength cache semantics, paid-quote
6539 // issuer K-closeness checks for single-node proofs, merkle candidate
6540 // closeness for merkle proofs, and the same price-floor policy — the
6541 // distinct context only labels price-floor telemetry.
6542 let Some(verification) = verify_payment_until_shutdown(
6543 &ctx.payment_verifier,
6544 key,
6545 &attempt.proof_of_payment,
6546 fresh_offer_payment_context(),
6547 &ctx.shutdown,
6548 )
6549 .await
6550 else {
6551 debug!(
6552 "Fresh offer for {} from {source} abandoned: engine shutting down \
6553 during payment verification",
6554 hex::encode(key)
6555 );
6556 return Ok(FreshOfferOutcome::Abandoned);
6557 };
6558 match verification {
6559 Ok(status) if status.can_store() => {
6560 debug!("PoP validated for fresh offer key {}", hex::encode(key));
6561 }
6562 // The chain has no record of this payment. That is a statement about
6563 // *this sender's* proof, so the key rotates to the next one rather than
6564 // being written off — the whole point of queueing them.
6565 //
6566 // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6567 // not "definitively unpaid", so a lagging or reorganising chain view
6568 // renders honest senders indistinguishable from forgers, and penalising
6569 // would land on the entire close group at once. The structural checks in
6570 // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6571 // because those cannot be produced by an honest sender at all.
6572 Ok(_) => {
6573 debug!(
6574 "Fresh offer for {} from {source}: no payment found for this proof",
6575 hex::encode(key)
6576 );
6577 send_replication_response(
6578 source,
6579 p2p_node,
6580 request_id,
6581 ReplicationMessageBody::FreshReplicationResponse(
6582 FreshReplicationResponse::Rejected {
6583 key: *key,
6584 reason: "Payment verification failed: payment required".to_string(),
6585 },
6586 ),
6587 rr_message_id,
6588 )
6589 .await;
6590 return Ok(FreshOfferOutcome::ProofRejected);
6591 }
6592 // A verification *error* is usually ours — an unreachable or failing EVM
6593 // endpoint — so it is neither penalised nor treated as this sender's
6594 // fault. Another proof still gets its turn, since the next call may well
6595 // succeed against a recovered endpoint.
6596 Err(e) => {
6597 warn!("PoP verification error for key {}: {e}", hex::encode(key));
6598 send_replication_response(
6599 source,
6600 p2p_node,
6601 request_id,
6602 ReplicationMessageBody::FreshReplicationResponse(
6603 FreshReplicationResponse::Rejected {
6604 key: *key,
6605 reason: format!("Payment verification error: {e}"),
6606 },
6607 ),
6608 rr_message_id,
6609 )
6610 .await;
6611 return Ok(FreshOfferOutcome::ProofRejected);
6612 }
6613 }
6614
6615 // Rule 6: add to PaidForList.
6616 if let Err(e) = ctx.paid_list.insert(key).await {
6617 warn!("Failed to add key to PaidForList: {e}");
6618 }
6619
6620 // Store the record.
6621 match ctx.storage.put(key, data).await {
6622 Ok(_) => {
6623 send_replication_response(
6624 source,
6625 p2p_node,
6626 request_id,
6627 ReplicationMessageBody::FreshReplicationResponse(
6628 FreshReplicationResponse::Accepted { key: *key },
6629 ),
6630 rr_message_id,
6631 )
6632 .await;
6633 Ok(FreshOfferOutcome::Settled)
6634 }
6635 Err(e) => {
6636 send_replication_response(
6637 source,
6638 p2p_node,
6639 request_id,
6640 ReplicationMessageBody::FreshReplicationResponse(
6641 FreshReplicationResponse::Rejected {
6642 key: *key,
6643 reason: e.to_string(),
6644 },
6645 ),
6646 rr_message_id,
6647 )
6648 .await;
6649 // The payment was good and the write still failed, so this is local
6650 // storage trouble that another proof cannot get around.
6651 Ok(FreshOfferOutcome::Abandoned)
6652 }
6653 }
6654}
6655
6656/// Admit a paid-list notification for handling on a worker, or drop it.
6657///
6658/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6659/// meant one message could park every other non-audit message behind a full
6660/// payment verification. That verification is not a bounded local computation:
6661/// on the merkle path it performs an iterative Kademlia lookup capped only by
6662/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6663/// the loop for minutes while the bounded inbound queue behind it overflowed
6664/// and dropped unrelated replication traffic wholesale.
6665///
6666/// It now follows the same detached-responder pattern as neighbor sync and
6667/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6668/// when stale, and run on a tracked worker.
6669///
6670/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6671/// refused notify is simply dropped. The sender's own paid-list convergence
6672/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6673/// the recovery path, exactly as for a notify lost in transit.
6674async fn dispatch_paid_notify(
6675 source: PeerId,
6676 notify: protocol::PaidNotify,
6677 ctx: &ReplicationMessageHandlerContext,
6678 received_at: Instant,
6679) -> Result<()> {
6680 let admission = match admit_bounded_responder(
6681 &ctx.paid_notify_admission_semaphore,
6682 &ctx.paid_notify_responder_inflight,
6683 &source,
6684 PAID_NOTIFY_MAX_OUTSTANDING,
6685 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6686 )
6687 .await
6688 {
6689 Ok(guard) => guard,
6690 Err(failure) => {
6691 audit_metrics::record_responder_admission_drop(
6692 ReplicationResponderClass::PaidNotify,
6693 failure.reason.into(),
6694 );
6695 // WARN for the same reason as fresh offers: PaidNotify is one-way,
6696 // so a refusal discards durable paid-list evidence outright rather
6697 // than pushing work back onto a requester.
6698 warn!(
6699 responder_class = "paid_notify",
6700 source = %source,
6701 key = %hex::encode(notify.key),
6702 "Paid notify dropped at admission — paid-list evidence lost until a verification cycle re-derives it: {failure}"
6703 );
6704 return Ok(());
6705 }
6706 };
6707
6708 let ctx = ctx.clone();
6709 let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6710 // Deliberately NOT the verification request deadline used by the
6711 // request/response responders. Nobody is waiting on a notify, and shedding
6712 // one discards durable paid-list evidence rather than a reply a requester
6713 // has already given up on. The threshold is instead the point at which the
6714 // pull path would have learned the same fact anyway: one slow-cadence
6715 // neighbor-sync interval, after which the verification cycle's paid-list
6716 // quorum makes this notify genuinely redundant.
6717 let queue_max_age = ctx.config.neighbor_sync_interval_max;
6718 ctx.detached_task_tracker.clone().spawn(async move {
6719 let _admission = admission;
6720 // Closed by `shutdown()`, so this is the prompt exit path for notifies
6721 // still queued behind a worker when the engine stops.
6722 let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6723 debug!("Paid notify from {source} dropped: worker pool shut down");
6724 return;
6725 };
6726 if request_is_stale(received_at, queue_max_age) {
6727 debug!(
6728 responder_class = "paid_notify",
6729 source = %source,
6730 request_age_ms = received_at.elapsed().as_millis(),
6731 "Redundant paid notify shed at dequeue"
6732 );
6733 return;
6734 }
6735 if let Err(e) = handle_paid_notify(
6736 &source,
6737 ¬ify,
6738 &ctx.paid_list,
6739 &ctx.payment_verifier,
6740 &ctx.p2p_node,
6741 &ctx.config,
6742 &ctx.shutdown,
6743 )
6744 .await
6745 {
6746 debug!("Paid notify from {source} error: {e}");
6747 }
6748 });
6749
6750 Ok(())
6751}
6752
6753async fn handle_paid_notify(
6754 _source: &PeerId,
6755 notify: &protocol::PaidNotify,
6756 paid_list: &Arc<PaidList>,
6757 payment_verifier: &Arc<PaymentVerifier>,
6758 p2p_node: &Arc<P2PNode>,
6759 config: &ReplicationConfig,
6760 shutdown: &CancellationToken,
6761) -> Result<()> {
6762 let self_id = *p2p_node.peer_id();
6763
6764 // Rule 3: validate PoP presence before adding.
6765 if notify.proof_of_payment.is_empty() {
6766 return Ok(());
6767 }
6768
6769 // Check if we're in PaidCloseGroup for this key.
6770 if !admission::is_in_paid_close_group(
6771 &self_id,
6772 ¬ify.key,
6773 p2p_node,
6774 config.paid_list_close_group_size,
6775 )
6776 .await
6777 {
6778 return Ok(());
6779 }
6780
6781 // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6782 // paid-list metadata, so local paid-list close-group membership was checked
6783 // above before proof work. The verifier then runs the same payment proof
6784 // checks as ClientPut while writing a paid-list-strength cache entry.
6785 let Some(verification) = verify_payment_until_shutdown(
6786 payment_verifier,
6787 ¬ify.key,
6788 ¬ify.proof_of_payment,
6789 paid_notify_payment_context(),
6790 shutdown,
6791 )
6792 .await
6793 else {
6794 debug!(
6795 "Paid notify for {} abandoned: engine shutting down during payment \
6796 verification",
6797 hex::encode(notify.key)
6798 );
6799 return Ok(());
6800 };
6801 match verification {
6802 Ok(status) if status.can_store() => {
6803 debug!(
6804 "PoP validated for paid notify key {}",
6805 hex::encode(notify.key)
6806 );
6807 }
6808 Ok(_) => {
6809 warn!(
6810 "Paid notify rejected: payment required for key {}",
6811 hex::encode(notify.key)
6812 );
6813 return Ok(());
6814 }
6815 Err(e) => {
6816 warn!(
6817 "PoP verification error for paid notify key {}: {e}",
6818 hex::encode(notify.key)
6819 );
6820 return Ok(());
6821 }
6822 }
6823
6824 if let Err(e) = paid_list.insert(¬ify.key).await {
6825 warn!("Failed to add paid notify key to PaidForList: {e}");
6826 }
6827
6828 Ok(())
6829}
6830
6831#[allow(clippy::too_many_arguments)]
6832async fn dispatch_neighbor_sync_request(
6833 source: PeerId,
6834 request: protocol::NeighborSyncRequest,
6835 ctx: &ReplicationMessageHandlerContext,
6836 is_bootstrapping: bool,
6837 my_commitment: Option<StorageCommitment>,
6838 request_id: u64,
6839 received_at: Instant,
6840 rr_message_id: Option<&str>,
6841) -> Result<()> {
6842 let guard = match admit_bounded_responder(
6843 &ctx.neighbor_sync_responder_admission_semaphore,
6844 &ctx.neighbor_sync_responder_inflight,
6845 &source,
6846 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6847 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6848 )
6849 .await
6850 {
6851 Ok(guard) => guard,
6852 Err(failure) => {
6853 audit_metrics::record_responder_admission_drop(
6854 ReplicationResponderClass::NeighborSync,
6855 failure.reason.into(),
6856 );
6857 warn!(
6858 responder_class = "neighbor_sync",
6859 source = %source,
6860 "Neighbor-sync response dropped at admission: {failure}"
6861 );
6862 return Ok(());
6863 }
6864 };
6865 let pointers = ctx.pointers.clone();
6866 let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6867 let p2p_node = Arc::clone(&ctx.p2p_node);
6868 let storage = Arc::clone(&ctx.storage);
6869 let paid_list = Arc::clone(&ctx.paid_list);
6870 let queues = Arc::clone(&ctx.queues);
6871 let config = Arc::clone(&ctx.config);
6872 let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6873 let sync_history = Arc::clone(&ctx.sync_history);
6874 let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6875 let repair_proofs = Arc::clone(&ctx.repair_proofs);
6876 let request_timeout = ctx.config.verification_request_timeout;
6877 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6878 ctx.detached_task_tracker.spawn(async move {
6879 let _guard = guard;
6880 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6881 debug!(
6882 responder_class = "neighbor_sync",
6883 source = %source,
6884 "Neighbor-sync responder worker pool closed before dequeue"
6885 );
6886 return;
6887 };
6888 if request_is_stale(received_at, request_timeout) {
6889 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6890 debug!(
6891 responder_class = "neighbor_sync",
6892 source = %source,
6893 request_age_ms = received_at.elapsed().as_millis(),
6894 "Stale neighbor-sync request shed at dequeue"
6895 );
6896 return;
6897 }
6898 // A peer whose sync request is admitted and fresh gets our pointer
6899 // hints as well, including a node that is bootstrapping, which is how
6900 // it learns the pointers it should hold. Only such a request: each
6901 // answer scans every pointer held, and a refused or stale one must
6902 // cost nothing.
6903 if let Some(pointers) = &pointers {
6904 pointers.answer_sync_with_hints(source);
6905 }
6906 if let Err(e) = handle_neighbor_sync_request(
6907 &source,
6908 &request,
6909 &p2p_node,
6910 &storage,
6911 &paid_list,
6912 &queues,
6913 &config,
6914 is_bootstrapping,
6915 &bootstrap_state,
6916 &sync_history,
6917 &sync_cycle_epoch,
6918 &repair_proofs,
6919 my_commitment,
6920 request_id,
6921 rr_message_id.as_deref(),
6922 )
6923 .await
6924 {
6925 debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6926 }
6927 });
6928
6929 Ok(())
6930}
6931
6932#[allow(clippy::too_many_arguments)]
6933async fn handle_neighbor_sync_request(
6934 source: &PeerId,
6935 request: &protocol::NeighborSyncRequest,
6936 p2p_node: &Arc<P2PNode>,
6937 storage: &Arc<ChunkStore>,
6938 paid_list: &Arc<PaidList>,
6939 queues: &Arc<RwLock<ReplicationQueues>>,
6940 config: &ReplicationConfig,
6941 is_bootstrapping: bool,
6942 bootstrap_state: &Arc<RwLock<BootstrapState>>,
6943 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6944 sync_cycle_epoch: &Arc<RwLock<u64>>,
6945 repair_proofs: &Arc<RwLock<RepairProofs>>,
6946 my_commitment: Option<StorageCommitment>,
6947 request_id: u64,
6948 rr_message_id: Option<&str>,
6949) -> Result<()> {
6950 let self_id = *p2p_node.peer_id();
6951
6952 // No per-request hint count limit: the wire message size limit
6953 // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6954 // challenges, sync hints don't drive expensive computation — they just
6955 // enter the verification queue. A per-request limit here would break
6956 // bootstrap replication for newly-joined nodes with 0 stored chunks.
6957
6958 // Build response (outbound hints).
6959 let (response, sent_replica_hints, sender_in_rt) =
6960 neighbor_sync::handle_sync_request_with_proofs(
6961 source,
6962 request,
6963 p2p_node,
6964 storage,
6965 paid_list,
6966 config,
6967 is_bootstrapping,
6968 my_commitment.clone(),
6969 )
6970 .await;
6971
6972 // Send response.
6973 let response_sent = send_replication_response_checked(
6974 source,
6975 p2p_node,
6976 request_id,
6977 ReplicationMessageBody::NeighborSyncResponse(response),
6978 rr_message_id,
6979 None,
6980 )
6981 .await;
6982
6983 // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6984 if !sender_in_rt {
6985 return Ok(());
6986 }
6987
6988 // Update sync history for this peer before recording repair proofs so a
6989 // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6990 {
6991 let mut history = sync_history.write().await;
6992 let record = history.entry(*source).or_insert(PeerSyncRecord {
6993 last_sync: None,
6994 cycles_since_sync: 0,
6995 });
6996 record.last_sync = Some(Instant::now());
6997 record.cycles_since_sync = 0;
6998 }
6999
7000 if response_sent && !request.bootstrapping {
7001 record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
7002 .await;
7003 }
7004
7005 // Admit inbound hints and queue for verification.
7006 let outcome = admit_and_queue_hints(
7007 &self_id,
7008 source,
7009 &request.replica_hints,
7010 &request.paid_hints,
7011 p2p_node,
7012 config,
7013 storage,
7014 paid_list,
7015 queues,
7016 )
7017 .await;
7018
7019 // Track discovered keys for bootstrap drain detection so that hints
7020 // admitted via inbound sync requests are not missed. Capacity-rejected
7021 // hints keep this source on the "not yet drained" list until its next
7022 // sync re-admits them; a clean cycle clears the source.
7023 if is_bootstrapping {
7024 let live_discovered = outcome.discovered.clone();
7025 let outcomes = [(*source, outcome)];
7026 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
7027 }
7028
7029 Ok(())
7030}
7031
7032/// Test-only record of who *sent* a verification request covering a watched key.
7033///
7034/// The capacity gate's entire effect is a request that is never sent, and a
7035/// request that was not sent leaves no production counter anywhere — not on the
7036/// sender, whose traffic counters are process-global and so cannot separate one
7037/// node of a single-process testnet from another, and not on the responder,
7038/// which simply never hears from it. Recording who asked is what lets a test
7039/// tell "held the key back" apart from "probed the close group, was refused at
7040/// the dial, and then held the key back", which are otherwise identical from the
7041/// queue's point of view.
7042///
7043/// Arming replaces the previous watch, so the outer map holds exactly the keys
7044/// the current test named, and each inner map holds at most one entry per node
7045/// in the process. Nothing is recorded until a test arms it, and the armed path
7046/// costs one read lock on the sending side.
7047///
7048/// Counting is per key because a node that cannot write legitimately keeps
7049/// sending verification requests for keys it has not yet authorized — that is
7050/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
7051/// would assert something untrue.
7052///
7053/// It counts *send attempts*, deliberately, recorded immediately before the wire
7054/// call. A responder sheds requests at admission and as stale, so a
7055/// receiver-side count would report zero for probes that were really sent, and
7056/// an assertion that this node asked nobody would pass on the strength of the
7057/// receiver dropping the question. It is not proof of delivery: a send that
7058/// fails immediately, with no route or during shutdown, is still counted.
7059///
7060/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
7061/// MSRV.
7062#[cfg(any(test, feature = "test-utils"))]
7063type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
7064
7065#[cfg(any(test, feature = "test-utils"))]
7066static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
7067 std::sync::OnceLock::new();
7068
7069#[cfg(any(test, feature = "test-utils"))]
7070fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
7071 VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
7072}
7073
7074/// Test-only: start counting verification requests for `keys`, from zero.
7075///
7076/// Replaces any previous watch rather than adding to it, so the map is bounded
7077/// by the keys of the test that armed it last and nothing accumulates across a
7078/// process running many tests.
7079#[cfg(any(test, feature = "test-utils"))]
7080pub fn watch_verification_requests_for_test(keys: &[XorName]) {
7081 if let Ok(mut watch) = verification_watch().write() {
7082 watch.clear();
7083 for key in keys {
7084 watch.insert(*key, HashMap::new());
7085 }
7086 }
7087}
7088
7089/// Record that `requester` sent a verification request covering `keys`, for
7090/// whichever of them are watched. A poisoned lock is ignored rather than
7091/// propagated: this is observation for tests and must never change behaviour.
7092#[cfg(any(test, feature = "test-utils"))]
7093pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
7094 // Fast path under a read lock: with nothing watched — every production
7095 // build, and every test that did not ask — this is all the sender pays.
7096 match verification_watch().read() {
7097 Ok(watch) if watch.is_empty() => return,
7098 Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
7099 Ok(_) => {}
7100 Err(_) => return,
7101 }
7102 if let Ok(mut watch) = verification_watch().write() {
7103 for key in keys {
7104 if let Some(by_peer) = watch.get_mut(key) {
7105 *by_peer.entry(*requester).or_insert(0) += 1;
7106 }
7107 }
7108 }
7109}
7110
7111/// Test-only: how many times `requester` has asked this process about `key`.
7112/// Zero unless the key was registered with `watch_verification_requests_for_test`.
7113#[cfg(any(test, feature = "test-utils"))]
7114#[must_use]
7115pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
7116 verification_watch().read().map_or(0, |watch| {
7117 watch
7118 .get(key)
7119 .and_then(|by_peer| by_peer.get(requester))
7120 .copied()
7121 .unwrap_or(0)
7122 })
7123}
7124
7125async fn handle_verification_request(
7126 source: &PeerId,
7127 request: &protocol::VerificationRequest,
7128 storage: &Arc<ChunkStore>,
7129 paid_list: &Arc<PaidList>,
7130 p2p_node: &Arc<P2PNode>,
7131 request_id: u64,
7132 rr_message_id: Option<&str>,
7133) -> Result<()> {
7134 #[derive(Clone, Copy)]
7135 enum CachedPaidLookup {
7136 NotChecked,
7137 Checked(Option<bool>),
7138 }
7139
7140 #[derive(Clone, Copy)]
7141 struct CachedVerificationLookup {
7142 present: Option<bool>,
7143 paid: CachedPaidLookup,
7144 }
7145
7146 if verification_request_exceeds_limit(request.keys.len()) {
7147 warn!(
7148 "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
7149 request.keys.len(),
7150 );
7151 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7152 return Ok(());
7153 }
7154
7155 let requested_keys = request.keys.as_slice();
7156
7157 if request.paid_list_check_indices.len() > request.keys.len() {
7158 warn!(
7159 "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
7160 request.paid_list_check_indices.len(),
7161 request.keys.len(),
7162 );
7163 send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7164 return Ok(());
7165 }
7166
7167 let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
7168 let paid_check_set: HashSet<u32> = request
7169 .paid_list_check_indices
7170 .iter()
7171 .copied()
7172 .filter(|&idx| {
7173 if idx >= keys_len {
7174 warn!(
7175 "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
7176 requested_keys.len(),
7177 );
7178 false
7179 } else {
7180 true
7181 }
7182 })
7183 .collect();
7184
7185 let mut results = Vec::with_capacity(requested_keys.len());
7186 let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
7187 for (i, key) in requested_keys.iter().enumerate() {
7188 let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
7189 let cached = lookup_cache.entry(*key).or_insert_with(|| {
7190 let present = match storage.exists(key) {
7191 Ok(present) => Some(present),
7192 Err(e) => {
7193 warn!(
7194 "Verification request from {source}: failed to check storage for {}: {e}",
7195 hex::encode(key)
7196 );
7197 None
7198 }
7199 };
7200 CachedVerificationLookup {
7201 present,
7202 paid: CachedPaidLookup::NotChecked,
7203 }
7204 });
7205
7206 if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
7207 cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
7208 Ok(paid) => Some(paid),
7209 Err(e) => {
7210 warn!(
7211 "Verification request from {source}: failed to check paid-list for {}: {e}",
7212 hex::encode(key)
7213 );
7214 None
7215 }
7216 });
7217 }
7218
7219 let paid = if needs_paid {
7220 match cached.paid {
7221 CachedPaidLookup::Checked(paid) => paid,
7222 CachedPaidLookup::NotChecked => None,
7223 }
7224 } else {
7225 None
7226 };
7227
7228 if cached.present.is_none() && paid.is_none() {
7229 continue;
7230 }
7231
7232 results.push(protocol::KeyVerificationResult {
7233 key: *key,
7234 present: cached.present.unwrap_or(false),
7235 paid,
7236 });
7237 }
7238
7239 send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
7240
7241 Ok(())
7242}
7243
7244async fn dispatch_verification_request(
7245 source: PeerId,
7246 request: protocol::VerificationRequest,
7247 ctx: &ReplicationMessageHandlerContext,
7248 request_id: u64,
7249 received_at: Instant,
7250 rr_message_id: Option<&str>,
7251) -> Result<()> {
7252 let guard = match admit_bounded_responder(
7253 &ctx.verification_responder_admission_semaphore,
7254 &ctx.verification_responder_inflight,
7255 &source,
7256 VERIFICATION_RESPONDER_MAX_OUTSTANDING,
7257 VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7258 )
7259 .await
7260 {
7261 Ok(guard) => guard,
7262 Err(failure) => {
7263 audit_metrics::record_responder_admission_drop(
7264 ReplicationResponderClass::Verification,
7265 failure.reason.into(),
7266 );
7267 warn!(
7268 responder_class = "verification",
7269 source = %source,
7270 "Verification response dropped at admission: {failure}"
7271 );
7272 return Ok(());
7273 }
7274 };
7275
7276 let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
7277 let storage = Arc::clone(&ctx.storage);
7278 let paid_list = Arc::clone(&ctx.paid_list);
7279 let p2p_node = Arc::clone(&ctx.p2p_node);
7280 let request_timeout = ctx.config.verification_request_timeout;
7281 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7282 ctx.detached_task_tracker.spawn(async move {
7283 let _guard = guard;
7284 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7285 debug!(
7286 responder_class = "verification",
7287 source = %source,
7288 "Verification responder worker pool closed before dequeue"
7289 );
7290 return;
7291 };
7292 if request_is_stale(received_at, request_timeout) {
7293 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
7294 debug!(
7295 responder_class = "verification",
7296 source = %source,
7297 request_age_ms = received_at.elapsed().as_millis(),
7298 "Stale verification request shed at dequeue"
7299 );
7300 return;
7301 }
7302 if let Err(e) = handle_verification_request(
7303 &source,
7304 &request,
7305 &storage,
7306 &paid_list,
7307 &p2p_node,
7308 request_id,
7309 rr_message_id.as_deref(),
7310 )
7311 .await
7312 {
7313 debug!(source = %source, "Verification request handling failed: {e}");
7314 }
7315 });
7316
7317 Ok(())
7318}
7319
7320const fn verification_request_exceeds_limit(key_count: usize) -> bool {
7321 key_count > MAX_INCOMING_VERIFICATION_KEYS
7322}
7323
7324async fn send_verification_results(
7325 source: &PeerId,
7326 p2p_node: &Arc<P2PNode>,
7327 request_id: u64,
7328 results: Vec<protocol::KeyVerificationResult>,
7329 rr_message_id: Option<&str>,
7330) {
7331 send_replication_response(
7332 source,
7333 p2p_node,
7334 request_id,
7335 ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
7336 rr_message_id,
7337 )
7338 .await;
7339}
7340
7341async fn dispatch_fetch_request(
7342 source: PeerId,
7343 request: protocol::FetchRequest,
7344 ctx: &ReplicationMessageHandlerContext,
7345 request_id: u64,
7346 received_at: Instant,
7347 rr_message_id: Option<&str>,
7348) -> Result<()> {
7349 let guard = match admit_bounded_responder(
7350 &ctx.fetch_responder_admission_semaphore,
7351 &ctx.fetch_responder_inflight,
7352 &source,
7353 FETCH_RESPONDER_MAX_OUTSTANDING,
7354 FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7355 )
7356 .await
7357 {
7358 Ok(guard) => guard,
7359 Err(failure) => {
7360 audit_metrics::record_responder_admission_drop(
7361 ReplicationResponderClass::Fetch,
7362 failure.reason.into(),
7363 );
7364 warn!(
7365 responder_class = "fetch",
7366 source = %source,
7367 "Fetch response dropped at admission: {failure}"
7368 );
7369 return Ok(());
7370 }
7371 };
7372
7373 let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
7374 let storage = Arc::clone(&ctx.storage);
7375 let p2p_node = Arc::clone(&ctx.p2p_node);
7376 let request_timeout = ctx.config.fetch_request_timeout;
7377 let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7378 ctx.detached_task_tracker.spawn(async move {
7379 let _guard = guard;
7380 let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7381 debug!(
7382 responder_class = "fetch",
7383 source = %source,
7384 "Fetch responder worker pool closed before dequeue"
7385 );
7386 return;
7387 };
7388 if request_is_stale(received_at, request_timeout) {
7389 audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
7390 debug!(
7391 responder_class = "fetch",
7392 source = %source,
7393 request_age_ms = received_at.elapsed().as_millis(),
7394 "Stale fetch request shed at dequeue"
7395 );
7396 return;
7397 }
7398 if let Err(e) = handle_fetch_request(
7399 &source,
7400 &request,
7401 &storage,
7402 &p2p_node,
7403 request_id,
7404 rr_message_id.as_deref(),
7405 )
7406 .await
7407 {
7408 debug!(source = %source, "Fetch request handling failed: {e}");
7409 }
7410 });
7411
7412 Ok(())
7413}
7414
7415fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
7416 received_at.elapsed() >= timeout
7417}
7418
7419/// Turn the responder's storage read into the answer it sends back.
7420///
7421/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7422/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7423/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7424/// Nothing about a node giving chunks up produces the second.
7425fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7426 match read {
7427 Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7428 Ok(None) => protocol::FetchResponse::NotFound { key },
7429 Err(e) => protocol::FetchResponse::Error {
7430 key,
7431 reason: format!("{e}"),
7432 },
7433 }
7434}
7435
7436async fn handle_fetch_request(
7437 source: &PeerId,
7438 request: &protocol::FetchRequest,
7439 storage: &Arc<ChunkStore>,
7440 p2p_node: &Arc<P2PNode>,
7441 request_id: u64,
7442 rr_message_id: Option<&str>,
7443) -> Result<()> {
7444 let response = fetch_response_for(request.key, storage.get(&request.key).await);
7445
7446 send_replication_response(
7447 source,
7448 p2p_node,
7449 request_id,
7450 ReplicationMessageBody::FetchResponse(response),
7451 rr_message_id,
7452 )
7453 .await;
7454
7455 Ok(())
7456}
7457
7458/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7459/// the prune-confirmation audit, which reuses the same wire message): reply with
7460/// per-key possession digests.
7461struct AuditResponderCompletion {
7462 response_kind: &'static str,
7463 sent: bool,
7464 processing: Duration,
7465 response_send: Duration,
7466}
7467
7468async fn handle_audit_challenge_msg(
7469 source: &PeerId,
7470 challenge: &protocol::AuditChallenge,
7471 storage: &Arc<ChunkStore>,
7472 p2p_node: &Arc<P2PNode>,
7473 is_bootstrapping: bool,
7474 reply: ReplyRoute<'_>,
7475) -> Result<AuditResponderCompletion> {
7476 #[allow(clippy::cast_possible_truncation)]
7477 let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7478 info!(
7479 "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7480 challenge.keys.len(),
7481 is_bootstrapping,
7482 reply.rr_message_id.is_some(),
7483 );
7484
7485 let processing_started = Instant::now();
7486 let response = audit::handle_audit_challenge(
7487 challenge,
7488 storage,
7489 p2p_node.peer_id(),
7490 is_bootstrapping,
7491 stored_chunks,
7492 )
7493 .await;
7494 let processing = processing_started.elapsed();
7495 let response_kind = audit_response_kind(&response);
7496
7497 let response_send_started = Instant::now();
7498 let sent = send_replication_response_checked(
7499 source,
7500 p2p_node,
7501 reply.request_id,
7502 ReplicationMessageBody::AuditResponse(response),
7503 reply.rr_message_id,
7504 Some(reply.protocol),
7505 )
7506 .await;
7507 let response_send = response_send_started.elapsed();
7508
7509 Ok(AuditResponderCompletion {
7510 response_kind,
7511 sent,
7512 processing,
7513 response_send,
7514 })
7515}
7516
7517#[allow(clippy::too_many_arguments)]
7518fn log_audit_responder_completion(
7519 metrics: &AuditResponderMetrics,
7520 source: PeerId,
7521 class: AuditResponderClass,
7522 kind: &'static str,
7523 challenge_id: u64,
7524 work_items: usize,
7525 response_kind: &'static str,
7526 sent: bool,
7527 received_at: Instant,
7528 worker_started: Instant,
7529 processing: Duration,
7530 response_send: Duration,
7531) {
7532 let dispatch = worker_started.saturating_duration_since(received_at);
7533 let total = received_at.elapsed();
7534 metrics.record_completed(source, processing, total, sent);
7535 if sent {
7536 info!(
7537 target: "ant_node::replication::audit_responder",
7538 event = "completed",
7539 kind,
7540 responder_class = class.as_str(),
7541 source = %source,
7542 challenge_id,
7543 work_items,
7544 response = response_kind,
7545 sent,
7546 dispatch_ms = dispatch.as_millis(),
7547 processing_ms = processing.as_millis(),
7548 response_send_ms = response_send.as_millis(),
7549 total_ms = total.as_millis(),
7550 "Audit responder request completed"
7551 );
7552 } else {
7553 warn!(
7554 target: "ant_node::replication::audit_responder",
7555 event = "completed",
7556 kind,
7557 responder_class = class.as_str(),
7558 source = %source,
7559 challenge_id,
7560 work_items,
7561 response = response_kind,
7562 sent,
7563 dispatch_ms = dispatch.as_millis(),
7564 processing_ms = processing.as_millis(),
7565 response_send_ms = response_send.as_millis(),
7566 total_ms = total.as_millis(),
7567 "Audit responder request completed without sending a reply"
7568 );
7569 }
7570}
7571
7572/// Where a reply goes and how it is addressed.
7573///
7574/// Grouped because the audit responder needs all three together and one of them
7575/// is not derivable from the body: during the rollout window a possession reply
7576/// may have to go out on the core id rather than its family's own (see
7577/// [`is_legacy_possession_challenge`]).
7578struct ReplyRoute<'a> {
7579 /// Correlates the reply with the challenge, at the replication layer.
7580 request_id: u64,
7581 /// Present when the challenge arrived over request-response, in which case
7582 /// the reply rides the same exchange back.
7583 rr_message_id: Option<&'a str>,
7584 /// The protocol id to answer on.
7585 protocol: &'static str,
7586}
7587
7588fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7589 match response {
7590 protocol::AuditResponse::Digests { .. } => "digests",
7591 protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7592 protocol::AuditResponse::Rejected { .. } => "rejected",
7593 }
7594}
7595
7596fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7597 match response {
7598 protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7599 protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7600 protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7601 }
7602}
7603
7604fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7605 match response {
7606 protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7607 protocol::SubtreeAuditResponse::Bootstrapping { .. }
7608 | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7609 }
7610}
7611
7612fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7613 match response {
7614 protocol::SubtreeSliceResponse::Items { .. } => "items",
7615 protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7616 protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7617 }
7618}
7619
7620fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7621 match response {
7622 protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7623 protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7624 }
7625}
7626
7627// ---------------------------------------------------------------------------
7628// Message sending helper
7629// ---------------------------------------------------------------------------
7630
7631/// Send a replication response message as a best-effort reply.
7632///
7633/// Encode and send failures are logged by the checked helper. Most response
7634/// paths do not need to branch on send success, so this wrapper keeps those
7635/// call sites explicit about their best-effort behavior.
7636async fn send_replication_response(
7637 peer: &PeerId,
7638 p2p_node: &Arc<P2PNode>,
7639 request_id: u64,
7640 body: ReplicationMessageBody,
7641 rr_message_id: Option<&str>,
7642) {
7643 let _ =
7644 send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7645 .await;
7646}
7647
7648/// Send a replication response message and report whether it was accepted.
7649///
7650/// Returns `true` after the message is encoded and accepted by the P2P send
7651/// path. Returns `false` after logging an encode or send failure. Repair-proof
7652/// recording uses this to avoid trusting hints that were not actually sent.
7653///
7654/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7655/// request-response path so saorsa-core can route it back to the caller's
7656/// `send_request` future. Otherwise it is sent as a plain message.
7657///
7658/// `protocol` overrides the id the body would route on by family. Exactly one
7659/// caller needs it: a possession challenge from a peer that predates the family
7660/// split has to be answered where it was asked (see
7661/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7662/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7663async fn send_replication_response_checked(
7664 peer: &PeerId,
7665 p2p_node: &Arc<P2PNode>,
7666 request_id: u64,
7667 body: ReplicationMessageBody,
7668 rr_message_id: Option<&str>,
7669 protocol: Option<&'static str>,
7670) -> bool {
7671 let msg = ReplicationMessage { request_id, body };
7672 let encoded = match msg.encode() {
7673 Ok(data) => data,
7674 Err(e) => {
7675 warn!("Failed to encode replication response: {e}");
7676 return false;
7677 }
7678 };
7679 // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7680 // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7681 // included for completeness. Other response variants (verification/audit/
7682 // commitment) are intentionally excluded — the round-2 audit reply is now a
7683 // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7684 if matches!(
7685 msg.body,
7686 ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7687 ) {
7688 protocol::record_served(peer, encoded.len());
7689 }
7690 let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7691 let result = if let Some(msg_id) = rr_message_id {
7692 p2p_node
7693 .send_response(peer, protocol, msg_id, encoded)
7694 .await
7695 } else {
7696 p2p_node.send_message(peer, protocol, encoded, &[]).await
7697 };
7698 if let Err(e) = result {
7699 debug!("Failed to send replication response to {peer}: {e}");
7700 return false;
7701 }
7702 true
7703}
7704
7705async fn record_sent_replica_hints(
7706 peer: &PeerId,
7707 hints: &[neighbor_sync::SentReplicaHint],
7708 repair_proofs: &Arc<RwLock<RepairProofs>>,
7709 sync_cycle_epoch: &Arc<RwLock<u64>>,
7710) {
7711 if hints.is_empty() {
7712 return;
7713 }
7714
7715 let hinted_at_epoch = *sync_cycle_epoch.read().await;
7716 let mut proofs = repair_proofs.write().await;
7717 for hint in hints {
7718 if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7719 debug!(
7720 "Recorded repair hint proof for peer {peer} and key {}",
7721 hex::encode(hint.key)
7722 );
7723 }
7724 }
7725}
7726
7727// ---------------------------------------------------------------------------
7728// Neighbor sync round
7729// ---------------------------------------------------------------------------
7730
7731/// Run one neighbor sync round.
7732#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7733async fn run_neighbor_sync_round(
7734 p2p_node: &Arc<P2PNode>,
7735 storage: &Arc<ChunkStore>,
7736 paid_list: &Arc<PaidList>,
7737 queues: &Arc<RwLock<ReplicationQueues>>,
7738 config: &ReplicationConfig,
7739 sync_state: &Arc<RwLock<NeighborSyncState>>,
7740 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7741 sync_cycle_epoch: &Arc<RwLock<u64>>,
7742 repair_proofs: &Arc<RwLock<RepairProofs>>,
7743 is_bootstrapping: &Arc<RwLock<bool>>,
7744 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7745 commitment_state: &Arc<ResponderCommitmentState>,
7746 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7747 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7748 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7749 audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7750 gossip_audit: &GossipAuditTrigger,
7751 disk_pressure: &retention::DiskPressure,
7752 pointers: Option<&Arc<pointer::PointerReplication>>,
7753) {
7754 let self_id = *p2p_node.peer_id();
7755 let bootstrapping = *is_bootstrapping.read().await;
7756
7757 // Check if cycle is complete; start new one if needed.
7758 // We check under a read lock, then release it before the expensive
7759 // prune pass and DHT snapshot so other tasks are not starved.
7760 let cycle_complete = sync_state.read().await.is_cycle_complete();
7761 if cycle_complete {
7762 // A completed local neighbor-sync cycle advances the epoch component
7763 // of repair-proof maturity. The per-key wall-clock minimum age is
7764 // checked when audits are selected.
7765 {
7766 let mut history = sync_history.write().await;
7767 for record in history.values_mut() {
7768 record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7769 }
7770 }
7771 {
7772 let mut epoch = sync_cycle_epoch.write().await;
7773 *epoch = epoch.saturating_add(1);
7774 }
7775 }
7776
7777 // Pruning (Section 11) — runs without holding sync_state. Prune candidacy
7778 // is unconditional once the hysteresis elapses, but a candidate is only
7779 // erased under disk pressure (ADR-0028); bootstrap state also defers the
7780 // remote prune-confirmation audits until bootstrap has drained. The passes
7781 // run after every completed cycle and, while the disk is under pressure,
7782 // on other rounds too, at most once per minimum sync interval: a cycle
7783 // spans several rounds, and a node under pressure should not wait for one
7784 // to end before it starts erasing.
7785 if disk_pressure.prune_pass_due(cycle_complete, storage, config.neighbor_sync_interval_min) {
7786 let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7787 pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7788 self_id: &self_id,
7789 storage,
7790 paid_list,
7791 p2p_node,
7792 config,
7793 sync_state,
7794 repair_proofs,
7795 allow_remote_prune_audits,
7796 commitment_state: Some(commitment_state),
7797 audit_challenge_coordinator,
7798 disk_pressure,
7799 })
7800 .await;
7801 if let Some(pointers) = pointers {
7802 pointers
7803 .prune_pass(
7804 allow_remote_prune_audits,
7805 disk_pressure,
7806 Some(commitment_state),
7807 )
7808 .await;
7809 }
7810 disk_pressure.prune_pass_finished();
7811 }
7812
7813 if cycle_complete {
7814 // Take fresh close-neighbor snapshot (DHT query, no lock held).
7815 let neighbors =
7816 neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7817 .await;
7818
7819 // Now re-acquire write lock and re-check before swapping cycle.
7820 let mut state = sync_state.write().await;
7821 if state.is_cycle_complete() {
7822 // Preserve cooldown and bootstrap-claim tracking across cycles.
7823 // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7824 // would reset the abuse detection timer every cycle.
7825 let old_sync_times = std::mem::take(&mut state.last_sync_times);
7826 let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7827 let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7828 *state = NeighborSyncState::new_cycle(neighbors);
7829 state.last_sync_times = old_sync_times;
7830 state.bootstrap_claims = old_bootstrap_claims;
7831 state.bootstrap_claim_history = old_bootstrap_claim_history;
7832 }
7833 }
7834
7835 // Select batch of peers.
7836 let batch = {
7837 let mut state = sync_state.write().await;
7838 neighbor_sync::select_sync_batch(
7839 &mut state,
7840 config.neighbor_sync_peer_count,
7841 config.neighbor_sync_cooldown,
7842 )
7843 };
7844
7845 if batch.is_empty() {
7846 return;
7847 }
7848
7849 debug!("Neighbor sync: syncing with {} peers", batch.len());
7850 if let Some(pointers) = pointers {
7851 pointers.push_hints_detached(batch.clone());
7852 }
7853
7854 // Snapshot our current commitment once per round so all peers in
7855 // this batch see the same thing (gossip is the responder's attestation;
7856 // same value across the batch is fine and reduces RwLock churn). Atomically
7857 // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7858 // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7859 let my_commitment = commitment_state
7860 .current_for_gossip()
7861 .map(|b| b.commitment().clone());
7862
7863 let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7864 &batch,
7865 storage,
7866 paid_list,
7867 p2p_node,
7868 config.close_group_size,
7869 config.paid_list_close_group_size,
7870 )
7871 .await;
7872
7873 // Sync with each peer in the batch.
7874 for peer in &batch {
7875 let hints = hints_by_peer.remove(peer).unwrap_or_default();
7876 let outcome = neighbor_sync::sync_with_peer_with_hints(
7877 peer,
7878 p2p_node,
7879 config,
7880 bootstrapping,
7881 hints,
7882 my_commitment.clone(),
7883 )
7884 .await;
7885
7886 if let Some(outcome) = outcome {
7887 handle_sync_response(
7888 &self_id,
7889 peer,
7890 &outcome.response,
7891 &outcome.sent_replica_hints,
7892 p2p_node,
7893 config,
7894 bootstrapping,
7895 bootstrap_state,
7896 storage,
7897 paid_list,
7898 queues,
7899 sync_state,
7900 sync_history,
7901 sync_cycle_epoch,
7902 repair_proofs,
7903 last_commitment_by_peer,
7904 ever_capable_peers,
7905 sig_verify_attempts,
7906 gossip_audit,
7907 )
7908 .await;
7909 } else {
7910 // Sync failed -- remove peer and try to fill slot.
7911 let replacement = {
7912 let mut state = sync_state.write().await;
7913 neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7914 };
7915
7916 // Attempt sync with the replacement peer (if one was found).
7917 if let Some(replacement_peer) = replacement {
7918 let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7919 std::slice::from_ref(&replacement_peer),
7920 storage,
7921 paid_list,
7922 p2p_node,
7923 config.close_group_size,
7924 config.paid_list_close_group_size,
7925 )
7926 .await;
7927 let hints = replacement_hints
7928 .remove(&replacement_peer)
7929 .unwrap_or_default();
7930 let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7931 &replacement_peer,
7932 p2p_node,
7933 config,
7934 bootstrapping,
7935 hints,
7936 my_commitment.clone(),
7937 )
7938 .await;
7939
7940 if let Some(outcome) = replacement_outcome {
7941 handle_sync_response(
7942 &self_id,
7943 &replacement_peer,
7944 &outcome.response,
7945 &outcome.sent_replica_hints,
7946 p2p_node,
7947 config,
7948 bootstrapping,
7949 bootstrap_state,
7950 storage,
7951 paid_list,
7952 queues,
7953 sync_state,
7954 sync_history,
7955 sync_cycle_epoch,
7956 repair_proofs,
7957 last_commitment_by_peer,
7958 ever_capable_peers,
7959 sig_verify_attempts,
7960 gossip_audit,
7961 )
7962 .await;
7963 }
7964 }
7965 }
7966 }
7967}
7968
7969/// Process a successful neighbor sync response: record the sync, check for
7970/// bootstrap claim abuse, and admit inbound hints.
7971#[allow(clippy::too_many_arguments)]
7972async fn handle_sync_response(
7973 self_id: &PeerId,
7974 peer: &PeerId,
7975 resp: &NeighborSyncResponse,
7976 sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7977 p2p_node: &Arc<P2PNode>,
7978 config: &ReplicationConfig,
7979 bootstrapping: bool,
7980 bootstrap_state: &Arc<RwLock<BootstrapState>>,
7981 storage: &Arc<ChunkStore>,
7982 paid_list: &Arc<PaidList>,
7983 queues: &Arc<RwLock<ReplicationQueues>>,
7984 sync_state: &Arc<RwLock<NeighborSyncState>>,
7985 sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7986 sync_cycle_epoch: &Arc<RwLock<u64>>,
7987 repair_proofs: &Arc<RwLock<RepairProofs>>,
7988 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7989 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7990 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7991 gossip_audit: &GossipAuditTrigger,
7992) {
7993 // Ingest the peer's commitment if they piggybacked one on the response.
7994 // Same verification as the request path (peer-id binding + signature);
7995 // forged commitments are dropped at the edge. A *changed* commitment here
7996 // is a gossip-audit trigger just like on the request path — so a peer that
7997 // only ever answers sync (never initiates) is still audited (ADR-0002).
7998 if let Some(target) = ingest_peer_commitment(
7999 peer,
8000 resp.commitment.as_ref(),
8001 p2p_node,
8002 last_commitment_by_peer,
8003 ever_capable_peers,
8004 sig_verify_attempts,
8005 )
8006 .await
8007 {
8008 maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
8009 }
8010
8011 // Record successful sync.
8012 {
8013 let mut state = sync_state.write().await;
8014 neighbor_sync::record_successful_sync(&mut state, peer);
8015 }
8016 {
8017 let mut history = sync_history.write().await;
8018 let record = history.entry(*peer).or_insert(PeerSyncRecord {
8019 last_sync: None,
8020 cycles_since_sync: 0,
8021 });
8022 record.last_sync = Some(Instant::now());
8023 record.cycles_since_sync = 0;
8024 }
8025
8026 // Process inbound hints from response (skip if peer is bootstrapping).
8027 if resp.bootstrapping {
8028 // Gap 6: BootstrapClaimAbuse grace period enforcement.
8029 // Separate state mutation from network I/O to avoid holding the
8030 // write lock across report_trust_event.
8031 let should_report = {
8032 let now = Instant::now();
8033 let mut state = sync_state.write().await;
8034 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
8035 BootstrapClaimObservation::WithinGrace { .. } => false,
8036 BootstrapClaimObservation::PastGrace { first_seen } => {
8037 warn!(
8038 "Peer {peer} has been claiming bootstrap for {:?}, \
8039 exceeding grace period of {:?} — reporting abuse",
8040 now.duration_since(first_seen),
8041 config.bootstrap_claim_grace_period,
8042 );
8043 true
8044 }
8045 BootstrapClaimObservation::Repeated { first_seen } => {
8046 warn!(
8047 "Peer {peer} repeated bootstrap claim after previously stopping; \
8048 first claim was {:?} ago — reporting abuse",
8049 now.duration_since(first_seen),
8050 );
8051 true
8052 }
8053 }
8054 };
8055 if should_report {
8056 p2p_node
8057 .report_trust_event(
8058 peer,
8059 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8060 )
8061 .await;
8062 }
8063 } else {
8064 // Peer is not claiming bootstrap; clear active claim while retaining
8065 // history so the peer cannot start a second grace window later.
8066 {
8067 let mut state = sync_state.write().await;
8068 state.clear_active_bootstrap_claim(peer);
8069 }
8070 record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
8071 let outcome = admit_and_queue_hints(
8072 self_id,
8073 peer,
8074 &resp.replica_hints,
8075 &resp.paid_hints,
8076 p2p_node,
8077 config,
8078 storage,
8079 paid_list,
8080 queues,
8081 )
8082 .await;
8083
8084 // Track discovered keys for bootstrap drain detection so that hints
8085 // admitted via regular neighbor sync are not missed. Capacity-
8086 // rejected hints keep this source on the "not yet drained" list
8087 // until its next sync replays them; a clean cycle clears it.
8088 if bootstrapping {
8089 let live_discovered = outcome.discovered.clone();
8090 let outcomes = [(*peer, outcome)];
8091 publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
8092 .await;
8093 }
8094 }
8095}
8096
8097/// Admit hints and queue them for verification, returning newly-discovered keys.
8098///
8099/// Shared by neighbor-sync request handling, response handling, and bootstrap
8100/// sync so that admission + queueing logic lives in one place.
8101#[allow(clippy::too_many_arguments)]
8102/// Outcome of [`admit_and_queue_hints`].
8103///
8104/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
8105/// available; that source is kept outstanding until it re-hints. `displaced`
8106/// tracks older borrowed hints reclaimed for another sender; only the key is
8107/// dropped from bootstrap tracking — the former owner's standing is untouched
8108/// (see [`publish_bootstrap_admission_outcomes`]).
8109struct AdmissionOutcome {
8110 discovered: HashSet<XorName>,
8111 capacity_rejected_count: usize,
8112 displaced: Vec<CapacityDisplacement>,
8113}
8114
8115/// Publish one atomic admission unit into bootstrap drain accounting.
8116///
8117/// Only sources that were themselves capacity-rejected are kept outstanding.
8118/// A fairness displacement forfeits the displaced *key* but never stamps its
8119/// former owner: reclaiming a borrowed slot is this node's own fairness
8120/// decision, so charging it to the victim would let a sustained flooder wedge
8121/// our bootstrap drain open through an unrelated honest peer. Clean sources
8122/// are cleared only after every outcome in the unit is known, so peer
8123/// iteration order cannot falsely clear a rejection recorded later in the same
8124/// bootstrap batch.
8125async fn publish_bootstrap_admission_outcomes(
8126 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8127 outcomes: &[(PeerId, AdmissionOutcome)],
8128 live_discovered: &HashSet<XorName>,
8129) {
8130 let mut rejected_sources = HashSet::new();
8131 let mut clean_sources = HashSet::new();
8132 let mut displaced_keys = HashSet::new();
8133
8134 for (source, outcome) in outcomes {
8135 if outcome.capacity_rejected_count > 0 {
8136 rejected_sources.insert(*source);
8137 } else {
8138 clean_sources.insert(*source);
8139 }
8140 // Only the *key* of a fairness displacement is forfeited here, never
8141 // its owner's standing. Reclaiming a borrowed slot is our own fairness
8142 // decision, not a failure by the peer that held it: stamping the victim
8143 // would let a sustained flooder block our bootstrap drain through an
8144 // unrelated honest peer that never overflowed us. The displaced key
8145 // falls to the same post-bootstrap neighbor-sync and audit/repair
8146 // recovery path that TTL expiry already relies on.
8147 for displacement in &outcome.displaced {
8148 displaced_keys.insert(displacement.key);
8149 }
8150 }
8151 clean_sources.retain(|source| !rejected_sources.contains(source));
8152
8153 let now = Instant::now();
8154 let mut state = bootstrap_state.write().await;
8155 for key in displaced_keys {
8156 state.remove_key(&key);
8157 }
8158 state.pending_keys.extend(live_discovered);
8159 for source in clean_sources {
8160 state.capacity_rejected_sources.remove(&source);
8161 }
8162 for source in rejected_sources {
8163 // First-seen: a source that keeps overflowing us must not keep its own
8164 // record fresh, or bootstrap never drains and auditing stays off.
8165 state.note_capacity_rejected(source, now);
8166 }
8167}
8168
8169#[allow(clippy::too_many_arguments)]
8170async fn admit_and_queue_hints(
8171 self_id: &PeerId,
8172 source_peer: &PeerId,
8173 replica_hints: &[XorName],
8174 paid_hints: &[XorName],
8175 p2p_node: &Arc<P2PNode>,
8176 config: &ReplicationConfig,
8177 storage: &Arc<ChunkStore>,
8178 paid_list: &Arc<PaidList>,
8179 queues: &Arc<RwLock<ReplicationQueues>>,
8180) -> AdmissionOutcome {
8181 let pending_keys: HashSet<XorName> = {
8182 let q = queues.read().await;
8183 q.pending_keys().into_iter().collect()
8184 };
8185
8186 let admitted = admission::admit_hints(
8187 self_id,
8188 replica_hints,
8189 paid_hints,
8190 p2p_node,
8191 config,
8192 storage,
8193 paid_list,
8194 &pending_keys,
8195 )
8196 .await;
8197
8198 let mut q = queues.write().await;
8199 queue_admitted_hints(source_peer, admitted, storage, &mut q)
8200}
8201
8202fn queue_admitted_hints(
8203 source_peer: &PeerId,
8204 admitted: admission::AdmissionResult,
8205 storage: &ChunkStore,
8206 q: &mut ReplicationQueues,
8207) -> AdmissionOutcome {
8208 let mut discovered = HashSet::new();
8209 let mut capacity_rejected_count: usize = 0;
8210 let mut displaced = Vec::new();
8211 let now = Instant::now();
8212
8213 for key in admitted.replica_keys {
8214 if !storage.exists(&key).unwrap_or(false) {
8215 let result = q.add_pending_verify(
8216 key,
8217 VerificationEntry {
8218 state: VerificationState::PendingVerify,
8219 verified_sources: Vec::new(),
8220 tried_sources: HashSet::new(),
8221 created_at: now,
8222 next_verify_at: now,
8223 hint_sources: HashSet::from([*source_peer]),
8224 // Non-empty: this peer claimed possession, so it is a
8225 // fetch-source candidate. Derives HintPipeline::Replica.
8226 replica_hint_sources: HashSet::from([*source_peer]),
8227 unresolved_retries: 0,
8228 no_holder_reported: false,
8229 },
8230 );
8231 match result {
8232 crate::replication::scheduling::AdmissionResult::Admitted => {
8233 discovered.insert(key);
8234 }
8235 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8236 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8237 capacity_rejected_count += 1;
8238 }
8239 }
8240 }
8241 }
8242
8243 for key in admitted.paid_only_keys {
8244 let result = q.add_pending_verify(
8245 key,
8246 VerificationEntry {
8247 state: VerificationState::PendingVerify,
8248 verified_sources: Vec::new(),
8249 tried_sources: HashSet::new(),
8250 created_at: now,
8251 next_verify_at: now,
8252 hint_sources: HashSet::from([*source_peer]),
8253 // Empty: a paid hint makes no possession claim, so this peer is
8254 // not a fetch source. Derives HintPipeline::PaidOnly.
8255 replica_hint_sources: HashSet::new(),
8256 unresolved_retries: 0,
8257 no_holder_reported: false,
8258 },
8259 );
8260 match result {
8261 crate::replication::scheduling::AdmissionResult::Admitted => {
8262 discovered.insert(key);
8263 }
8264 crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8265 crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8266 capacity_rejected_count += 1;
8267 }
8268 }
8269 }
8270
8271 if capacity_rejected_count > 0 {
8272 debug!(
8273 "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
8274 rejected at queue capacity; source will need to re-hint after pending_verify drains"
8275 );
8276 }
8277
8278 displaced.extend(q.take_capacity_displacements());
8279
8280 AdmissionOutcome {
8281 discovered,
8282 capacity_rejected_count,
8283 displaced,
8284 }
8285}
8286
8287// ---------------------------------------------------------------------------
8288// Verification cycle
8289// ---------------------------------------------------------------------------
8290
8291/// Run one verification cycle: process pending keys through quorum checks.
8292#[allow(clippy::too_many_lines)]
8293async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
8294 let cycle_started = Instant::now();
8295 let VerificationCycleContext {
8296 p2p_node,
8297 paid_list,
8298 storage,
8299 queues,
8300 config,
8301 bootstrap_state,
8302 is_bootstrapping,
8303 bootstrap_complete_notify,
8304 last_commitment_by_peer,
8305 ever_capable_peers,
8306 recent_provers,
8307 } = ctx;
8308
8309 // Self-heal the bootstrap drain before any early-return below: abandoned
8310 // capacity-rejection records must expire, and a drain condition that
8311 // became true without a triggering event must still be observed. Pending
8312 // peer requests legitimately block the drain check itself, but not this.
8313 expire_and_recheck_bootstrap_drain(
8314 bootstrap_state,
8315 queues,
8316 is_bootstrapping,
8317 bootstrap_complete_notify,
8318 config.capacity_rejected_max_age(),
8319 )
8320 .await;
8321
8322 // Bootstrap admits one concurrent neighbor batch as an atomic source
8323 // aggregation unit. Do not select newly queued keys until that batch's
8324 // hints and drain accounting have both been published.
8325 if bootstrap_state.read().await.pending_peer_requests > 0 {
8326 return;
8327 }
8328
8329 // Evict stale entries that have been pending too long (e.g. unreachable
8330 // verification targets during a network partition).
8331 let stale_pending_keys = {
8332 let mut q = queues.write().await;
8333 q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
8334 };
8335 if !stale_pending_keys.is_empty() {
8336 update_bootstrap_after_verification(
8337 &stale_pending_keys,
8338 bootstrap_state,
8339 queues,
8340 is_bootstrapping,
8341 bootstrap_complete_notify,
8342 )
8343 .await;
8344 }
8345
8346 let pending_keys = {
8347 let mut q = queues.write().await;
8348 // Re-check while holding the queue write lock used by fair selection.
8349 // This closes the race
8350 // where a bootstrap batch starts after the early check: the batch
8351 // cannot publish its hints under the queue write lock until this
8352 // selection either returns or declines to run.
8353 if bootstrap_state.read().await.pending_peer_requests > 0 {
8354 return;
8355 }
8356 q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
8357 };
8358
8359 if pending_keys.is_empty() {
8360 return;
8361 }
8362 let initial_pending_count = pending_keys.len();
8363
8364 // Capacity verdict for this cycle — the same pre-check the PUT handler and
8365 // the fresh-offer path already run (V2-411), read once and reused below.
8366 //
8367 // It gates only the two steps that exist to enable a fetch: the presence
8368 // probe that discovers holders, and the promotion that queues the download.
8369 // Everything a cycle does that does not need a local write still runs on a
8370 // full node — the local paid-list fast path, `PaidForList` convergence
8371 // through the quorum round, and the terminal checks that retire a key this
8372 // node already holds or is no longer admitted for. Gating earlier than this
8373 // would stop a full node learning which of its keys were paid for, and
8374 // would strand keys that should have retired, which keeps bootstrap drain
8375 // pending and audits disabled until stale eviction.
8376 // Only a *full* disk is a standing condition worth minutes of backoff. A
8377 // failed `statvfs` says nothing about available space and may have cleared
8378 // by the next cycle, so it is treated as writable here and left to the
8379 // pre-check at the dial, which queries again and may well permit the write.
8380 let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8381 // Counted per gate rather than combined. `local_paid_probe` below counts
8382 // probes actually sent, so it reads zero once the first gate fires; keeping
8383 // the two deferral counts apart is what lets an operator see which branch a
8384 // full node's keys are taking without adding a code path to find out.
8385 let mut capacity_deferred_probe = 0usize;
8386 let mut capacity_deferred_promote = 0usize;
8387
8388 let self_id = *p2p_node.peer_id();
8389
8390 // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8391 // step 4). Paid-list membership settles *validity* — the key is known-paid,
8392 // so no quorum round is needed. It says nothing about whether we must hold
8393 // the bytes; that is decided below.
8394 let mut local_paid_keys = Vec::new();
8395 let mut keys_needing_network = Vec::new();
8396 let mut terminal_keys: Vec<XorName> = Vec::new();
8397 {
8398 let mut q = queues.write().await;
8399 for key in &pending_keys {
8400 if paid_list.contains(key).unwrap_or(false) {
8401 if q.set_pending_state(key, VerificationState::PaidListVerified) {
8402 local_paid_keys.push(*key);
8403 }
8404 } else {
8405 keys_needing_network.push(*key);
8406 }
8407 }
8408 }
8409
8410 // Storage responsibility is a live routing question, decided identically
8411 // for every known-paid key regardless of how the advertising peer labelled
8412 // its hint — a replica hint is a possession *claim* by the sender, never
8413 // permission for us to store. Held outside the queue lock: `is_responsible`
8414 // awaits into the DHT manager.
8415 let mut local_paid_presence_probe_keys = Vec::new();
8416 if !local_paid_keys.is_empty() {
8417 let mut terminal_paid = Vec::new();
8418 for key in local_paid_keys {
8419 if storage.exists(&key).unwrap_or(false) {
8420 terminal_paid.push(key);
8421 } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8422 // We carry storage responsibility and lack the bytes. The
8423 // presence probe below discovers holders to fetch from; it is
8424 // source discovery, not re-verification.
8425 local_paid_presence_probe_keys.push(key);
8426 } else {
8427 terminal_paid.push(key);
8428 }
8429 }
8430
8431 if !terminal_paid.is_empty() {
8432 let mut q = queues.write().await;
8433 for key in terminal_paid {
8434 q.remove_pending(&key);
8435 terminal_keys.push(key);
8436 }
8437 }
8438
8439 // Capacity gate, first of two. Everything above this point has already
8440 // run: authorization succeeded via the local `PaidForList` hit, and the
8441 // keys that should retire (already held, or no longer storage-admitted)
8442 // have retired. What is left is a probe whose only purpose is finding a
8443 // holder to download from, and this node cannot write what it would
8444 // download.
8445 if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8446 let mut q = queues.write().await;
8447 for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8448 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8449 capacity_deferred_probe += 1;
8450 }
8451 }
8452 }
8453 }
8454
8455 let local_paid_probe_count = local_paid_presence_probe_keys.len();
8456 let keys_needing_network_count = keys_needing_network.len();
8457 // Keys this cycle put back because no peer claimed possession. Reported in
8458 // aggregate below; the per-key line is warned once per entry, not per retry.
8459 let mut no_holder_deferrals = 0usize;
8460
8461 // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8462 // step 4, authorization succeeds immediately; run a presence-only probe
8463 // to find any holder we can fetch from.
8464 if !local_paid_presence_probe_keys.is_empty() {
8465 let targets = quorum::compute_presence_targets(
8466 &local_paid_presence_probe_keys,
8467 p2p_node,
8468 config,
8469 &self_id,
8470 )
8471 .await;
8472 let evidence = quorum::run_verification_round(
8473 &local_paid_presence_probe_keys,
8474 &targets,
8475 p2p_node,
8476 config,
8477 )
8478 .await;
8479
8480 let mut q = queues.write().await;
8481 for key in local_paid_presence_probe_keys {
8482 if storage.exists(&key).unwrap_or(false) {
8483 q.remove_pending(&key);
8484 terminal_keys.push(key);
8485 continue;
8486 }
8487 let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8488 quorum::present_sources_for_key(&key, ev, &targets)
8489 });
8490 if let Some(entry) = q.get_pending(&key) {
8491 add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8492 }
8493 if sources.is_empty() {
8494 no_holder_deferrals += 1;
8495 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8496 let first_report = q.claim_no_holder_report(&key);
8497 report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8498 } else {
8499 // A holder answered, so whatever came before is not a run of
8500 // consecutive failures any more. Clear before promoting: if the
8501 // fetch queue is full the entry stays pending, and it must not
8502 // carry the old backoff.
8503 q.clear_unresolved(&key);
8504 let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8505 // Atomic remove+enqueue: if fetch_queue is at capacity, the
8506 // pending entry is preserved and retried next cycle (no
8507 // silent drop of verified replica-repair work).
8508 let _ = q.promote_pending_to_fetch(key, distance, sources);
8509 }
8510 }
8511 }
8512
8513 // Steps 2-5: Network verification (skipped if all keys resolved locally).
8514 if !keys_needing_network.is_empty() {
8515 // Step 2: Compute targets and run network verification round.
8516 let targets =
8517 quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8518 .await;
8519
8520 let evidence =
8521 quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8522
8523 // Step 3: Evaluate results — collect outcomes without holding the write
8524 // lock across paid-list I/O.
8525 //
8526 // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8527 // table and recent_provers cache up front so the synchronous
8528 // evaluate_key_evidence_with_holder_check predicate can consult
8529 // them without awaiting. The predicate downgrades a Present
8530 // claim to Unresolved unless the peer is credited for that key.
8531 // Snapshot per-peer commitment data. We need two views:
8532 // - `commitment_by_peer_snapshot`: peers that currently have
8533 // a verified commitment record on file (used to look up
8534 // their current hash).
8535 // - `capable_peer_snapshot`: the sticky "ever v12-capable"
8536 // set. Sourced from a separate set rather than the
8537 // commitment map so eviction (PeerRemoved cleanup, sybil
8538 // cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8539 // a previously-v12 peer to "legacy" credit-unconditionally.
8540 // Legacy / pre-v12 peers that have never sent a commitment
8541 // remain absent from the set and are credited via the
8542 // legacy path so mixed-version networks stay live.
8543 let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8544 let map = last_commitment_by_peer.read().await;
8545 map.iter()
8546 // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8547 // of every peer's ~5 KiB commitment.
8548 .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8549 .collect()
8550 };
8551 let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8552 // Take a full snapshot of recent_provers under the read lock,
8553 // then release. The cache is bounded (16/key × keys), so the
8554 // clone is cheap.
8555 let provers_snapshot = recent_provers.read().await.clone();
8556 // For the replica-fetch path, we need to know whether THIS
8557 // node already holds the key being verified. The v12 §6
8558 // holder-credit gate is meant to prevent uncredited Present
8559 // claims from contributing to paid-list / reward quorum for
8560 // keys we DO hold (and could audit ourselves). For keys we
8561 // are trying to FETCH (i.e. not in local storage), there is
8562 // no possible local audit credit, and gating the presence
8563 // quorum on credit would deadlock replica-repair in a
8564 // fully v12-capable close group.
8565 let mut locally_held: HashSet<XorName> = HashSet::new();
8566 for key in &keys_needing_network {
8567 if storage.exists(key).unwrap_or(false) {
8568 locally_held.insert(*key);
8569 }
8570 }
8571 let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8572 if !locally_held.contains(key) {
8573 // Replica-fetch path: we don't hold this key, so we
8574 // cannot have collected audit credit for it. Trust
8575 // Present claims to drive fetch-source promotion;
8576 // chunk-PUT payment_verifier is the security backstop
8577 // when the bytes actually arrive.
8578 return true;
8579 }
8580 if !capable_peer_snapshot.contains(peer) {
8581 // Pre-v12 / legacy peer that has never gossiped a
8582 // commitment. The v12 §6 holder-eligibility check
8583 // doesn't apply: their Present evidence comes through
8584 // the legacy path and we credit it unconditionally
8585 // so a mixed-version network stays live during
8586 // transition.
8587 return true;
8588 }
8589 let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8590 // Peer is commitment_capable (sticky) but currently
8591 // has no live commitment record on file (e.g. their
8592 // last gossip was evicted from the LRU cache, or it
8593 // failed verification). Withhold credit until they
8594 // re-prove storage under a fresh commitment.
8595 return false;
8596 };
8597 provers_snapshot.is_credited_holder(key, peer, hash)
8598 };
8599
8600 let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8601 {
8602 let q = queues.read().await;
8603 for key in &keys_needing_network {
8604 let Some(ev) = evidence.get(key) else {
8605 continue;
8606 };
8607 if q.get_pending(key).is_none() {
8608 continue;
8609 }
8610 let outcome = quorum::evaluate_key_evidence_with_holder_check(
8611 key,
8612 ev,
8613 &targets,
8614 config,
8615 holder_credit,
8616 );
8617 evaluated.push((*key, outcome));
8618 }
8619 } // read lock released
8620
8621 // Step 4: Insert verified keys into PaidForList (no lock held).
8622 let mut paid_insert_keys: Vec<XorName> = Vec::new();
8623 for (key, outcome) in &evaluated {
8624 if matches!(
8625 outcome,
8626 KeyVerificationOutcome::QuorumVerified { .. }
8627 | KeyVerificationOutcome::PaidListVerified { .. }
8628 ) {
8629 paid_insert_keys.push(*key);
8630 }
8631 }
8632 for key in &paid_insert_keys {
8633 if let Err(e) = paid_list.insert(key).await {
8634 warn!("Failed to add verified key to PaidForList: {e}");
8635 }
8636 }
8637
8638 // Verification established validity; the paid-list insert above records
8639 // it. Downloading the bytes is a separate duty, owed only by the
8640 // storage-admission group, asked on the same terms for every verified
8641 // key — the advertising peer's replica/paid labelling is a claim about
8642 // itself and carries no authority over what we store. This check is a
8643 // cheap pre-filter that keeps never-responsible keys out of the fetch
8644 // queue entirely; the authoritative gate is the per-attempt recheck in
8645 // `execute_single_fetch`, because a key can wait in the nearest-first
8646 // fetch queue long enough for this promotion-time answer to go stale.
8647 let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8648 for (key, outcome) in &evaluated {
8649 if matches!(
8650 outcome,
8651 KeyVerificationOutcome::QuorumVerified { .. }
8652 | KeyVerificationOutcome::PaidListVerified { .. }
8653 ) && !storage.exists(key).unwrap_or(false)
8654 && is_storage_admitted(&self_id, key, p2p_node, config).await
8655 {
8656 fetch_allowed_keys.insert(*key);
8657 }
8658 }
8659
8660 // Step 5: Update queues with the evaluated outcomes.
8661 let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
8662 let mut q = queues.write().await;
8663 for (key, outcome) in evaluated {
8664 let replica_hint_sources = q
8665 .get_pending(&key)
8666 .map(|entry| entry.replica_hint_sources.clone())
8667 .unwrap_or_default();
8668 if let Some(ev) = evidence.get(&key) {
8669 if let Some(source) =
8670 punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8671 {
8672 *bad_singleton_hints.entry(source).or_insert(0) += 1;
8673 }
8674 }
8675 match outcome {
8676 KeyVerificationOutcome::QuorumVerified { sources }
8677 | KeyVerificationOutcome::PaidListVerified { sources } => {
8678 let mut fetch_sources = sources;
8679 add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8680 let fetch_eligible = fetch_allowed_keys.contains(&key);
8681 if fetch_eligible && write_blocked {
8682 // Capacity gate, second of two, and deliberately after
8683 // Step 4: the key is now recorded in `PaidForList` and
8684 // its verification stands. Only the download is held,
8685 // because `execute_single_fetch` would refuse it and
8686 // hand the key straight back here.
8687 if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8688 capacity_deferred_promote += 1;
8689 }
8690 } else if fetch_eligible && !fetch_sources.is_empty() {
8691 // A holder answered; see the matching clear on the
8692 // local-paid path.
8693 q.clear_unresolved(&key);
8694 let distance =
8695 crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8696 // Atomic remove+enqueue: on fetch_queue capacity miss
8697 // the pending entry is preserved so this verified key
8698 // is retried on the next cycle (no silent drop).
8699 let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8700 // Not terminal — either moved to fetch queue, or
8701 // retained as pending until queue drains.
8702 } else if fetch_eligible && fetch_sources.is_empty() {
8703 no_holder_deferrals += 1;
8704 let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8705 let first_report = q.claim_no_holder_report(&key);
8706 report_unresolved_deferral(
8707 "Verified storage-admitted key",
8708 &key,
8709 outcome,
8710 first_report,
8711 );
8712 } else {
8713 q.remove_pending(&key);
8714 terminal_keys.push(key);
8715 }
8716 }
8717 KeyVerificationOutcome::QuorumFailed => {
8718 q.remove_pending(&key);
8719 terminal_keys.push(key);
8720 }
8721 KeyVerificationOutcome::QuorumInconclusive => {
8722 q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8723 // Backed off like any other unresolved round, but it does
8724 // NOT claim the no-holder report: nothing yet says this key
8725 // has no holder, so the first round that does say so must
8726 // still be the one that warns.
8727 let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8728 }
8729 }
8730 }
8731 drop(q);
8732
8733 for (peer, bad_hint_count) in bad_singleton_hints {
8734 let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8735 warn!(
8736 "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8737 sole-source replica hints; \
8738 reporting {reports} bounded trust failure(s)"
8739 );
8740 for _ in 0..reports {
8741 p2p_node
8742 .report_trust_event(
8743 &peer,
8744 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8745 )
8746 .await;
8747 }
8748 }
8749 }
8750
8751 // Step 6: Remove terminal keys from bootstrap pending set and re-check
8752 // the drain condition.
8753 update_bootstrap_after_verification(
8754 &terminal_keys,
8755 bootstrap_state,
8756 queues,
8757 is_bootstrapping,
8758 bootstrap_complete_notify,
8759 )
8760 .await;
8761
8762 let (pending_after, fetch_after, in_flight_after) = {
8763 let q = queues.read().await;
8764 (
8765 q.pending_count(),
8766 q.fetch_queue_count(),
8767 q.in_flight_count(),
8768 )
8769 };
8770 let terminal_key_count = terminal_keys.len();
8771 let elapsed_ms = cycle_started.elapsed().as_millis();
8772
8773 if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8774 info!(
8775 target: "ant_node::replication::verification",
8776 "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}",
8777 );
8778 } else {
8779 debug!(
8780 target: "ant_node::replication::verification",
8781 "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}",
8782 );
8783 }
8784}
8785
8786/// Report a verification round that left a key without a usable holder.
8787///
8788/// Warns once per entry — the first failure is news, and by the hundredth the
8789/// node is re-asking peers it has already exhausted. Later failures stay at
8790/// `debug`, and the per-cycle count is carried in the cycle summary so the
8791/// scale of a backlog is still visible without a line per key per retry.
8792///
8793/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8794/// number: a round may advance the count without producing a no-holder result,
8795/// and such a round must not consume the warning.
8796///
8797/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8798/// a holder clears it, so a later relapse warns again: "once per episode", not
8799/// "once ever".
8800fn report_unresolved_deferral(
8801 what: &str,
8802 key: &XorName,
8803 outcome: Option<DeferralOutcome>,
8804 first_report: bool,
8805) {
8806 let Some(outcome) = outcome else {
8807 // The entry left `pending_verify` under the same lock; nothing deferred.
8808 return;
8809 };
8810 if first_report {
8811 warn!(
8812 "{what} {} has no responding holders yet; deferring retry",
8813 hex::encode(key)
8814 );
8815 } else {
8816 debug!(
8817 "{what} {} still has no responding holders after {} attempts; \
8818 retrying in {}s",
8819 hex::encode(key),
8820 outcome.attempt,
8821 outcome.retry_after.as_secs()
8822 );
8823 }
8824}
8825
8826/// Add peers that claimed possession as fallback fetch sources.
8827///
8828/// Paid-only advertisers make no possession claim and are absent from
8829/// `replica_hint_sources` by construction, so they are never added.
8830fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8831 for source in replica_hint_sources {
8832 if !sources.contains(source) {
8833 sources.push(*source);
8834 }
8835 }
8836}
8837
8838/// Return the sole replica advertiser when either the close group definitively
8839/// rejects the key or the advertiser explicitly denies possessing it.
8840/// Paid-only advertisements, corroborated replica hints, and inconclusive
8841/// rounds without that direct contradiction are deliberately non-penalizing.
8842fn punishable_singleton_replica_hint_source(
8843 replica_hint_sources: &HashSet<PeerId>,
8844 outcome: &KeyVerificationOutcome,
8845 evidence: &crate::replication::types::KeyVerificationEvidence,
8846) -> Option<PeerId> {
8847 // A paid-only advertiser leaves this set empty, so the sole-source lane is
8848 // reserved for peers that actually claimed possession.
8849 if replica_hint_sources.len() != 1 {
8850 return None;
8851 }
8852 let source = *replica_hint_sources.iter().next()?;
8853 let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8854 let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8855
8856 (rejected_by_close_group || denied_possession).then_some(source)
8857}
8858
8859/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8860/// bootstrap pending set and transition out of bootstrapping when drained.
8861async fn update_bootstrap_after_verification(
8862 terminal_keys: &[XorName],
8863 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8864 queues: &Arc<RwLock<ReplicationQueues>>,
8865 is_bootstrapping: &Arc<RwLock<bool>>,
8866 bootstrap_complete_notify: &Arc<Notify>,
8867) {
8868 if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8869 return;
8870 }
8871 {
8872 let mut bs = bootstrap_state.write().await;
8873 for key in terminal_keys {
8874 bs.remove_key(key);
8875 }
8876 }
8877 let q = queues.read().await;
8878 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8879 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8880 }
8881}
8882
8883/// Retire bootstrap work owed by a peer that permanently left the routing
8884/// table, then immediately re-check drain so this removal can complete
8885/// bootstrap without waiting for an unrelated pipeline event.
8886async fn update_bootstrap_after_peer_removed(
8887 peer: &PeerId,
8888 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8889 queues: &Arc<RwLock<ReplicationQueues>>,
8890 is_bootstrapping: &Arc<RwLock<bool>>,
8891 bootstrap_complete_notify: &Arc<Notify>,
8892) {
8893 let orphaned_keys = queues.write().await.remove_hint_source(peer);
8894 let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8895
8896 if !orphaned_keys.is_empty() {
8897 let mut state = bootstrap_state.write().await;
8898 for key in &orphaned_keys {
8899 state.remove_key(key);
8900 }
8901 }
8902
8903 if orphaned_keys.is_empty() && !cleared_rejection {
8904 return;
8905 }
8906 let q = queues.read().await;
8907 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8908 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8909 }
8910}
8911
8912/// Periodic bootstrap-drain self-healing, run on every verification worker
8913/// tick until bootstrap drains.
8914///
8915/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8916/// recording of a capacity rejection leaves an entry no future event can
8917/// clear — `max_age` expiry is its only exit. And a clean-cycle
8918/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8919/// quiet node the drain condition can become true with nothing left to
8920/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8921/// drain itself, so this is invoked before `run_verification_cycle`'s
8922/// early-returns.
8923async fn expire_and_recheck_bootstrap_drain(
8924 bootstrap_state: &Arc<RwLock<BootstrapState>>,
8925 queues: &Arc<RwLock<ReplicationQueues>>,
8926 is_bootstrapping: &Arc<RwLock<bool>>,
8927 bootstrap_complete_notify: &Arc<Notify>,
8928 max_age: Duration,
8929) {
8930 if bootstrap_state.read().await.is_drained() {
8931 return;
8932 }
8933 bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8934 let q = queues.read().await;
8935 if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8936 complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8937 }
8938}
8939
8940/// Set `is_bootstrapping` to `false` and wake all waiters.
8941async fn complete_bootstrap(
8942 is_bootstrapping: &Arc<RwLock<bool>>,
8943 bootstrap_complete_notify: &Arc<Notify>,
8944) {
8945 *is_bootstrapping.write().await = false;
8946 bootstrap_complete_notify.notify_waiters();
8947 info!("Replication bootstrap complete");
8948}
8949
8950// ---------------------------------------------------------------------------
8951// Fetch types and single-fetch executor
8952// ---------------------------------------------------------------------------
8953
8954/// Result classification for a single fetch attempt.
8955enum FetchResult {
8956 /// Data fetched, integrity-checked, and stored successfully.
8957 Stored,
8958 /// Content-address integrity check failed — do not retry.
8959 IntegrityFailed,
8960 /// Source failed (network error or non-success response) — retryable.
8961 SourceFailed,
8962 /// This node could not write the chunk locally: the capacity pre-check
8963 /// refused before the dial, or `put` failed after the bytes arrived.
8964 ///
8965 /// Distinct from [`Self::SourceFailed`] because nothing about the source
8966 /// is implicated, and because the remedy is the opposite one. A source
8967 /// failure should move on to the next holder; a local write failure must
8968 /// not — every remaining source would send the same chunk into the same
8969 /// full disk. The key returns to verification instead, so a later cycle
8970 /// retries it once local capacity allows. That is a retry path, not a
8971 /// liveness guarantee: `evict_stale` still expires the entry at
8972 /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8973 /// which re-acquisition depends on a fresh hint.
8974 LocalWriteFailed,
8975 /// This node already holds the key, so there is nothing to fetch —
8976 /// terminal, exactly like [`Self::Stored`], because the duty is already
8977 /// discharged.
8978 ///
8979 /// Responsibility is rechecked at download time; possession has to be too.
8980 /// The earlier gates already drop held keys out of the fetch pipeline —
8981 /// `queue_admitted_hints` skips them, and the promotion-time
8982 /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8983 /// them. (`is_relevant` is not one of them: possession there makes a key
8984 /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8985 /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8986 /// client PUT, or another source landing first. The nearest-first fetch
8987 /// queue is deep enough for that window to be real.
8988 ///
8989 /// This check must also precede the capacity pre-check below, because
8990 /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
8991 /// it, a full node would decline a key it already holds, which `put` would
8992 /// have accepted as a duplicate.
8993 AlreadyHeld,
8994 /// Live routing state no longer places this node in the storage-admission
8995 /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8996 /// the fetch was serving has lapsed, so no alternate source is tried and
8997 /// no trust event is reported: the source did nothing wrong.
8998 NoLongerResponsible,
8999}
9000
9001/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
9002/// worker loop to update queue state.
9003struct FetchOutcome {
9004 key: XorName,
9005 result: FetchResult,
9006}
9007
9008/// What the fetch worker must do next for a key whose fetch attempt resolved.
9009#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9010enum FetchFollowUp {
9011 /// The key terminally left the fetch pipeline (its in-flight entry is
9012 /// removed and any verification retry-slot reservation released); the
9013 /// caller must run bootstrap accounting for it.
9014 Terminal,
9015 /// The key returned to `pending_verify` for a later verification round.
9016 RequeuedForVerification,
9017 /// Retry immediately from this next untried verified source.
9018 RetryFrom(PeerId),
9019}
9020
9021/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
9022///
9023/// Split out of the fetch-worker loop so the per-variant queue transitions
9024/// are unit-testable without a live network. The caller holds the queues
9025/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
9026/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
9027/// retry-slot reservation, and the caller's terminal handling shrinks the
9028/// bootstrap pending set — dropping the key without that accounting would
9029/// stall bootstrap drain forever.
9030///
9031/// The nursery `option_if_let_else` rewrite is impossible here: both
9032/// `map_or_else` closures would need `&mut *q` simultaneously.
9033#[allow(clippy::option_if_let_else)]
9034fn apply_fetch_result(
9035 q: &mut ReplicationQueues,
9036 key: &XorName,
9037 result: &FetchResult,
9038 verification_retry_after: Duration,
9039) -> FetchFollowUp {
9040 match result {
9041 FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
9042 q.complete_fetch(key);
9043 FetchFollowUp::Terminal
9044 }
9045 FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
9046 if let Some(next_peer) = q.retry_fetch(key) {
9047 FetchFollowUp::RetryFrom(next_peer)
9048 } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
9049 FetchFollowUp::RequeuedForVerification
9050 } else {
9051 FetchFollowUp::Terminal
9052 }
9053 }
9054 // No `retry_fetch`: the local write is what failed, so every other
9055 // source would be asked to send the same chunk into the same full
9056 // disk. Requeueing for verification is what keeps the key from being
9057 // stranded — it comes back once capacity allows — and the fallthrough
9058 // to `Terminal` when there is no retry metadata is what keeps
9059 // bootstrap drain accounting correct, exactly as for a source failure.
9060 //
9061 // The ordinary requeue delay, deliberately. A standing capacity block
9062 // does not need a longer one here: the key returns to pending, and the
9063 // gate at the head of the next cycle defers it for minutes. A separate
9064 // backoff on this path would duplicate that to save one 15 s round, on
9065 // a race the gate already makes rare.
9066 FetchResult::LocalWriteFailed => {
9067 if q.requeue_fetch_for_verification(key, verification_retry_after) {
9068 FetchFollowUp::RequeuedForVerification
9069 } else {
9070 FetchFollowUp::Terminal
9071 }
9072 }
9073 }
9074}
9075
9076/// Whether this node currently sits inside the storage-admission group for
9077/// `key`, per live local routing state.
9078///
9079/// This is the one question every storage decision in this module asks; see
9080/// [`admission::is_responsible`]. A purely local routing-table lookup — no
9081/// network I/O — but it awaits into the DHT manager, so callers must not
9082/// hold the queues lock across it.
9083async fn is_storage_admitted(
9084 self_id: &PeerId,
9085 key: &XorName,
9086 p2p_node: &Arc<P2PNode>,
9087 config: &ReplicationConfig,
9088) -> bool {
9089 admission::is_responsible(
9090 self_id,
9091 key,
9092 p2p_node,
9093 storage_admission_width(config.close_group_size),
9094 )
9095 .await
9096}
9097
9098#[allow(clippy::too_many_lines)]
9099/// Execute a single fetch request against `source` for `key`.
9100///
9101/// Handles encoding, network I/O, integrity checking, storage, and trust
9102/// event reporting. Returns a [`FetchOutcome`] so the caller can update
9103/// queue state without holding any locks during the network round-trip.
9104///
9105/// This is the authoritative storage-responsibility gate: each attempt —
9106/// including every per-source retry, which re-enters here — rechecks live
9107/// routing state before spending bandwidth, and once more before writing
9108/// bytes that arrived after a round-trip. The verification-time check that
9109/// promoted the key into the fetch queue is only a pre-filter; the queue is
9110/// nearest-first and deep, so a promotion decision can go stale under
9111/// topology churn before the key is ever dequeued.
9112async fn execute_single_fetch(
9113 p2p_node: Arc<P2PNode>,
9114 storage: Arc<ChunkStore>,
9115 config: Arc<ReplicationConfig>,
9116 key: XorName,
9117 source: PeerId,
9118) -> FetchOutcome {
9119 let self_id = *p2p_node.peer_id();
9120 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9121 debug!(
9122 "Skipping fetch for {}: no longer in the storage-admission group",
9123 hex::encode(key)
9124 );
9125 return FetchOutcome {
9126 key,
9127 result: FetchResult::NoLongerResponsible,
9128 };
9129 }
9130
9131 // Possession, then capacity — both before the dial, and in that order.
9132 //
9133 // `ChunkStore::put` tests `exists` before it tests disk space, so a full
9134 // node still accepts a key it already holds. Checking possession first is
9135 // what keeps this pair of gates from declining work `put` would have
9136 // taken.
9137 if storage.exists(&key).unwrap_or(false) {
9138 debug!(
9139 "Skipping fetch for {}: already held locally",
9140 hex::encode(key)
9141 );
9142 return FetchOutcome {
9143 key,
9144 result: FetchResult::AlreadyHeld,
9145 };
9146 }
9147
9148 // Capacity is checked before the dial rather than after the bytes arrive.
9149 // `put` runs this same check on every write of a key it does not already
9150 // hold, so this reaches the same verdict `put` would reach *at this
9151 // instant*. It is not a guarantee about the later write: both answers can
9152 // change across the round trip. Space freed in between would have let a
9153 // post-download `put` succeed, so a refusal here can cost a fleeting
9154 // acquisition and one retry cycle of delay; space lost in between is why
9155 // the check inside `put` still has to stay.
9156 //
9157 // What it buys is that the refusal costs no bandwidth. Without it a
9158 // disk-full node pulls the whole chunk over the network first, and the
9159 // failure is then classified as the source's — no trust event, but the
9160 // worker walks to every remaining holder, and each re-uploads the same
9161 // chunk into the same full disk.
9162 if let Err(e) = storage.check_capacity() {
9163 debug!(
9164 "Skipping fetch for {}: local storage cannot accept a write: {e}",
9165 hex::encode(key)
9166 );
9167 return FetchOutcome {
9168 key,
9169 result: FetchResult::LocalWriteFailed,
9170 };
9171 }
9172
9173 let request = protocol::FetchRequest { key };
9174 let msg = ReplicationMessage {
9175 request_id: rand::thread_rng().gen::<u64>(),
9176 body: ReplicationMessageBody::FetchRequest(request),
9177 };
9178
9179 let encoded = match msg.encode() {
9180 Ok(data) => data,
9181 Err(e) => {
9182 warn!("Failed to encode fetch request: {e}");
9183 return FetchOutcome {
9184 key,
9185 result: FetchResult::SourceFailed,
9186 };
9187 }
9188 };
9189
9190 let result = p2p_node
9191 .send_request(
9192 &source,
9193 REPLICATION_PROTOCOL_ID,
9194 encoded,
9195 config.fetch_request_timeout,
9196 )
9197 .await;
9198
9199 match result {
9200 Ok(response) => {
9201 let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
9202 p2p_node
9203 .report_trust_event(
9204 &source,
9205 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9206 )
9207 .await;
9208 return FetchOutcome {
9209 key,
9210 result: FetchResult::SourceFailed,
9211 };
9212 };
9213
9214 match resp_msg.body {
9215 ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
9216 key: resp_key,
9217 data,
9218 }) => {
9219 // Validate the response key matches the requested key.
9220 // A malicious peer could serve valid data for a different
9221 // key, passing integrity checks while the requested key
9222 // is falsely marked as fetched.
9223 if resp_key != key {
9224 warn!(
9225 "Fetch response key mismatch: requested {}, got {}",
9226 hex::encode(key),
9227 hex::encode(resp_key)
9228 );
9229 p2p_node
9230 .report_trust_event(
9231 &source,
9232 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9233 )
9234 .await;
9235 return FetchOutcome {
9236 key,
9237 result: FetchResult::IntegrityFailed,
9238 };
9239 }
9240
9241 // Enforce chunk size invariant on fetched data.
9242 // Checked before the content-address hash to avoid
9243 // hashing up to 10 MiB of oversized junk data.
9244 if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
9245 warn!(
9246 "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
9247 hex::encode(resp_key),
9248 data.len(),
9249 crate::ant_protocol::MAX_CHUNK_SIZE,
9250 );
9251 p2p_node
9252 .report_trust_event(
9253 &source,
9254 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9255 )
9256 .await;
9257 return FetchOutcome {
9258 key,
9259 result: FetchResult::IntegrityFailed,
9260 };
9261 }
9262
9263 // Content-address integrity check.
9264 let computed = crate::client::compute_address(&data);
9265 if computed != resp_key {
9266 warn!(
9267 "Fetched record integrity check failed: expected {}, got {}",
9268 hex::encode(resp_key),
9269 hex::encode(computed)
9270 );
9271 p2p_node
9272 .report_trust_event(
9273 &source,
9274 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9275 )
9276 .await;
9277 return FetchOutcome {
9278 key,
9279 result: FetchResult::IntegrityFailed,
9280 };
9281 }
9282
9283 // Responsibility can lapse during the network round-trip.
9284 // The bandwidth is already spent; declining the write is
9285 // what still avoids the disk write and the later
9286 // fetch→store→prune churn. Edge flapping is dampened by
9287 // the margin `storage_admission_width` adds over
9288 // `close_group_size`.
9289 if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9290 debug!(
9291 "Fetched {} but responsibility lapsed in transit; not storing",
9292 hex::encode(key)
9293 );
9294 return FetchOutcome {
9295 key,
9296 result: FetchResult::NoLongerResponsible,
9297 };
9298 }
9299
9300 if let Err(e) = storage.put(&resp_key, &data).await {
9301 // The bytes arrived and passed the content-address
9302 // check, so the source did its job; the failure is
9303 // entirely local (disk-full, or a storage error). Any
9304 // valid source must serve identical content, so trying
9305 // the next one cannot cure a local error — it only
9306 // re-downloads the same chunk into the same store.
9307 warn!(
9308 "Failed to store fetched record {}: {e}",
9309 hex::encode(resp_key)
9310 );
9311 return FetchOutcome {
9312 key,
9313 result: FetchResult::LocalWriteFailed,
9314 };
9315 }
9316
9317 FetchOutcome {
9318 key,
9319 result: FetchResult::Stored,
9320 }
9321 }
9322 ReplicationMessageBody::FetchResponse(
9323 ref response @ (protocol::FetchResponse::NotFound { .. }
9324 | protocol::FetchResponse::Error { .. }),
9325 ) => {
9326 // This peer was selected as a fetch source because it recently
9327 // answered `Present` during verification, so either answer means it
9328 // could not serve a chunk it had just claimed.
9329 if let protocol::FetchResponse::Error { reason, .. } = response {
9330 warn!(
9331 "Fetch: peer {source} returned error for {}: {reason}",
9332 hex::encode(key)
9333 );
9334 } else {
9335 warn!(
9336 "Fetch: verified source {source} returned NotFound for {}",
9337 hex::encode(key)
9338 );
9339 }
9340 p2p_node
9341 .report_trust_event(
9342 &source,
9343 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9344 )
9345 .await;
9346 FetchOutcome {
9347 key,
9348 result: FetchResult::SourceFailed,
9349 }
9350 }
9351 _ => {
9352 // Unexpected message type — treat as malformed.
9353 p2p_node
9354 .report_trust_event(
9355 &source,
9356 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9357 )
9358 .await;
9359 FetchOutcome {
9360 key,
9361 result: FetchResult::SourceFailed,
9362 }
9363 }
9364 }
9365 }
9366 Err(e) => {
9367 debug!("Fetch request to {source} failed: {e}");
9368 // No ApplicationFailure here — P2PNode::send_request() already
9369 // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9370 FetchOutcome {
9371 key,
9372 result: FetchResult::SourceFailed,
9373 }
9374 }
9375 }
9376}
9377
9378// ---------------------------------------------------------------------------
9379// Audit result handler
9380// ---------------------------------------------------------------------------
9381
9382/// Format the first confirmed-failed key as a 16-hex-char label.
9383///
9384/// Pairs with `challenged_peer` to form a stable cross-host correlation
9385/// handle in the audit-failure log line, e.g.
9386///
9387/// ```text
9388/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9389/// ```
9390///
9391/// Falls back to `"0x"` when the list is empty so the log line never
9392/// contains a misleading default.
9393fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9394 confirmed_failed_keys.first().map_or_else(
9395 || "0x".to_string(),
9396 |k| format!("0x{}", hex::encode(&k[..8])),
9397 )
9398}
9399
9400/// Execute the side effects for a subtree storage-commitment audit failure.
9401///
9402/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9403/// legitimately time out on slow or loaded honest peers, so it never touches the
9404/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9405/// failures still penalise immediately and revoke holder credit.
9406async fn handle_subtree_failed_audit(
9407 challenged_peer: &PeerId,
9408 confirmed_failed_key_count: usize,
9409 reason: &AuditFailureReason,
9410 p2p_node: &Arc<P2PNode>,
9411 sync_state: &Arc<RwLock<NeighborSyncState>>,
9412 recent_provers: &Arc<RwLock<RecentProvers>>,
9413) {
9414 if matches!(reason, AuditFailureReason::Timeout) {
9415 debug!(
9416 "Audit timeout for {challenged_peer} fully graced \
9417 (subtree audit does not evict on timeout)"
9418 );
9419 return;
9420 }
9421
9422 // The caller already logged the rich failure line with reason + per-category
9423 // summary; avoid a redundant second error log here.
9424 let _ = confirmed_failed_key_count;
9425 {
9426 let mut state = sync_state.write().await;
9427 state.clear_active_bootstrap_claim(challenged_peer);
9428 }
9429 {
9430 let mut provers_guard = recent_provers.write().await;
9431 apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9432 }
9433 p2p_node
9434 .report_trust_event(
9435 challenged_peer,
9436 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9437 )
9438 .await;
9439}
9440
9441/// Handle audit result: log findings and emit trust events.
9442async fn handle_subtree_audit_result(
9443 result: &AuditTickResult,
9444 p2p_node: &Arc<P2PNode>,
9445 sync_state: &Arc<RwLock<NeighborSyncState>>,
9446 recent_provers: &Arc<RwLock<RecentProvers>>,
9447 config: &ReplicationConfig,
9448) {
9449 match result {
9450 AuditTickResult::Passed {
9451 challenged_peer,
9452 keys_checked,
9453 } => {
9454 protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9455 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9456 // Peer responded normally — clear the active bootstrap claim while
9457 // retaining history so a later claim is treated as repeated abuse.
9458 {
9459 let mut state = sync_state.write().await;
9460 state.clear_active_bootstrap_claim(challenged_peer);
9461 }
9462 p2p_node
9463 .report_trust_event(
9464 challenged_peer,
9465 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9466 )
9467 .await;
9468 }
9469 AuditTickResult::Failed {
9470 evidence,
9471 no_response_class,
9472 } => {
9473 if let FailureEvidence::AuditFailure {
9474 challenged_peer,
9475 confirmed_failed_keys,
9476 summary,
9477 reason,
9478 ..
9479 } = evidence
9480 {
9481 protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9482 // Rich diagnostics (from main's audit-failure logging) + the
9483 // first-failed-key correlation handle.
9484 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9485 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9486 error!(
9487 "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}",
9488 audit_failure_class,
9489 confirmed_failed_keys.len(),
9490 summary.challenged_keys,
9491 summary.absent_keys,
9492 summary.digest_mismatch_keys,
9493 );
9494 // Route the side effects through the subtree-only failure path.
9495 // Responsible-chunk `AuditChallenge` handling intentionally uses
9496 // its own old immediate-penalty handler below.
9497 handle_subtree_failed_audit(
9498 challenged_peer,
9499 confirmed_failed_keys.len(),
9500 reason,
9501 p2p_node,
9502 sync_state,
9503 recent_provers,
9504 )
9505 .await;
9506 }
9507 }
9508 AuditTickResult::BootstrapClaim { peer } => {
9509 // Gap 6: BootstrapClaimAbuse grace period in audit path.
9510 // Separate state mutation from network I/O to avoid holding the
9511 // write lock across report_trust_event.
9512 let should_report = {
9513 let now = Instant::now();
9514 let mut state = sync_state.write().await;
9515 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9516 {
9517 BootstrapClaimObservation::WithinGrace { .. } => {
9518 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9519 false
9520 }
9521 BootstrapClaimObservation::PastGrace { first_seen } => {
9522 warn!(
9523 "Audit: peer {peer} claiming bootstrap past grace period \
9524 ({:?} > {:?}), reporting abuse",
9525 now.duration_since(first_seen),
9526 config.bootstrap_claim_grace_period,
9527 );
9528 true
9529 }
9530 BootstrapClaimObservation::Repeated { first_seen } => {
9531 warn!(
9532 "Audit: peer {peer} repeated bootstrap claim after previously \
9533 stopping; first claim was {:?} ago, reporting abuse",
9534 now.duration_since(first_seen),
9535 );
9536 true
9537 }
9538 }
9539 };
9540 if should_report {
9541 p2p_node
9542 .report_trust_event(
9543 peer,
9544 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9545 )
9546 .await;
9547 }
9548 }
9549 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9550 }
9551}
9552
9553/// Whether a confirmed audit failure with this reason clears the peer's active
9554/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9555/// bootstrapping); every confirmed storage-integrity reason does.
9556///
9557/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9558/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9559/// still reports the normal audit trust penalty.
9560fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9561 !matches!(reason, AuditFailureReason::Timeout)
9562}
9563
9564/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9565/// events and manage bootstrap-claim state.
9566///
9567/// This is intentionally separate from the subtree audit result handler. A
9568/// responsible-chunk `AuditChallenge` `Failed` result reports
9569/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9570/// restoring the pre-ADR-0002 behaviour.
9571#[allow(clippy::too_many_lines)]
9572async fn handle_audit_result(
9573 result: &AuditTickResult,
9574 p2p_node: &Arc<P2PNode>,
9575 sync_state: &Arc<RwLock<NeighborSyncState>>,
9576 config: &ReplicationConfig,
9577) {
9578 match result {
9579 AuditTickResult::Passed {
9580 challenged_peer,
9581 keys_checked,
9582 } => {
9583 protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9584 debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9585 {
9586 let mut state = sync_state.write().await;
9587 state.clear_active_bootstrap_claim(challenged_peer);
9588 }
9589 p2p_node
9590 .report_trust_event(
9591 challenged_peer,
9592 TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9593 )
9594 .await;
9595 }
9596 AuditTickResult::Failed {
9597 evidence,
9598 no_response_class,
9599 } => {
9600 if let FailureEvidence::AuditFailure {
9601 challenged_peer,
9602 confirmed_failed_keys,
9603 summary,
9604 reason,
9605 ..
9606 } = evidence
9607 {
9608 protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9609 let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9610 let audit_failure_class = no_response_class.unwrap_or("confirmed");
9611 error!(
9612 "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}",
9613 audit_failure_class,
9614 confirmed_failed_keys.len(),
9615 summary.challenged_keys,
9616 summary.absent_keys,
9617 summary.digest_mismatch_keys,
9618 );
9619 if audit_failure_clears_bootstrap_claim(reason) {
9620 let mut state = sync_state.write().await;
9621 state.clear_active_bootstrap_claim(challenged_peer);
9622 } else {
9623 debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9624 }
9625 p2p_node
9626 .report_trust_event(
9627 challenged_peer,
9628 TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9629 )
9630 .await;
9631 }
9632 }
9633 AuditTickResult::BootstrapClaim { peer } => {
9634 let should_report = {
9635 let now = Instant::now();
9636 let mut state = sync_state.write().await;
9637 match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9638 {
9639 BootstrapClaimObservation::WithinGrace { .. } => {
9640 debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9641 false
9642 }
9643 BootstrapClaimObservation::PastGrace { first_seen } => {
9644 warn!(
9645 "Audit: peer {peer} claiming bootstrap past grace period \
9646 ({:?} > {:?}), reporting abuse",
9647 now.duration_since(first_seen),
9648 config.bootstrap_claim_grace_period,
9649 );
9650 true
9651 }
9652 BootstrapClaimObservation::Repeated { first_seen } => {
9653 warn!(
9654 "Audit: peer {peer} repeated bootstrap claim after previously \
9655 stopping; first claim was {:?} ago, reporting abuse",
9656 now.duration_since(first_seen),
9657 );
9658 true
9659 }
9660 }
9661 };
9662 if should_report {
9663 p2p_node
9664 .report_trust_event(
9665 peer,
9666 TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9667 )
9668 .await;
9669 }
9670 }
9671 AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9672 }
9673}
9674
9675/// Whether a confirmed audit failure with this reason should revoke the
9676/// peer's `recent_provers` holder credit immediately (v12 §6).
9677///
9678/// `true` for any reason where the peer actually answered (or admitted
9679/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9680/// bytes for committed key"), `MalformedResponse` — these prove the
9681/// peer no longer holds what it committed to, so it must not keep
9682/// holder credit for the proof TTL. `false` for `Timeout`: a single
9683/// dropped packet must not strip an honest peer; the 40-min TTL is the
9684/// deliberate liveness cushion there.
9685fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9686 !matches!(reason, AuditFailureReason::Timeout)
9687}
9688
9689/// Apply the holder-credit revocation decision for a confirmed audit
9690/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9691/// testable without a live `P2PNode`: the production `Failed` arm of
9692/// `handle_subtree_audit_result` calls exactly this.
9693fn apply_audit_failure_credit_revocation(
9694 provers: &mut RecentProvers,
9695 challenged_peer: &PeerId,
9696 reason: &AuditFailureReason,
9697) {
9698 if audit_failure_revokes_holder_credit(reason) {
9699 provers.forget_peer(challenged_peer);
9700 }
9701}
9702
9703// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9704
9705// ---------------------------------------------------------------------------
9706// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9707// ---------------------------------------------------------------------------
9708
9709/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9710/// message handler passes one value instead of a long argument list; all
9711/// fields are cheap `Arc` clones.
9712#[derive(Clone)]
9713struct GossipAuditTrigger {
9714 p2p_node: Arc<P2PNode>,
9715 config: Arc<ReplicationConfig>,
9716 recent_provers: Arc<RwLock<RecentProvers>>,
9717 sync_state: Arc<RwLock<NeighborSyncState>>,
9718 /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9719 /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9720 /// only when a real audit is about to be sent — never by a losing lottery
9721 /// ticket — so gossip traffic alone can never suppress a paid first audit.
9722 cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9723 detached_task_tracker: TaskTracker,
9724 /// Gossip-private lottery attempt window: stamped on every roll (win or
9725 /// lose) so a gossip flood cannot re-roll the lottery within the window.
9726 /// The first-audit scheduler never reads this map.
9727 lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9728}
9729
9730/// What a gossip ingest yields for the audit trigger: the commitment hash to
9731/// pin and the `key_count` needed to size the response deadline from the actual
9732/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9733/// or not) so a stable-keyset node stays auditable — not just on its first
9734/// commitment.
9735#[derive(Debug, Clone, Copy)]
9736struct AuditTarget {
9737 pin_hash: [u8; 32],
9738 key_count: u32,
9739}
9740
9741/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9742/// verifier's cross-check so it can receive a **deterministic first audit**.
9743///
9744/// Sent from the verifier to the replication engine's first-audit drainer. The
9745/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9746/// audits of the same peer revert to the gossip lottery), orders most-recently-
9747/// monetized first, and runs the same `run_subtree_audit` under the same
9748/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9749#[derive(Debug, Clone, Copy)]
9750pub struct MonetizedPinEvent {
9751 /// The peer whose commitment backed the payment.
9752 pub peer: PeerId,
9753 /// The pinned commitment hash.
9754 pub pin: [u8; 32],
9755 /// The committed key count (sizes the audit deadline).
9756 pub key_count: u32,
9757 /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9758 /// pin whose quote is older than the answerability window (ADR-0004 A1
9759 /// guardrail A): with grace removed, challenging an aged-out pin would
9760 /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9761 pub quote_ts: SystemTime,
9762}
9763
9764/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9765/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9766/// stamps `now`), `false` if it was audited within
9767/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9768/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9769/// without a live node: a burst of gossips from one peer yields at most one
9770/// `true` per cooldown window.
9771fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9772 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9773 let known = match map.get(peer) {
9774 Some(&last) => {
9775 if now.saturating_duration_since(last) < cooldown {
9776 return false;
9777 }
9778 true
9779 }
9780 None => false,
9781 };
9782 // Bound the map under churn like its siblings (drop the oldest stamp) before
9783 // admitting a brand-new peer.
9784 if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9785 if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9786 map.remove(&victim);
9787 }
9788 }
9789 map.insert(*peer, now);
9790 true
9791}
9792
9793/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9794/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9795/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9796/// already covered; the authoritative check-and-stamp still runs at promotion,
9797/// so this is only an optimization and never the security boundary.
9798fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9799 let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9800 map.get(peer)
9801 .is_none_or(|&last| now.saturating_duration_since(last) >= cooldown)
9802}
9803
9804/// The gossip-audit launch decision in ONE place so the ordering is shared
9805/// between production and its test (ADR-0002 "occasional surprise exams").
9806///
9807/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9808/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9809/// sampled first, a gossip flood would re-roll it on every message until one
9810/// won, multiplying audits, so each peer gets at most one lottery roll per
9811/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9812/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9813/// also consults — only after a WIN, i.e. only when a real audit is about to be
9814/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9815/// wire, so it must not defer a paid first audit (repeatable losses could
9816/// otherwise hold a monetized pin past its answerability window). Production
9817/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9818/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9819/// here fails the test.
9820fn audit_launch_decision(
9821 attempts: &mut HashMap<PeerId, Instant>,
9822 launched: &mut HashMap<PeerId, Instant>,
9823 peer: &PeerId,
9824 now: Instant,
9825 lottery_wins: bool,
9826) -> bool {
9827 // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9828 // window even on a loss; private to the gossip path).
9829 if !cooldown_allows_audit(attempts, peer, now) {
9830 return false;
9831 }
9832 // Gate 2: the probability lottery. A loss stops here and stamps nothing
9833 // shared.
9834 if !lottery_wins {
9835 return false;
9836 }
9837 // Gate 3: the shared actual-audit cooldown (a recent real audit from
9838 // either path still suppresses this launch), stamped only on launch.
9839 cooldown_allows_audit(launched, peer, now)
9840}
9841
9842/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9843/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9844/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9845/// handling is never blocked on a network round-trip.
9846async fn maybe_trigger_gossip_audit(
9847 trigger: &GossipAuditTrigger,
9848 peer: &PeerId,
9849 target: AuditTarget,
9850) {
9851 // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9852 // lives in the pure `audit_launch_decision` so the ordering is shared with
9853 // its test. Sample the lottery here, then let the helper apply the gates.
9854 let now = Instant::now();
9855 let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9856 {
9857 // Lock order: attempts before the shared cooldown; this is the only
9858 // place both are held together.
9859 let mut attempts = trigger.lottery_attempts.write().await;
9860 let mut launched = trigger.cooldown.write().await;
9861 if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9862 return;
9863 }
9864 }
9865
9866 let detached_task_tracker = trigger.detached_task_tracker.clone();
9867 let trigger = trigger.clone();
9868 let peer = *peer;
9869 detached_task_tracker.spawn(async move {
9870 let credit = storage_commitment_audit::AuditCredit {
9871 recent_provers: &trigger.recent_provers,
9872 };
9873 let result = storage_commitment_audit::run_subtree_audit_with_origin(
9874 &trigger.p2p_node,
9875 &trigger.config,
9876 &peer,
9877 target.pin_hash,
9878 target.key_count,
9879 Some(&credit),
9880 storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9881 )
9882 .await;
9883 handle_subtree_audit_result(
9884 &result,
9885 &trigger.p2p_node,
9886 &trigger.sync_state,
9887 &trigger.recent_provers,
9888 &trigger.config,
9889 )
9890 .await;
9891 });
9892}
9893
9894/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9895///
9896/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9897/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9898/// of its last attempt. Holds one write lock across the decision so two
9899/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9900/// caller's expensive verify so a slow/failed verify still rate-limits the next
9901/// message. Bounds the map under a flood of distinct peer ids.
9902async fn sig_verify_rate_limit_ok(
9903 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9904 source: &PeerId,
9905 now: Instant,
9906) -> bool {
9907 let mut attempts = sig_verify_attempts.write().await;
9908 if let Some(&last) = attempts.get(source) {
9909 if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9910 return false;
9911 }
9912 }
9913 if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9914 if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9915 attempts.remove(&victim);
9916 }
9917 }
9918 attempts.insert(*source, now);
9919 true
9920}
9921
9922/// Verify + store an inbound commitment from a gossip peer.
9923///
9924/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9925/// the bootstrap-sync loop. Drops the commitment unless all five gates
9926/// pass:
9927/// 1. `source` is in our DHT routing table (sybil/churn cap).
9928/// 2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9929/// binding to the authenticated transport peer).
9930/// 3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9931/// (the embedded pubkey actually belongs to the claimed identity —
9932/// saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9933/// 4. `verify_commitment_signature(commitment)` succeeds against the
9934/// embedded public key. The signed payload binds the pubkey, so an
9935/// adversary cannot swap the key while keeping the body.
9936/// 5. The cache has room or this is an update for an existing entry
9937/// (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9938///
9939/// On all-pass, the commitment is stored as the auditor's per-peer
9940/// "last known commitment" for use as `expected_commitment_hash` in
9941/// future audits.
9942///
9943/// Failures (no commitment / mismatched peer id / bad signature) are
9944/// silent drops — gossip is best-effort and a malformed commitment from
9945/// one peer should not affect anything else.
9946///
9947/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9948/// or not its root changed), so the caller can run a probabilistic,
9949/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9950/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9951/// being auditable, so it cannot pass one audit and then delete data while
9952/// re-gossiping the same root forever. The cooldown + probability bound the
9953/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9954/// gate) or there is nothing to pin.
9955///
9956/// Handle a capable peer gossiping `None` (a commitment downgrade).
9957///
9958/// A capable peer that previously gossiped a commitment but now gossips `None`
9959/// is trying to drop off the audit path. Within the answerability window we keep
9960/// the cached commitment pinned AND return it as an audit target so this gossip
9961/// still schedules a subtree audit against the peer's last known commitment — if
9962/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9963/// the trigger MUST fire here or the downgrade is never re-challenged).
9964///
9965/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9966/// honours for its own retired commitment: once that elapses since we last
9967/// received the peer's commitment, an honest peer has legitimately retired that
9968/// root (its responder side `retire_current`s and lets it age out) and can no
9969/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9970/// failure, so we then forget the cached commitment (keeping the sticky
9971/// `commitment_capable` bit) and stop pinning it.
9972async fn handle_commitment_downgrade(
9973 source: &PeerId,
9974 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9975) -> Option<AuditTarget> {
9976 let now = Instant::now();
9977 let cached = {
9978 let map = last_commitment_by_peer.read().await;
9979 map.get(source).and_then(|rec| {
9980 if !rec.commitment_capable {
9981 return None;
9982 }
9983 let last = rec.last_commitment()?;
9984 let pin = rec.commitment_hash()?;
9985 let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9986 Some((pin, last.key_count, fresh))
9987 })
9988 };
9989 match cached {
9990 Some((pin, key_count, true)) => {
9991 warn!(
9992 "ingest_peer_commitment: commitment-capable peer {source} sent None \
9993 (downgrade attempt); auditing against its last cached commitment"
9994 );
9995 Some(AuditTarget {
9996 pin_hash: pin,
9997 key_count,
9998 })
9999 }
10000 Some((_, _, false)) => {
10001 // Cached commitment has aged past the answerability window — forget
10002 // it so we stop pinning a root the peer is no longer obliged to
10003 // answer. Keep `commitment_capable` (sticky). Re-check freshness
10004 // UNDER the write lock (compare-and-clear): a concurrent valid gossip
10005 // from this peer may have refreshed `received_at` in the gap between
10006 // our read and write locks; if so, leave its fresh commitment intact.
10007 if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
10008 let still_stale =
10009 now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
10010 if still_stale {
10011 rec.clear_commitment();
10012 debug!(
10013 "ingest_peer_commitment: capable peer {source} sent None and its cached \
10014 commitment aged past the answerability TTL; forgetting it"
10015 );
10016 }
10017 }
10018 None
10019 }
10020 None => None,
10021 }
10022}
10023
10024async fn ingest_peer_commitment(
10025 source: &PeerId,
10026 commitment: Option<&StorageCommitment>,
10027 p2p_node: &Arc<P2PNode>,
10028 last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
10029 ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
10030 sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
10031) -> Option<AuditTarget> {
10032 let Some(c) = commitment else {
10033 return handle_commitment_downgrade(source, last_commitment_by_peer).await;
10034 };
10035 // RT-membership gate: only accept commitments from peers in our
10036 // routing table. Off-RT senders (sybils, drive-by relays) cannot
10037 // populate the cache, which closes the hole where a flood of
10038 // off-RT identities could fill the cap and evict honest
10039 // peers. The neighbor-sync request handler applies the same gate
10040 // before admitting inbound replication hints (see neighbor_sync.rs
10041 // `sender_in_rt`); we mirror that policy here for the commitment
10042 // piggyback.
10043 if !p2p_node.dht_manager().is_in_routing_table(source).await {
10044 debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
10045 return None;
10046 }
10047 // Peer-id binding: the commitment's claimed sender must match the
10048 // authenticated transport peer (`source`). Defeats relay/replay
10049 // and also pins which embedded public key we are about to verify
10050 // against — the verify itself trusts the embedded key, so the
10051 // peer-id binding is the link to a real identity.
10052 if &c.sender_peer_id != source.as_bytes() {
10053 warn!(
10054 "ingest_peer_commitment: sender_peer_id mismatch from {source} \
10055 (dropped, possible relay attempt)"
10056 );
10057 return None;
10058 }
10059 // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
10060 // BLAKE3(pubkey_bytes). Without this check, a responder could sign
10061 // with a throwaway key they own and lie about which identity it
10062 // belongs to (the embedded-key signature would verify trivially).
10063 let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
10064 if derived_peer_id != c.sender_peer_id {
10065 warn!(
10066 "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
10067 {source} (dropped, throwaway-key attack)"
10068 );
10069 return None;
10070 }
10071 // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
10072 // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
10073 // sybil/RT-membership-bypassing peer that flooded valid-looking
10074 // gossip would otherwise burn CPU on every message. The rate
10075 // limit is checked AFTER cheap structural gates (RT, peer-id
10076 // binding, pubkey-binding) and BEFORE the expensive sig verify.
10077 //
10078 // Tracked in `sig_verify_attempts` (separate from
10079 // last_commitment_by_peer) so EVERY attempt — successful or not —
10080 // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
10081 // would skip the cap for peers we've never successfully verified,
10082 // letting a flood of invalid-but-structurally-plausible gossips
10083 // burn CPU.
10084 let now = Instant::now();
10085 if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
10086 debug!(
10087 "ingest_peer_commitment: rate-limited sig verify from {source} \
10088 (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
10089 );
10090 return None;
10091 }
10092 // Signature verify, using the public key embedded in the commitment
10093 // itself. The pubkey is bound by the signature payload (see
10094 // commitment_signed_payload) so an adversary cannot keep the body
10095 // and swap the key to one they hold the secret for.
10096 if !crate::replication::commitment::verify_commitment_signature(c) {
10097 warn!(
10098 "ingest_peer_commitment: signature did not verify under embedded key for {source} \
10099 (dropped, forged commitment)"
10100 );
10101 return None;
10102 }
10103 // The new commitment's hash, used to store and to pin for the audit target.
10104 let new_hash = commitment_hash(c);
10105 let mut map = last_commitment_by_peer.write().await;
10106 // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
10107 // evict an arbitrary existing entry to make room. Updates for peers
10108 // already in the map are always accepted (they replace, not grow).
10109 if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
10110 // Drop one arbitrary entry. HashMap iter order is random which
10111 // is fine — over time PeerRemoved cleanup keeps the working set
10112 // anchored on the real RT membership; this cap only fires under
10113 // active flooding attempts.
10114 if let Some(victim) = map.keys().next().copied() {
10115 map.remove(&victim);
10116 warn!(
10117 "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
10118 evicted {victim} to admit {source}"
10119 );
10120 }
10121 }
10122 // Preserve sticky commitment_capable across updates — once true,
10123 // always true. New entries start with capable = true (we just
10124 // verified a valid commitment from this peer).
10125 map.entry(*source)
10126 .and_modify(|r| {
10127 // set_commitment refreshes the cached hash (§13) alongside the
10128 // commitment + received_at so they never drift.
10129 r.set_commitment(c.clone(), now);
10130 r.last_sig_verify_at = now;
10131 r.commitment_capable = true; // sticky-redundant but explicit
10132 })
10133 .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
10134 drop(map);
10135 // Record the sticky "ever v12-capable" bit in a set independent of
10136 // `last_commitment_by_peer` (whose entries can be evicted by
10137 // `PeerRemoved` and the sybil cap). This is what the §3 audit
10138 // shield and the §6 holder-eligibility closure consult to decide
10139 // whether the peer is expected to speak v12.
10140 //
10141 // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
10142 // identity-rotation attacks: once full, new entries are refused.
10143 // Refusal degrades over-cap peers to the behaviour before this set
10144 // existed (treated as legacy on rejoin), which is not a security
10145 // regression and preserves the historic set stable.
10146 {
10147 let mut set = ever_capable_peers.write().await;
10148 if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
10149 set.insert(*source);
10150 } else {
10151 warn!(
10152 "ingest_peer_commitment: ever_capable_peers at cap \
10153 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
10154 );
10155 }
10156 }
10157 // Return an audit target for EVERY valid stored commitment (changed or
10158 // not), so the caller's cooldown+probability-gated trigger keeps a
10159 // stable-keyset peer auditable over time (ADR-0002). Only a serialization
10160 // failure (new_hash == None, unreachable for a real commitment) yields None.
10161 new_hash.map(|pin_hash| AuditTarget {
10162 pin_hash,
10163 key_count: c.key_count,
10164 })
10165}
10166
10167// ---------------------------------------------------------------------------
10168// Storage-bound audit (v12) — responder commitment rotation
10169// ---------------------------------------------------------------------------
10170
10171/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
10172/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
10173/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
10174async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
10175 let bytes = match tokio::fs::read(path).await {
10176 Ok(b) => b,
10177 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
10178 debug!(
10179 "Commitment retention: no snapshot at {} (fresh start)",
10180 path.display()
10181 );
10182 return;
10183 }
10184 Err(e) => {
10185 warn!(
10186 "Commitment retention: failed to read {}: {e}",
10187 path.display()
10188 );
10189 return;
10190 }
10191 };
10192 if let Some(mut persisted) = PersistedRetention::from_bytes(&bytes) {
10193 let sidecar = pointer_leaves_path(path);
10194 match tokio::fs::read(&sidecar).await {
10195 Ok(leaves) => {
10196 if !persisted.attach_pointer_leaves(&leaves) {
10197 warn!(
10198 "Commitment retention: corrupt pointer leaves at {}; \
10199 commitments holding pointers will not be restored",
10200 sidecar.display()
10201 );
10202 }
10203 }
10204 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
10205 Err(e) => warn!(
10206 "Commitment retention: failed to read {}: {e}",
10207 sidecar.display()
10208 ),
10209 }
10210 state.restore(&persisted);
10211 info!(
10212 "Commitment retention: reloaded {} slot(s) from {}",
10213 state.retained_slot_count(),
10214 path.display()
10215 );
10216 } else {
10217 warn!(
10218 "Commitment retention: corrupt snapshot at {}; starting with empty retention",
10219 path.display()
10220 );
10221 }
10222}
10223
10224/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
10225/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
10226/// needless disk writes on idle nodes. On success updates `last` to the bytes
10227/// written; on a serialization/write error the existing on-disk snapshot is left
10228/// intact (never truncated).
10229///
10230/// The pointer leaves go to a sidecar written first (ADR-0016), so the
10231/// retention file never names a commitment whose pointer leaves are not yet
10232/// on disk. A crash between the two leaves a sidecar ahead of the file, which
10233/// is harmless: it is keyed by commitment hash.
10234async fn persist_retention_if_changed(
10235 state: &ResponderCommitmentState,
10236 path: &Path,
10237 last: &mut Option<Vec<u8>>,
10238) {
10239 let snapshot = state.snapshot();
10240 let (Some(bytes), Some(leaves)) = (snapshot.to_bytes(), snapshot.pointer_leaves_bytes()) else {
10241 warn!("Commitment retention: serialization failed; keeping previous snapshot");
10242 return;
10243 };
10244 let mut combined = leaves.clone();
10245 combined.extend_from_slice(&bytes);
10246 if last.as_deref() == Some(combined.as_slice()) {
10247 return;
10248 }
10249 if write_file_atomic(&pointer_leaves_path(path), leaves).await
10250 && write_file_atomic(path, bytes).await
10251 {
10252 *last = Some(combined);
10253 }
10254}
10255
10256/// Where the pointer leaves of the retention at `path` are kept.
10257fn pointer_leaves_path(path: &Path) -> PathBuf {
10258 path.with_file_name("commitment_retention_pointers.bin")
10259}
10260
10261/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
10262/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
10263/// success. Each path has a single writer, so a fixed temp name is safe.
10264async fn write_file_atomic(path: &Path, bytes: Vec<u8>) -> bool {
10265 let path = path.to_path_buf();
10266 let target = path.clone();
10267 let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
10268 let tmp = path.with_extension("tmp");
10269 // Sync through the handle that wrote, and close it before the rename:
10270 // Windows refuses to flush a read-only handle or to rename an open file.
10271 let mut file = std::fs::File::create(&tmp)?;
10272 file.write_all(&bytes)?;
10273 file.sync_all()?;
10274 drop(file);
10275 std::fs::rename(&tmp, &path)?;
10276 // Fsync the directory so the rename (the durable-commit point) is not
10277 // lost on a crash right after it. An empty parent (relative filename)
10278 // means the current directory. Windows can't open a directory as a file.
10279 if cfg!(unix) {
10280 let dir = path
10281 .parent()
10282 .filter(|p| !p.as_os_str().is_empty())
10283 .unwrap_or_else(|| Path::new("."));
10284 std::fs::File::open(dir)?.sync_all()?;
10285 }
10286 Ok(())
10287 })
10288 .await;
10289 match res {
10290 Ok(Ok(())) => true,
10291 Ok(Err(e)) => {
10292 warn!("Failed to persist {target:?}: {e}");
10293 false
10294 }
10295 Err(e) => {
10296 warn!("Persist task for {target:?} failed to join: {e}");
10297 false
10298 }
10299 }
10300}
10301
10302/// Read the current key set, build + sign a fresh
10303/// `StorageCommitment`, and rotate it into `state` as the new `current`.
10304/// The prior `current` is demoted to `previous`; the prior `previous` is
10305/// dropped (per `ResponderCommitmentState::rotate`).
10306///
10307/// For content-addressed chunks (Autonomi's chunk store), `address ==
10308/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
10309/// re-read each chunk's bytes to compute the leaf hash.
10310///
10311/// The pointers this node is responsible for are committed alongside, each as
10312/// `(address, pointer_leaf_hash(address))` (ADR-0016), so they are audited and
10313/// priced exactly as chunks are.
10314///
10315/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
10316/// rotate. The auditor side handles "no commitment for this peer" by
10317/// falling back to the legacy plain-digest audit path.
10318async fn rebuild_and_rotate_commitment(
10319 storage: &Arc<ChunkStore>,
10320 pointers: Option<&PointerStore>,
10321 identity: &Arc<NodeIdentity>,
10322 state: &Arc<ResponderCommitmentState>,
10323 p2p: &Arc<P2PNode>,
10324 config: &Arc<ReplicationConfig>,
10325) -> Result<()> {
10326 // `all_keys()` is what the store can answer for: it already drops a file marked suspect or
10327 // known-wrong, so a name that cannot be read is not offered here. It is NOT the commitment
10328 // set — that is narrowed to the keys this node is still responsible for, by the filter a
10329 // few lines below, and not by this call. The comment that used to be here said "not
10330 // `all_keys()`" immediately above the call to it, which is the sort of thing that sends
10331 // somebody to change the wrong layer.
10332 let stored_keys = storage
10333 .all_keys()
10334 .await
10335 .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
10336
10337 // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
10338 // everything currently on disk ("hold"). This is the half of the retention
10339 // contract that lets out-of-range chunks age out: a key that has left our
10340 // close group is excluded from the NEXT commitment, so once its last gossip
10341 // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
10342 // set, `ResponderCommitmentState::is_held` goes false,
10343 // and the pruner (which until then vetoes its deletion) reclaims it. Without
10344 // this filter the pruner's reprieve would keep re-committing stale keys
10345 // forever (the rebuild reads all_keys, so a retained-on-disk key would be
10346 // re-committed and re-gossiped every rotation — a permanent pin).
10347 let self_id = *p2p.peer_id();
10348 let mut keys = Vec::with_capacity(stored_keys.len());
10349 for k in stored_keys {
10350 if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
10351 keys.push(k);
10352 }
10353 }
10354 // The same rule for pointers: an out-of-range pointer leaves the next
10355 // commitment, and the pruner reclaims it once no retained slot holds it.
10356 let mut pointer_keys = Vec::new();
10357 for state in pointers.map(PointerStore::held_states).unwrap_or_default() {
10358 if admission::is_responsible(&self_id, &state.address, p2p, config.close_group_size).await {
10359 pointer_keys.push(state.address);
10360 }
10361 }
10362
10363 if keys.is_empty() && pointer_keys.is_empty() {
10364 // There used to be a second branch here that dropped every retained root outright
10365 // when the node looked empty. It is gone, and the reason is worth keeping.
10366 //
10367 // "Empty" was decided from key counts, and every version of that test was wrong in
10368 // the same direction: a node can hold bytes the counts do not show, because a file is
10369 // published before it is indexed. Each fix closed one window and left another.
10370 //
10371 // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10372 // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10373 // lane, so a node that still holds the bytes is penalised for holding them. Retiring
10374 // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10375 // instead of vanishing now. Both set `has_current = false`; they differ only in
10376 // whether the node goes on being answerable in the meantime. A genuinely empty node
10377 // cannot answer either way, so retiring costs it nothing it had.
10378 //
10379 // So there is one branch, and no emptiness question to get wrong.
10380 //
10381 // A peer may still be pinning a root we gossiped
10382 // moments ago and could demand its bytes in a round-2 challenge, which
10383 // we can still answer (the bytes are present). But we must STOP
10384 // advertising the stale commitment: retire it so `current()` returns
10385 // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10386 // The retired slot then ages out by its gossip-answerability TTL while
10387 // remaining answerable for in-flight pins until then. Once it ages out,
10388 // `is_held` flips false and the pruner reclaims the now-uncommitted,
10389 // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10390 // pointing at the stale root, which the gossip loop would keep
10391 // re-stamping — pinning its keys forever.)
10392 debug!(
10393 "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10394 (stays answerable until its gossip TTL lapses, bytes still on disk)"
10395 );
10396 state.retire_current();
10397 return Ok(());
10398 }
10399
10400 // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10401 // to more than the protocol limit; auditor would reject the
10402 // commitment otherwise).
10403 let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10404 let total = keys.len().saturating_add(pointer_keys.len());
10405 if total > cap {
10406 warn!(
10407 "Commitment rotation: key set ({total}) exceeds MAX_COMMITMENT_KEY_COUNT ({cap}); \
10408 truncating — investigate as this likely means a misconfiguration"
10409 );
10410 }
10411
10412 // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10413 // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10414 // full chunk re-read per rotation.
10415 //
10416 // Consequence to be precise about: because the leaf is `(key, key)`,
10417 // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10418 // commitment therefore binds "which keys I claim to hold"; it does NOT
10419 // by itself prove byte possession. Byte possession is enforced by the
10420 // round-2 slice audit: a Bao verified slice decoded against the chunk
10421 // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10422 // nonce, so a responder that holds the key list but dropped the bytes
10423 // cannot answer. This is sound ONLY while keys are content addresses;
10424 // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10425 // (`evaluate_subtree_structure`), so a non-content-addressed
10426 // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10427 // earn credit for `key`. If this module is ever reused for
10428 // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10429 // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10430 //
10431 // Pointers are that case, and are handled by being told apart rather than
10432 // hashed: a pointer leaf is `(address, pointer_leaf_hash(address))`, which
10433 // the verifier accepts only for a leaf of exactly a pointer's size, and
10434 // round 2 then demands the whole signed record in place of a Bao slice.
10435 // The root binds which pointers are held, never their current state, so an
10436 // update does not move it.
10437 //
10438 // A pointer address that is also a chunk key would need a BLAKE3 preimage;
10439 // the dedup only keeps such a collision from failing the whole build.
10440 let mut entries: Vec<_> = keys
10441 .into_iter()
10442 .map(|k| (k, k))
10443 .chain(
10444 pointer_keys
10445 .into_iter()
10446 .map(|address| (address, commitment::pointer_leaf_hash(&address))),
10447 )
10448 .collect();
10449 entries.sort_by_key(|(k, _)| *k);
10450 entries.dedup_by_key(|(k, _)| *k);
10451 entries.truncate(cap);
10452
10453 // No-op-rotation guard: compute just the Merkle root from `entries`
10454 // and compare against the currently-advertised commitment's root.
10455 // If they match, the key set is unchanged and a new rotation would
10456 // only swap a randomized ML-DSA signature for a fresh one — same
10457 // content, different commitment_hash. That invalidates every
10458 // outstanding `recent_provers` credit on this node across the
10459 // close group with no security benefit, breaking steady-state
10460 // quorum liveness on large nodes that can't re-audit every key
10461 // every rotation interval. Skip the rotation entirely when the
10462 // tree is unchanged.
10463 // Build the tree ONCE here (moving `entries`): it serves both the no-op
10464 // root check below and, if we proceed, the signed commitment via
10465 // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10466 // inside `BuiltCommitment::build`).
10467 let candidate_tree = commitment::MerkleTree::build(entries)
10468 .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10469 let candidate_root = candidate_tree.root();
10470 if let Some(current) = state.current() {
10471 if current.commitment().root == candidate_root {
10472 debug!(
10473 "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10474 hex::encode(candidate_root)
10475 );
10476 // Even though we skip re-signing (to avoid invalidating holder
10477 // credit), retention must still advance on the wall clock: a
10478 // previously-gossiped commitment that holds a now-out-of-range key
10479 // must be able to age out of the answerability window even when the
10480 // committed key set is frozen here for many rotations. Without this,
10481 // the no-op guard would pin a stale slot — and its key — forever.
10482 state.age_out();
10483 return Ok(());
10484 }
10485 }
10486
10487 let sk_bytes = identity.secret_key_bytes().to_vec();
10488 let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10489 .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10490 let pk_bytes = identity.public_key().as_bytes().to_vec();
10491 let peer_id_bytes = *p2p.peer_id().as_bytes();
10492
10493 let built = commitment_state::BuiltCommitment::build_from_tree(
10494 candidate_tree,
10495 &peer_id_bytes,
10496 &sk,
10497 &pk_bytes,
10498 )
10499 .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10500
10501 let hash = hex::encode(built.hash());
10502 let key_count = built.commitment().key_count;
10503 let pointer_count = built.tree().pointer_count();
10504 state.rotate(built);
10505 info!("Storage commitment rotated: hash={hash} key_count={key_count} pointers={pointer_count}");
10506 Ok(())
10507}
10508
10509#[cfg(test)]
10510#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10511mod tests {
10512
10513 /// The responder's answer says whether it lacks the chunk or failed to read it.
10514 ///
10515 /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10516 /// an I/O fault or a failed integrity check, reads as `Err`. Nothing turns the first
10517 /// into the second.
10518 #[tokio::test]
10519 async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10520 let dir = tempfile::tempdir().expect("temp dir");
10521 let storage = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
10522 root_dir: dir.path().to_path_buf(),
10523 verify_on_read: true,
10524 disk_reserve: 0,
10525 })
10526 .await
10527 .expect("open store");
10528
10529 let absent = [9u8; 32];
10530 assert!(
10531 matches!(storage.get(&absent).await, Ok(None)),
10532 "a chunk this node does not hold must read as a plain miss, not a fault"
10533 );
10534
10535 // And the answer each read produces: a miss is `NotFound`, a failed read is `Error`.
10536 // Both are charged to a verified source that gives them, but they say different
10537 // things to whoever reads the logs.
10538 assert!(matches!(
10539 fetch_response_for(absent, Ok(None)),
10540 protocol::FetchResponse::NotFound { .. }
10541 ));
10542 assert!(matches!(
10543 fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10544 protocol::FetchResponse::Success { .. }
10545 ));
10546 assert!(matches!(
10547 fetch_response_for(
10548 absent,
10549 Err(crate::error::Error::Storage("read failed".into()))
10550 ),
10551 protocol::FetchResponse::Error { .. }
10552 ));
10553 }
10554 use super::*;
10555 use super::{
10556 apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10557 audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10558 config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10559 first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10560 quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10561 FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10562 FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10563 FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10564 };
10565 use crate::payment::VerificationContext;
10566 use crate::replication::audit::AuditTickResult;
10567 use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10568 use crate::replication::recent_provers::RecentProvers;
10569 use crate::replication::types::{AuditFailureReason, FailureEvidence};
10570 use lru::LruCache;
10571 use saorsa_core::identity::PeerId;
10572 use std::collections::HashMap;
10573 use std::num::NonZeroUsize;
10574 use std::sync::atomic::Ordering;
10575 use std::sync::Arc;
10576 use std::time::Duration;
10577 use std::time::Instant;
10578 use std::time::SystemTime;
10579
10580 #[test]
10581 fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10582 for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10583 assert_eq!(match_replication_protocol(id), Some((id, false)));
10584 assert_eq!(
10585 match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10586 Some((id, true))
10587 );
10588 }
10589 assert_eq!(
10590 match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10591 None
10592 );
10593 assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10594 assert_eq!(match_replication_protocol(RR_PREFIX), None);
10595 }
10596
10597 #[test]
10598 fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10599 use crate::replication::protocol::{
10600 AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10601 SubtreeSliceChallenge,
10602 };
10603
10604 let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10605 challenge_id: 1,
10606 nonce: [0u8; 32],
10607 challenged_peer_id: [0u8; 32],
10608 expected_commitment_hash: [0u8; 32],
10609 openings: vec![],
10610 });
10611 let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10612 challenge_id: 1,
10613 nonce: [0u8; 32],
10614 challenged_peer_id: [0u8; 32],
10615 keys: vec![[0u8; 32]],
10616 });
10617 let digest_response =
10618 ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10619 let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10620 key: [0u8; 32],
10621 data: vec![],
10622 proof_of_payment: vec![],
10623 });
10624
10625 assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10626 assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10627
10628 for body in [&digest_challenge, &digest_response, &core] {
10629 assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10630 assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10631 }
10632
10633 for body in [&subtree, &digest_challenge, &digest_response, &core] {
10634 assert!(body_matches_protocol(body, response_protocol_for(body)));
10635 }
10636 }
10637
10638 fn test_peer(b: u8) -> PeerId {
10639 let mut bytes = [0u8; 32];
10640 bytes[0] = b;
10641 PeerId::from_bytes(bytes)
10642 }
10643
10644 /// A structurally valid offer for `data`: real content address, a proof of
10645 /// the minimum accepted size, distinguished by `proof_marker` so a test can
10646 /// tell whose proof came back out of the queue.
10647 fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10648 protocol::FreshReplicationOffer {
10649 key: crate::client::compute_address(&data),
10650 data,
10651 proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10652 }
10653 }
10654
10655 fn admit_test_offer(
10656 in_flight: &FreshOfferInFlight,
10657 offer: protocol::FreshReplicationOffer,
10658 source: PeerId,
10659 ) -> FreshOfferAdmission {
10660 FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10661 }
10662
10663 #[test]
10664 fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10665 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10666 let data = vec![0x11u8; 64];
10667
10668 let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10669 let FreshOfferAdmission::Opened(entry) = opened else {
10670 panic!("first offer for a key should open the entry")
10671 };
10672
10673 // A second sender contributes its proof instead of being turned away:
10674 // its bytes are provably the same, so only the proof is worth keeping.
10675 assert!(
10676 matches!(
10677 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10678 FreshOfferAdmission::Joined
10679 ),
10680 "a duplicate from a new source should queue its proof"
10681 );
10682 // The same peer twice is not extra evidence, just extra work.
10683 assert!(
10684 matches!(
10685 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10686 FreshOfferAdmission::DuplicateSource
10687 ),
10688 "one source should hold at most one queued proof per key"
10689 );
10690
10691 // An entry that outlived its handler would bar the key forever.
10692 drop(entry);
10693 assert!(
10694 matches!(
10695 admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10696 FreshOfferAdmission::Opened(_)
10697 ),
10698 "a released key should be openable again"
10699 );
10700 }
10701
10702 #[test]
10703 fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10704 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10705
10706 // A node only receives offers for keys close to its own ID, so accepted
10707 // keys share a long prefix. Any prefix-derived shard index would have
10708 // funnelled these two onto one lock and serialized them.
10709 let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10710 assert!(
10711 matches!(
10712 admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10713 FreshOfferAdmission::Opened(_)
10714 ),
10715 "distinct keys should never block each other"
10716 );
10717 }
10718
10719 /// The regression that motivated queueing proofs at all.
10720 ///
10721 /// A sender whose proof does not verify must cost the network its own
10722 /// attempt and nothing more. Refusing every later offer outright made the
10723 /// first arrival the only arrival, so one bad proof lost the record — and
10724 /// the delayed possession check then charged that absence to this node.
10725 #[test]
10726 fn a_failing_proof_hands_the_key_to_the_next_sender() {
10727 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10728 let data = vec![0x5Au8; 128];
10729 let forger = test_peer(0xF0);
10730 let genuine = test_peer(0x0F);
10731
10732 let FreshOfferAdmission::Opened(mut entry) =
10733 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10734 else {
10735 panic!("the first offer should open the entry");
10736 };
10737 assert!(
10738 matches!(
10739 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10740 FreshOfferAdmission::Joined
10741 ),
10742 "the genuine sender must not be turned away by the forger"
10743 );
10744
10745 let first = entry
10746 .next_attempt()
10747 .expect("the opener's proof comes first");
10748 assert_eq!(first.source, forger);
10749
10750 // Treat the forger's proof as failed: the next one is still reachable,
10751 // and it is tried against the bytes already held rather than a refetch.
10752 let second = entry
10753 .next_attempt()
10754 .expect("a failed proof must not consume the key");
10755 assert_eq!(second.source, genuine);
10756 assert_eq!(
10757 second.proof_of_payment,
10758 vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10759 );
10760 assert_eq!(
10761 entry.data(),
10762 data.as_slice(),
10763 "every proof is tried against the one copy of the bytes"
10764 );
10765
10766 // Draining the queue releases the key rather than stranding it.
10767 assert!(entry.next_attempt().is_none());
10768 assert!(
10769 matches!(
10770 admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10771 FreshOfferAdmission::Opened(_)
10772 ),
10773 "an exhausted entry should release its key"
10774 );
10775 }
10776
10777 /// The cap has to be a lifetime budget, not a queue depth.
10778 ///
10779 /// The handler pops a proof before verifying it, so gating admission on the
10780 /// *instantaneous* queue length lets a fresh source refill the slot that pop
10781 /// just freed. Each refill is another on-chain payment verification, run
10782 /// sequentially while the entry holds its admission permit and a worker
10783 /// slot, so a stream of distinct sources could keep one key's handler — and
10784 /// one of only four workers — busy indefinitely.
10785 #[test]
10786 fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10787 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10788 let data = vec![0x3Du8; 32];
10789
10790 let FreshOfferAdmission::Opened(mut entry) =
10791 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10792 else {
10793 panic!("the first offer should open the entry")
10794 };
10795
10796 // Drive pop-then-admit with a fresh source every time, exactly as a
10797 // sybil stream would. The budget must be spent by admissions, not
10798 // returned by pops.
10799 let mut admitted = 1;
10800 for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10801 let _ = entry.next_attempt();
10802 if matches!(
10803 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10804 FreshOfferAdmission::Joined
10805 ) {
10806 admitted += 1;
10807 }
10808 }
10809
10810 assert!(
10811 admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10812 "a key accepted {admitted} proofs over its lifetime, but the budget is \
10813 {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10814 );
10815 }
10816
10817 #[test]
10818 fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10819 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10820 let data = vec![0x2Cu8; 32];
10821
10822 // The opener occupies the first slot, so the cap is reached after
10823 // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10824 let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10825 for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10826 let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10827 assert!(
10828 matches!(
10829 admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10830 FreshOfferAdmission::Joined
10831 ),
10832 "sender {i} is within the legitimate close-group fan-out"
10833 );
10834 }
10835
10836 let surplus = test_peer(0xEE);
10837 assert!(
10838 matches!(
10839 admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10840 FreshOfferAdmission::Full
10841 ),
10842 "past the cap a proof is surplus: enough are already queued to place the record"
10843 );
10844 }
10845
10846 #[test]
10847 fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10848 assert!(!verification_request_exceeds_limit(
10849 config::MAX_VERIFICATION_KEYS_PER_CYCLE
10850 ));
10851 assert!(verification_request_exceeds_limit(
10852 config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10853 ));
10854 }
10855
10856 // The heavy round-1 limiter enforces the per-peer rate cooldown
10857 // and single-use round-1 → round-2 sessions.
10858 #[tokio::test]
10859 async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10860 let limiter = SubtreeRound1Limiter::new(
10861 Duration::from_hours(1),
10862 config::MAX_CONCURRENT_SUBTREE_ROUND1,
10863 );
10864 let peer = test_peer(1);
10865
10866 // First round-1 is admitted; drop the guard so concurrency is free again.
10867 let guard = limiter.admit(&peer).await;
10868 assert!(guard.is_some(), "first round-1 admitted");
10869 drop(guard);
10870 // A second round-1 within the cooldown is dropped even though the heavy
10871 // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10872 assert!(
10873 limiter.admit(&peer).await.is_none(),
10874 "second round-1 within cooldown is rate-dropped"
10875 );
10876 // A different peer has its own cooldown.
10877 assert!(limiter.admit(&test_peer(2)).await.is_some());
10878
10879 // Session: opened by round 1, consumed exactly once by the matching round 2.
10880 let hash = [7u8; 32];
10881 let nonce = [9u8; 32];
10882 assert!(
10883 limiter
10884 .open_session(peer, 42, hash, nonce, PointerBindings::new())
10885 .await
10886 );
10887 // Wrong nonce / commitment does not match.
10888 assert!(limiter
10889 .consume_session(&peer, 42, &hash, &[0u8; 32])
10890 .await
10891 .is_none());
10892 assert!(limiter
10893 .consume_session(&peer, 42, &[0u8; 32], &nonce)
10894 .await
10895 .is_none());
10896 // A round 2 with no prior round 1 (wrong challenge_id) misses.
10897 assert!(limiter
10898 .consume_session(&peer, 99, &hash, &nonce)
10899 .await
10900 .is_none());
10901 // The matching round 2 consumes it — and only once (single-use).
10902 assert!(limiter
10903 .consume_session(&peer, 42, &hash, &nonce)
10904 .await
10905 .is_some());
10906 assert!(limiter
10907 .consume_session(&peer, 42, &hash, &nonce)
10908 .await
10909 .is_none());
10910 }
10911
10912 // A session carries what its round 1 bound for each pointer to round 2,
10913 // and every live session together stays under the binding budget. A
10914 // session that does not fit is refused, and no session already opened
10915 // gives up its bindings or its place for it.
10916 #[tokio::test]
10917 async fn subtree_session_carries_pointer_bindings_within_the_budget() {
10918 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10919 let (hash, nonce) = ([1u8; 32], [2u8; 32]);
10920 let bindings = |from: u64, count: usize| -> PointerBindings {
10921 (from..)
10922 .take(count)
10923 .map(|i| {
10924 let mut key = [0u8; 32];
10925 key[..8].copy_from_slice(&i.to_le_bytes());
10926 (key, [0xAB; 32])
10927 })
10928 .collect()
10929 };
10930
10931 let half = MAX_SESSION_POINTER_BINDINGS / 2;
10932 let first = bindings(0, half);
10933 assert!(
10934 limiter
10935 .open_session(test_peer(1), 1, hash, nonce, first.clone())
10936 .await
10937 );
10938 assert!(
10939 limiter
10940 .open_session(test_peer(2), 2, hash, nonce, bindings(1 << 40, half))
10941 .await
10942 );
10943 // The budget is full: one more binding is refused, but a round 1 with
10944 // no pointers in it still opens.
10945 assert!(
10946 !limiter
10947 .open_session(test_peer(3), 3, hash, nonce, bindings(1 << 41, 1))
10948 .await
10949 );
10950 assert!(
10951 limiter
10952 .open_session(test_peer(4), 4, hash, nonce, PointerBindings::new())
10953 .await
10954 );
10955
10956 assert_eq!(
10957 limiter
10958 .consume_session(&test_peer(1), 1, &hash, &nonce)
10959 .await,
10960 Some(first.clone()),
10961 "an opened session keeps every binding it was given"
10962 );
10963 assert!(
10964 limiter
10965 .consume_session(&test_peer(3), 3, &hash, &nonce)
10966 .await
10967 .is_none(),
10968 "a refused session was never opened"
10969 );
10970 assert_eq!(
10971 limiter
10972 .consume_session(&test_peer(2), 2, &hash, &nonce)
10973 .await
10974 .map(|b| b.len()),
10975 Some(half)
10976 );
10977
10978 // Consumed sessions free their room.
10979 assert!(
10980 limiter
10981 .open_session(test_peer(5), 5, hash, nonce, bindings(1 << 42, half))
10982 .await
10983 );
10984 }
10985
10986 // A session refused for the binding budget is refused before the session
10987 // cap evicts anything: with both full, the refusal costs no session its
10988 // place.
10989 #[tokio::test]
10990 async fn a_session_refused_for_bindings_evicts_no_other_session() {
10991 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10992 let (hash, nonce) = ([1u8; 32], [2u8; 32]);
10993 let full: PointerBindings = (0u64..)
10994 .take(MAX_SESSION_POINTER_BINDINGS)
10995 .map(|i| {
10996 let mut key = [0u8; 32];
10997 key[..8].copy_from_slice(&i.to_le_bytes());
10998 (key, [0xCD; 32])
10999 })
11000 .collect();
11001 assert!(
11002 limiter
11003 .open_session(test_peer(0), 0, hash, nonce, full)
11004 .await
11005 );
11006 for id in 1..MAX_SUBTREE_SESSIONS as u64 {
11007 assert!(
11008 limiter
11009 .open_session(test_peer(1), id, hash, nonce, PointerBindings::new())
11010 .await
11011 );
11012 }
11013
11014 let one: PointerBindings = std::iter::once(([0xEE; 32], [0xEE; 32])).collect();
11015 assert!(
11016 !limiter
11017 .open_session(test_peer(2), u64::MAX, hash, nonce, one)
11018 .await
11019 );
11020 assert_eq!(
11021 limiter.sessions.read().await.len(),
11022 MAX_SUBTREE_SESSIONS,
11023 "every session is still there"
11024 );
11025 assert!(
11026 limiter
11027 .consume_session(&test_peer(0), 0, &hash, &nonce)
11028 .await
11029 .is_some(),
11030 "including the oldest"
11031 );
11032 }
11033
11034 // The concurrency pool and the per-peer cooldown are both keyed by peer id,
11035 // so a party holding several identities refills its allowance by rotating
11036 // between them and can keep the heavy pool busy indefinitely. The work
11037 // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
11038 // so a fresh identity is refused exactly like a repeat caller once it is
11039 // spent. That is the difference between bounding concurrency and bounding
11040 // sustained work.
11041 #[tokio::test]
11042 async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
11043 // Cooldown disabled so only the work budget can refuse anything.
11044 let limiter =
11045 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11046 assert!(
11047 limiter.admit(&test_peer(1)).await.is_some(),
11048 "a node starts with budget in hand so it can serve audits at once"
11049 );
11050
11051 // Serve enough proof work to run the balance into debt. Charging exactly
11052 // the burst would leave it at zero, which the next nanosecond of refill
11053 // lifts back above the line — the debt is the point.
11054 limiter
11055 .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
11056 .await;
11057
11058 for id in 2..8u8 {
11059 assert!(
11060 limiter.admit(&test_peer(id)).await.is_none(),
11061 "a never-seen peer must still be refused while the budget is spent"
11062 );
11063 }
11064 }
11065
11066 // The budget is a rate, not a quota: it comes back on its own, so an honest
11067 // auditor blocked by a flood is only delayed. Carrying the debt is what
11068 // prices an expensive proof above a cheap one — without it, a proof reading
11069 // a maximal subtree would cost no more of the next caller's wait than a
11070 // one-leaf proof.
11071 #[test]
11072 fn round1_work_budget_carries_debt_and_refills_over_time() {
11073 let now = Instant::now();
11074 let at = |secs: u64| {
11075 now.checked_add(Duration::from_secs(secs))
11076 .unwrap_or_else(Instant::now)
11077 };
11078 let mut budget = Round1WorkBudget {
11079 balance: 0,
11080 last_refill: now,
11081 };
11082 assert!(!budget.has_budget(now), "empty means empty");
11083
11084 // A proof costing four seconds' worth of refill leaves four seconds of
11085 // debt, so the wait scales with what was actually served.
11086 budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
11087 assert!(
11088 !budget.has_budget(at(3)),
11089 "still in debt three seconds after an over-large proof"
11090 );
11091 assert!(
11092 budget.has_budget(at(5)),
11093 "the debt is worked off at the refill rate"
11094 );
11095
11096 // Idle time does not bank unbounded credit for a later flood.
11097 budget.refill(at(24 * 60 * 60));
11098 assert_eq!(
11099 budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
11100 "refill is capped at the burst size"
11101 );
11102 }
11103
11104 // The heavy round-1 pool size is the tightest bound the responder applies and
11105 // the one least backed by fleet measurement, so it is read from config rather
11106 // than baked into the binary: a fleet that lands on the wrong number retunes
11107 // instead of waiting for a release. These pin that the configured value is
11108 // what actually gates admission, and that a 0 degrades to slow, not to off —
11109 // a wedged-shut responder would read on every auditor as a graced timeout,
11110 // i.e. a silent audit outage with nobody penalised and nothing in the logs.
11111 #[tokio::test]
11112 async fn round1_pool_size_comes_from_config() {
11113 // Cooldown disabled so only concurrency can refuse anything.
11114 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
11115 let held = limiter.admit(&test_peer(1)).await;
11116 assert!(held.is_some(), "the single configured slot is admitted");
11117 assert!(
11118 limiter.admit(&test_peer(2)).await.is_none(),
11119 "a second concurrent round 1 is refused at a configured pool of 1, \
11120 proving admission follows config rather than the compiled-in default"
11121 );
11122 drop(held);
11123 assert!(
11124 limiter.admit(&test_peer(2)).await.is_some(),
11125 "the slot is reusable once the first proof completes"
11126 );
11127 }
11128
11129 #[tokio::test]
11130 async fn round1_pool_size_of_zero_is_clamped_to_one() {
11131 let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
11132 assert!(
11133 limiter.admit(&test_peer(1)).await.is_some(),
11134 "a mis-set pool of 0 must still serve audits, not silently refuse every one"
11135 );
11136 }
11137
11138 fn test_key(b: u8) -> crate::ant_protocol::XorName {
11139 let mut k = [0u8; 32];
11140 k[0] = b;
11141 k
11142 }
11143
11144 #[test]
11145 fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
11146 let source = test_peer(0x91);
11147 let corroborator = test_peer(0x92);
11148 let mut evidence = types::KeyVerificationEvidence {
11149 presence: HashMap::from([(source, PresenceEvidence::Absent)]),
11150 paid_list: HashMap::new(),
11151 };
11152 let failed = KeyVerificationOutcome::QuorumFailed;
11153
11154 assert_eq!(
11155 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11156 Some(source),
11157 "a close-group rejection of a sole-source hint is punishable"
11158 );
11159 assert_eq!(
11160 punishable_singleton_replica_hint_source(
11161 &HashSet::from([source, corroborator]),
11162 &failed,
11163 &evidence,
11164 ),
11165 None,
11166 "corroborated hints must not use the sole-source penalty lane"
11167 );
11168 assert_eq!(
11169 punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
11170 None,
11171 "paid-list advertisements do not claim possession, so they leave the \
11172 replica-hint source set empty and cannot be penalized"
11173 );
11174
11175 evidence
11176 .presence
11177 .insert(source, PresenceEvidence::Unresolved);
11178 assert_eq!(
11179 punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11180 Some(source),
11181 "definitive close-group rejection is punishable without direct contradiction"
11182 );
11183 assert_eq!(
11184 punishable_singleton_replica_hint_source(
11185 &HashSet::from([source]),
11186 &KeyVerificationOutcome::QuorumInconclusive,
11187 &evidence,
11188 ),
11189 None,
11190 "timeouts and inconclusive evidence are neutral"
11191 );
11192
11193 evidence.presence.insert(source, PresenceEvidence::Absent);
11194 assert_eq!(
11195 punishable_singleton_replica_hint_source(
11196 &HashSet::from([source]),
11197 &KeyVerificationOutcome::QuorumVerified {
11198 sources: vec![corroborator],
11199 },
11200 &evidence,
11201 ),
11202 Some(source),
11203 "an explicit denial is punishable regardless of the overall outcome"
11204 );
11205 }
11206
11207 /// Build a round-2 slice challenge matching an open session. `openings` is
11208 /// empty: these tests exercise admission and session handling only, which
11209 /// run before any block is opened.
11210 fn slice_challenge(
11211 challenge_id: u64,
11212 commitment_hash: [u8; 32],
11213 nonce: [u8; 32],
11214 ) -> protocol::SubtreeSliceChallenge {
11215 protocol::SubtreeSliceChallenge {
11216 challenge_id,
11217 nonce,
11218 challenged_peer_id: [0u8; 32],
11219 expected_commitment_hash: commitment_hash,
11220 openings: Vec::new(),
11221 }
11222 }
11223
11224 // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
11225 // responder caps MUST NOT burn the single-use round-1 session.
11226 //
11227 // The handler used to consume the session first and admit second, so a
11228 // transient local capacity drop permanently destroyed that audit exchange —
11229 // every retry hit the `no live round-1 session` path and got `Transient`,
11230 // even after load cleared. Turning momentary local load into a deterministic
11231 // round-2 miss costs the responder its whole-slice credit for that round.
11232 #[tokio::test]
11233 async fn capacity_refused_slice_challenge_preserves_round1_session() {
11234 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11235 let inflight = Arc::new(RwLock::new(HashMap::new()));
11236 let round1 =
11237 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11238 let peer = test_peer(0xB1);
11239 let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
11240 let challenge = slice_challenge(id, hash, nonce);
11241
11242 assert!(
11243 round1
11244 .open_session(peer, id, hash, nonce, PointerBindings::new())
11245 .await
11246 );
11247
11248 // Saturate this peer's share so the next admission must be refused.
11249 let mut hold = Vec::new();
11250 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11251 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
11252 .await
11253 {
11254 Ok(guard) => hold.push(guard),
11255 Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
11256 }
11257 }
11258
11259 let refused =
11260 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11261 assert!(
11262 matches!(refused, SliceAdmission::Capacity(_)),
11263 "a saturated peer share must refuse on capacity, not on session"
11264 );
11265
11266 // Load clears. The session must have survived the refusal.
11267 drop(hold);
11268 let retried =
11269 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11270 assert!(
11271 matches!(retried, SliceAdmission::Admitted(..)),
11272 "the round-1 session must survive a capacity refusal so the retry succeeds"
11273 );
11274
11275 // Still single-use: the successful admission consumed it exactly once.
11276 drop(retried);
11277 let replayed =
11278 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11279 assert!(
11280 matches!(replayed, SliceAdmission::NoSession),
11281 "a consumed session must not be replayable"
11282 );
11283 }
11284
11285 // The permit taken for the session probe is released when the probe misses,
11286 // so an unsessioned flood cannot pin the responder pool shut.
11287 #[tokio::test]
11288 async fn unsessioned_slice_challenge_releases_its_admission_slot() {
11289 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11290 let inflight = Arc::new(RwLock::new(HashMap::new()));
11291 let round1 =
11292 SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11293 let peer = test_peer(0xB2);
11294 let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
11295
11296 // Far more unsessioned challenges than the per-peer cap would allow if
11297 // the slot leaked on the miss path.
11298 for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
11299 let outcome =
11300 admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11301 assert!(
11302 matches!(outcome, SliceAdmission::NoSession),
11303 "no session was ever opened, so every attempt must miss"
11304 );
11305 }
11306
11307 assert_eq!(
11308 semaphore.available_permits(),
11309 MAX_CONCURRENT_AUDIT_RESPONSES,
11310 "every global permit must be returned"
11311 );
11312 assert!(
11313 inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
11314 "no per-peer slot may be left occupied"
11315 );
11316 }
11317
11318 #[test]
11319 fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
11320 assert!(!audit_failure_revokes_holder_credit(
11321 &AuditFailureReason::Timeout
11322 ));
11323 assert!(audit_failure_revokes_holder_credit(
11324 &AuditFailureReason::DigestMismatch
11325 ));
11326 }
11327
11328 #[tokio::test]
11329 async fn audit_responder_admission_reports_per_peer_cap_full() {
11330 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11331 let inflight = Arc::new(RwLock::new(HashMap::new()));
11332 let peer = test_peer(0xA1);
11333
11334 let mut guards = Vec::new();
11335 for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11336 match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
11337 .await
11338 {
11339 Ok(guard) => guards.push(guard),
11340 Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
11341 }
11342 }
11343
11344 let Err(err) =
11345 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11346 else {
11347 panic!("admission should fail once per-peer cap is full");
11348 };
11349 assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
11350 assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
11351 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11352 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11353
11354 drop(guards);
11355 }
11356
11357 #[tokio::test]
11358 async fn audit_responder_admission_reports_global_pool_full() {
11359 let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11360 let inflight = Arc::new(RwLock::new(HashMap::new()));
11361 let peer = test_peer(0xA2);
11362
11363 let mut held_global_permits = Vec::new();
11364 for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
11365 held_global_permits.push(
11366 Arc::clone(&semaphore)
11367 .try_acquire_owned()
11368 .expect("test should be able to exhaust the global pool"),
11369 );
11370 }
11371
11372 let Err(err) =
11373 admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11374 else {
11375 panic!("admission should fail once global pool is full");
11376 };
11377 assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
11378 assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
11379 assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11380 assert_eq!(err.peer_inflight, 0);
11381 assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11382
11383 drop(held_global_permits);
11384 }
11385
11386 #[tokio::test]
11387 async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
11388 let semaphore = Arc::new(Semaphore::new(1));
11389 let inflight = Arc::new(RwLock::new(HashMap::new()));
11390 let peer = test_peer(0xA3);
11391
11392 let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
11393 .await
11394 .expect("first responder should be admitted");
11395 assert_eq!(semaphore.available_permits(), 0);
11396 assert_eq!(inflight.read().await.get(&peer), Some(&1));
11397
11398 drop(guard);
11399 assert_eq!(semaphore.available_permits(), 1);
11400 assert!(!inflight.read().await.contains_key(&peer));
11401 }
11402
11403 #[tokio::test]
11404 async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
11405 let semaphore = Arc::new(Semaphore::new(1));
11406 let inflight = Arc::new(RwLock::new(HashMap::new()));
11407 let peer = test_peer(0xA4);
11408 let held_map = inflight.write().await;
11409
11410 let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
11411 assert!(
11412 tokio::time::timeout(Duration::from_millis(10), waiting)
11413 .await
11414 .is_err(),
11415 "admission should still be waiting for the peer map"
11416 );
11417
11418 drop(held_map);
11419 assert_eq!(semaphore.available_permits(), 1);
11420 assert!(!inflight.read().await.contains_key(&peer));
11421 }
11422
11423 #[test]
11424 fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
11425 let timeout = Duration::from_secs(1);
11426 let old_received_at = Instant::now()
11427 .checked_sub(timeout)
11428 .unwrap_or_else(Instant::now);
11429
11430 assert!(request_is_stale(old_received_at, timeout));
11431 assert!(!request_is_stale(Instant::now(), timeout));
11432 }
11433
11434 #[tokio::test]
11435 async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
11436 let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
11437 let inflight = Arc::new(RwLock::new(HashMap::new()));
11438 let first_peer = test_peer(0xB3);
11439 let second_peer = test_peer(0xB4);
11440
11441 let first_guard = admit_bounded_responder(
11442 &semaphore,
11443 &inflight,
11444 &first_peer,
11445 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11446 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11447 )
11448 .await
11449 .expect("first sync from a peer should be admitted");
11450 let duplicate = admit_bounded_responder(
11451 &semaphore,
11452 &inflight,
11453 &first_peer,
11454 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11455 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11456 )
11457 .await;
11458 let other_peer = admit_bounded_responder(
11459 &semaphore,
11460 &inflight,
11461 &second_peer,
11462 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11463 NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11464 )
11465 .await;
11466
11467 assert!(matches!(
11468 duplicate,
11469 Err(ResponderAdmissionFailure {
11470 reason: ResponderRejectReason::PerPeerCapFull,
11471 ..
11472 })
11473 ));
11474 assert!(other_peer.is_ok());
11475 drop(first_guard);
11476 drop(other_peer);
11477 }
11478
11479 /// One flooding peer must not be able to hold every fresh-offer slot.
11480 ///
11481 /// This is the eviction primitive the per-peer share closes: with only a
11482 /// global bound, a single source occupies the pool, every honest offer in
11483 /// that window is refused, and because a refusal reads as absence to the
11484 /// sender's delayed possession check those refusals land as
11485 /// audit-severity penalties on *this* node.
11486 #[tokio::test]
11487 async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
11488 let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
11489 let inflight = Arc::new(RwLock::new(HashMap::new()));
11490 let flooder = test_peer(0xC1);
11491 let honest = test_peer(0xC2);
11492
11493 let mut held = Vec::new();
11494 for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11495 held.push(
11496 admit_bounded_responder(
11497 &semaphore,
11498 &inflight,
11499 &flooder,
11500 FRESH_OFFER_MAX_OUTSTANDING,
11501 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11502 )
11503 .await
11504 .expect("offers within the per-peer share are admitted"),
11505 );
11506 }
11507
11508 let flooder_excess = admit_bounded_responder(
11509 &semaphore,
11510 &inflight,
11511 &flooder,
11512 FRESH_OFFER_MAX_OUTSTANDING,
11513 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11514 )
11515 .await;
11516 assert!(
11517 matches!(
11518 flooder_excess,
11519 Err(ResponderAdmissionFailure {
11520 reason: ResponderRejectReason::PerPeerCapFull,
11521 ..
11522 })
11523 ),
11524 "one source must not exceed its fresh-offer share"
11525 );
11526
11527 let honest_offer = admit_bounded_responder(
11528 &semaphore,
11529 &inflight,
11530 &honest,
11531 FRESH_OFFER_MAX_OUTSTANDING,
11532 FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11533 )
11534 .await;
11535 assert!(
11536 honest_offer.is_ok(),
11537 "an honest sender must still be admitted while another peer floods"
11538 );
11539
11540 assert!(
11541 usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11542 < FRESH_OFFER_MAX_OUTSTANDING,
11543 "the per-peer share must leave room for other sources"
11544 );
11545
11546 drop(held);
11547 drop(honest_offer);
11548 }
11549
11550 /// Paid notifies get the same per-source treatment as every other class.
11551 #[tokio::test]
11552 async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11553 let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11554 let inflight = Arc::new(RwLock::new(HashMap::new()));
11555 let flooder = test_peer(0xC3);
11556 let honest = test_peer(0xC4);
11557
11558 let mut held = Vec::new();
11559 for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11560 held.push(
11561 admit_bounded_responder(
11562 &semaphore,
11563 &inflight,
11564 &flooder,
11565 PAID_NOTIFY_MAX_OUTSTANDING,
11566 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11567 )
11568 .await
11569 .expect("notifies within the per-peer share are admitted"),
11570 );
11571 }
11572
11573 assert!(
11574 matches!(
11575 admit_bounded_responder(
11576 &semaphore,
11577 &inflight,
11578 &flooder,
11579 PAID_NOTIFY_MAX_OUTSTANDING,
11580 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11581 )
11582 .await,
11583 Err(ResponderAdmissionFailure {
11584 reason: ResponderRejectReason::PerPeerCapFull,
11585 ..
11586 })
11587 ),
11588 "one source must not exceed its paid-notify share"
11589 );
11590 assert!(
11591 admit_bounded_responder(
11592 &semaphore,
11593 &inflight,
11594 &honest,
11595 PAID_NOTIFY_MAX_OUTSTANDING,
11596 PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11597 )
11598 .await
11599 .is_ok(),
11600 "an honest sender must still be admitted while another peer floods"
11601 );
11602
11603 drop(held);
11604 }
11605
11606 /// The fresh-offer per-source bound must guarantee headroom for a peer
11607 /// holding nothing, without throttling a single legitimate fan-out.
11608 ///
11609 /// Sized as a quota rather than a reserve, this bound refused offers during
11610 /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11611 /// refusal is charged to THIS node at audit severity because the sender
11612 /// never reads it.
11613 #[test]
11614 fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11615 let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11616
11617 assert_eq!(
11618 FRESH_OFFER_MAX_OUTSTANDING - share,
11619 FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11620 "a source holding none must always find a free slot"
11621 );
11622 assert!(
11623 share < FRESH_OFFER_MAX_OUTSTANDING,
11624 "one peer must not be able to take the whole pool"
11625 );
11626 // The failure this pins: a share sized like the request/response
11627 // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11628 // one-way bulk traffic.
11629 assert!(
11630 share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11631 "fresh offers are one-way bulk, not request/response — their share \
11632 must not be sized like the request classes'"
11633 );
11634 }
11635
11636 /// A malformed offer must be refused before it can occupy an admission
11637 /// slot, so junk cannot hold capacity for the length of a verification.
11638 #[test]
11639 fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11640 let key = test_key(0xC5);
11641
11642 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11643
11644 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11645 .expect("an offer with no proof must be refused");
11646 assert!(
11647 rejection.penalise,
11648 "an honest sender always attaches a proof"
11649 );
11650
11651 // A proof is retained per queued sender, so its size has to be bounded
11652 // here rather than at the verifier, which only sees it on a worker.
11653 let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11654 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11655 .expect("an undersized proof must be refused");
11656 assert!(
11657 rejection.penalise,
11658 "no honest sender constructs an undersized proof"
11659 );
11660 let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11661 let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11662 .expect("an oversized proof must be refused");
11663 assert!(
11664 rejection.penalise,
11665 "no honest sender constructs an oversized proof"
11666 );
11667
11668 let rejection = fresh_offer_structural_rejection(
11669 &key,
11670 &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11671 &valid_proof,
11672 )
11673 .expect("an oversized offer must be refused");
11674 assert!(
11675 rejection.penalise,
11676 "no honest sender constructs an oversized offer"
11677 );
11678
11679 let data = vec![0u8; 1];
11680 assert!(
11681 fresh_offer_structural_rejection(
11682 &crate::client::compute_address(&data),
11683 &data,
11684 &valid_proof
11685 )
11686 .is_none(),
11687 "a well-formed offer must reach admission"
11688 );
11689 }
11690
11691 /// Knowing a key must not be enough to enter its entry.
11692 ///
11693 /// Opening an entry on an unverified key/bytes association would let a peer
11694 /// that has only *learned* the key — every recipient of its `PaidNotify`,
11695 /// not just the close group that gets the chunk — seize it with junk.
11696 /// Joining one would be worse: the handler tries each queued proof against
11697 /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11698 /// on bytes it never offered.
11699 #[test]
11700 fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11701 let genuine_data = vec![0x5Au8; 128];
11702 let key = crate::client::compute_address(&genuine_data);
11703 let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11704
11705 let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11706 .expect("bytes that do not hash to the advertised key must be refused");
11707 assert!(
11708 rejection.penalise,
11709 "no honest sender offers bytes that do not hash to the advertised key"
11710 );
11711
11712 // Dispatch reaches the entry only past that rejection, so the forged
11713 // offer never touched the key and the genuine one still opens it.
11714 assert!(
11715 fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11716 "the offer that actually carries the key's bytes must reach the entry"
11717 );
11718
11719 let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11720 assert!(
11721 matches!(
11722 admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11723 FreshOfferAdmission::Opened(_)
11724 ),
11725 "an offer refused on payload shape must leave the key openable"
11726 );
11727 }
11728
11729 #[tokio::test]
11730 async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11731 let peer = test_peer(0xA5);
11732 let key = test_key(0xA5);
11733 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11734 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11735 let is_bootstrapping = Arc::new(RwLock::new(true));
11736 let bootstrap_complete_notify = Arc::new(Notify::new());
11737
11738 let now = Instant::now();
11739 queues.write().await.add_pending_verify(
11740 key,
11741 VerificationEntry {
11742 state: VerificationState::PendingVerify,
11743 verified_sources: Vec::new(),
11744 tried_sources: HashSet::new(),
11745 created_at: now,
11746 next_verify_at: now,
11747 hint_sources: HashSet::from([peer]),
11748 replica_hint_sources: HashSet::from([peer]),
11749 unresolved_retries: 0,
11750 no_holder_reported: false,
11751 },
11752 );
11753 super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11754 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11755 {
11756 let q = queues.read().await;
11757 assert!(
11758 !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11759 "capacity rejection should initially block bootstrap drain"
11760 );
11761 }
11762
11763 update_bootstrap_after_peer_removed(
11764 &peer,
11765 &bootstrap_state,
11766 &queues,
11767 &is_bootstrapping,
11768 &bootstrap_complete_notify,
11769 )
11770 .await;
11771
11772 let state = bootstrap_state.read().await;
11773 assert!(state.capacity_rejected_sources.is_empty());
11774 assert!(state.pending_keys.is_empty());
11775 assert!(state.is_drained());
11776 drop(state);
11777 assert!(!*is_bootstrapping.read().await);
11778 }
11779
11780 /// A fairness displacement forfeits the key but must not stamp its former
11781 /// owner: the owner did nothing wrong, and stamping it lets a flooding
11782 /// source block bootstrap drain through an unrelated honest peer.
11783 #[tokio::test]
11784 async fn fairness_displacement_does_not_stamp_its_victim() {
11785 let displaced_owner = test_peer(0xB1);
11786 let incoming_source = test_peer(0xB2);
11787 let displaced_key = test_key(0xB1);
11788 let admitted_key = test_key(0xB2);
11789 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11790 {
11791 let mut state = bootstrap_state.write().await;
11792 state.pending_keys.insert(displaced_key);
11793 state
11794 .capacity_rejected_sources
11795 .insert(incoming_source, Instant::now());
11796 }
11797 let outcomes = [(
11798 incoming_source,
11799 AdmissionOutcome {
11800 discovered: HashSet::from([admitted_key]),
11801 capacity_rejected_count: 0,
11802 displaced: vec![CapacityDisplacement {
11803 key: displaced_key,
11804 owner: displaced_owner,
11805 }],
11806 },
11807 )];
11808
11809 publish_bootstrap_admission_outcomes(
11810 &bootstrap_state,
11811 &outcomes,
11812 &HashSet::from([admitted_key]),
11813 )
11814 .await;
11815
11816 let state = bootstrap_state.read().await;
11817 assert!(!state.pending_keys.contains(&displaced_key));
11818 assert!(state.pending_keys.contains(&admitted_key));
11819 assert!(
11820 !state
11821 .capacity_rejected_sources
11822 .contains_key(&displaced_owner),
11823 "the displaced owner must not be charged for our own fairness reclaim"
11824 );
11825 assert!(!state
11826 .capacity_rejected_sources
11827 .contains_key(&incoming_source));
11828 }
11829
11830 /// A source that keeps overflowing us must not keep its own record fresh.
11831 ///
11832 /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11833 /// rejection the debt could never age out, so `check_bootstrap_drained`
11834 /// stayed false forever and auditing never started (Invariant 19).
11835 #[tokio::test]
11836 async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11837 const REJECTION_ROUNDS: usize = 5;
11838
11839 let source = test_peer(0xB3);
11840 let key = test_key(0xB3);
11841 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11842
11843 let first_seen = {
11844 let outcomes = [(
11845 source,
11846 AdmissionOutcome {
11847 discovered: HashSet::new(),
11848 capacity_rejected_count: 1,
11849 displaced: Vec::new(),
11850 },
11851 )];
11852 publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11853 .await;
11854 bootstrap_state
11855 .read()
11856 .await
11857 .capacity_rejected_sources
11858 .get(&source)
11859 .copied()
11860 .expect("first rejection recorded")
11861 };
11862
11863 for _ in 0..REJECTION_ROUNDS {
11864 let outcomes = [(
11865 source,
11866 AdmissionOutcome {
11867 discovered: HashSet::from([key]),
11868 capacity_rejected_count: 1,
11869 displaced: Vec::new(),
11870 },
11871 )];
11872 publish_bootstrap_admission_outcomes(
11873 &bootstrap_state,
11874 &outcomes,
11875 &HashSet::from([key]),
11876 )
11877 .await;
11878 }
11879
11880 let recorded = bootstrap_state
11881 .read()
11882 .await
11883 .capacity_rejected_sources
11884 .get(&source)
11885 .copied()
11886 .expect("debt still outstanding");
11887 assert_eq!(
11888 recorded, first_seen,
11889 "repeat rejections must not restart the expiry clock"
11890 );
11891 }
11892
11893 /// The verification-worker tick's self-heal path: a capacity rejection
11894 /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11895 /// blocks drain until the TTL expires it, at which point the same tick
11896 /// completes bootstrap without any external event.
11897 #[tokio::test]
11898 async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11899 let peer = test_peer(0xA6);
11900 let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11901 let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11902 let is_bootstrapping = Arc::new(RwLock::new(true));
11903 let bootstrap_complete_notify = Arc::new(Notify::new());
11904
11905 // PeerRemoved was fully processed before the rejection landed, so no
11906 // future event will ever clear this entry.
11907 super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11908
11909 // Within the TTL the tick keeps waiting for re-delivery.
11910 expire_and_recheck_bootstrap_drain(
11911 &bootstrap_state,
11912 &queues,
11913 &is_bootstrapping,
11914 &bootstrap_complete_notify,
11915 ReplicationConfig::default().capacity_rejected_max_age(),
11916 )
11917 .await;
11918 assert!(!bootstrap_state.read().await.is_drained());
11919 assert!(*is_bootstrapping.read().await);
11920
11921 // Past the TTL the tick expires the orphan and completes bootstrap.
11922 expire_and_recheck_bootstrap_drain(
11923 &bootstrap_state,
11924 &queues,
11925 &is_bootstrapping,
11926 &bootstrap_complete_notify,
11927 Duration::ZERO,
11928 )
11929 .await;
11930 assert!(bootstrap_state.read().await.is_drained());
11931 assert!(!*is_bootstrapping.read().await);
11932 }
11933
11934 #[test]
11935 fn first_audit_terminal_outcomes_are_stable() {
11936 let peer = test_peer(1);
11937 let passed = AuditTickResult::Passed {
11938 challenged_peer: peer,
11939 keys_checked: 1,
11940 };
11941 let timed_out = AuditTickResult::Failed {
11942 evidence: FailureEvidence::AuditFailure {
11943 challenge_id: 1,
11944 challenged_peer: peer,
11945 confirmed_failed_keys: vec![test_key(1)],
11946 summary: crate::replication::types::AuditFailureSummary::default(),
11947 reason: AuditFailureReason::Timeout,
11948 },
11949 no_response_class: Some("timeout"),
11950 };
11951
11952 assert_eq!(
11953 first_audit_terminal_outcome(&passed),
11954 FirstAuditTerminalOutcome::Passed
11955 );
11956 assert_eq!(
11957 first_audit_terminal_outcome(&timed_out),
11958 FirstAuditTerminalOutcome::Timeout
11959 );
11960 assert_eq!(
11961 first_audit_terminal_outcome(&AuditTickResult::Idle),
11962 FirstAuditTerminalOutcome::Idle
11963 );
11964 assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11965 assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11966 assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11967 assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11968 assert_eq!(
11969 FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11970 "insufficient_keys"
11971 );
11972 assert_eq!(
11973 FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11974 "bootstrap_claim"
11975 );
11976 }
11977
11978 #[test]
11979 fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11980 let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11981 let mut rng = StdRng::seed_from_u64(7);
11982 let peer = test_peer(1);
11983 let base = MonetizedPinEvent {
11984 peer,
11985 pin: [1; 32],
11986 key_count: 100,
11987 quote_ts: SystemTime::now(),
11988 };
11989
11990 // First insert into an empty slot: Queued.
11991 assert_eq!(
11992 coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11993 FirstAuditQueueOutcome::Queued
11994 );
11995
11996 // A strictly LOWER-count same-peer nomination must NOT displace it.
11997 let lower = MonetizedPinEvent {
11998 pin: [2; 32],
11999 key_count: 50,
12000 ..base
12001 };
12002 assert_eq!(
12003 coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
12004 FirstAuditQueueOutcome::SuppressedLower
12005 );
12006 assert_eq!(
12007 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12008 Some(([1; 32], 100)),
12009 "the higher-count pin is retained"
12010 );
12011
12012 // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
12013 let higher = MonetizedPinEvent {
12014 pin: [3; 32],
12015 key_count: 400,
12016 ..base
12017 };
12018 assert_eq!(
12019 coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
12020 FirstAuditQueueOutcome::Coalesced
12021 );
12022 assert_eq!(
12023 pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12024 Some(([3; 32], 400))
12025 );
12026
12027 // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
12028 let equal_newer = MonetizedPinEvent {
12029 pin: [4; 32],
12030 key_count: 400,
12031 ..base
12032 };
12033 assert_eq!(
12034 coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
12035 FirstAuditQueueOutcome::Coalesced
12036 );
12037 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12038 // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
12039 let equal_older = MonetizedPinEvent {
12040 pin: [5; 32],
12041 key_count: 400,
12042 ..base
12043 };
12044 assert_eq!(
12045 coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
12046 FirstAuditQueueOutcome::RetainedOnTie
12047 );
12048 assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12049
12050 // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
12051 let other_peer = MonetizedPinEvent {
12052 peer: test_peer(2),
12053 pin: [6; 32],
12054 key_count: 100,
12055 ..base
12056 };
12057 assert_eq!(
12058 coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
12059 FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
12060 );
12061 assert_eq!(pending.len(), 1);
12062 assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
12063 }
12064
12065 // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
12066
12067 #[test]
12068 fn first_audit_limiter_enforces_burst_then_refills() {
12069 let base = Instant::now();
12070 let mut limiter = FirstAuditLimiter::new(base);
12071 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12072
12073 // The full burst is admitted back-to-back (distinct peers).
12074 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12075 let peer = test_peer(u8::try_from(i).expect("small burst"));
12076 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12077 limiter.commit_launch(peer, 10, base);
12078 }
12079 // Bucket empty: the next distinct peer is deferred, never dropped.
12080 let extra = test_peer(0xEE);
12081 assert_eq!(
12082 limiter.assess(&extra, 10, base, 0),
12083 LimiterVerdict::RateDeferred
12084 );
12085
12086 // One full interval later exactly one token is available again.
12087 let later = base + interval;
12088 assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
12089 limiter.commit_launch(extra, 10, later);
12090 let extra2 = test_peer(0xEF);
12091 assert_eq!(
12092 limiter.assess(&extra2, 10, later, 0),
12093 LimiterVerdict::RateDeferred
12094 );
12095 }
12096
12097 #[test]
12098 fn first_audit_limiter_refill_keeps_fractional_remainder() {
12099 let base = Instant::now();
12100 let mut limiter = FirstAuditLimiter::new(base);
12101 let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12102 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12103 let peer = test_peer(u8::try_from(i).expect("small burst"));
12104 assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
12105 limiter.commit_launch(peer, 1, base);
12106 }
12107 // 1.5 intervals later one token is earned and the half interval is
12108 // NOT lost to drift...
12109 let at_1_5 = base + interval + interval / 2;
12110 let p = test_peer(0xAA);
12111 assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
12112 limiter.commit_launch(p, 1, at_1_5);
12113 // ...so the next token arrives at 2.0 intervals, not 2.5.
12114 let at_2_0 = base + interval * 2;
12115 let q = test_peer(0xAB);
12116 assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
12117 }
12118
12119 #[test]
12120 fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
12121 let base = Instant::now();
12122 let mut limiter = FirstAuditLimiter::new(base);
12123 let peer = test_peer(1);
12124 assert_eq!(
12125 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
12126 LimiterVerdict::RateDeferred
12127 );
12128 // A freed slot admits without any clock movement.
12129 assert_eq!(
12130 limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
12131 LimiterVerdict::Admit
12132 );
12133 }
12134
12135 #[test]
12136 fn first_audit_limiter_assess_consumes_nothing() {
12137 let base = Instant::now();
12138 let mut limiter = FirstAuditLimiter::new(base);
12139 let peer = test_peer(3);
12140 // Repeated assessment must not burn budget or stamp the window: only
12141 // `commit_launch` consumes (the cooldown gate between assess and
12142 // commit can defer, and that deferral must be free).
12143 for _ in 0..10 {
12144 assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
12145 }
12146 for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12147 let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
12148 assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
12149 limiter.commit_launch(p, 5, base);
12150 }
12151 }
12152
12153 #[test]
12154 fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
12155 let base = Instant::now();
12156 let mut limiter = FirstAuditLimiter::new(base);
12157 let peer = test_peer(7);
12158 assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
12159 limiter.commit_launch(peer, 100, base);
12160
12161 // A rotated pin with a similar count inside the window is dropped...
12162 let soon = base + Duration::from_mins(1);
12163 assert_eq!(
12164 limiter.assess(&peer, 100, soon, 0),
12165 LimiterVerdict::WindowDeduped
12166 );
12167 // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
12168 assert_eq!(
12169 limiter.assess(&peer, 150, soon, 0),
12170 LimiterVerdict::WindowDeduped
12171 );
12172 // ...but a >1.5x committed-count jump re-nominates immediately (an
12173 // inflated sidecar-only pin is invisible to the gossip lottery, so
12174 // the window must not shield it).
12175 assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
12176
12177 // Window expiry re-admits an unchanged count.
12178 let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
12179 assert_eq!(
12180 limiter.assess(&peer, 100, expired, 0),
12181 LimiterVerdict::Admit
12182 );
12183 }
12184
12185 #[test]
12186 fn first_audit_limiter_window_verdict_outranks_empty_budget() {
12187 // A window-deduped nomination must be DROPPED, not kept pending as
12188 // rate-deferred, even when the bucket is also empty: re-queuing a
12189 // suppressed rotation would hold a pending slot for two hours.
12190 let base = Instant::now();
12191 let mut limiter = FirstAuditLimiter::new(base);
12192 let peer = test_peer(9);
12193 assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12194 limiter.commit_launch(peer, 10, base);
12195 let other = test_peer(10);
12196 assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
12197 limiter.commit_launch(other, 10, base);
12198 assert_eq!(
12199 limiter.assess(&peer, 10, base, 0),
12200 LimiterVerdict::WindowDeduped
12201 );
12202 }
12203
12204 /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
12205 /// is answerable now but would age out of the answerability window during
12206 /// the launch jitter, so scheduling state is only ever committed for a pin
12207 /// that can still be challenged when it actually sends.
12208 #[test]
12209 fn first_audit_horizon_prefilter_boundary() {
12210 let now = SystemTime::now();
12211 // C = the too-old cutoff; H = the worst-case send horizon.
12212 let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
12213 let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
12214 // A quote whose age is exactly C at `now + H` (in the past, since C > H).
12215 let boundary = now
12216 .checked_add(h)
12217 .and_then(|t| t.checked_sub(c))
12218 .expect("boundary time");
12219
12220 // In window at `now` (age = C - H < C)...
12221 assert!(quote_within_audit_window(boundary, now));
12222 // ...but the horizon prefilter rejects it (age == C at now + H).
12223 assert!(!quote_answerable_through_nominal_jitter(boundary, now));
12224
12225 // A hair newer stays answerable through the horizon; a hair older does
12226 // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
12227 // a nanosecond step would round to the same instant there.
12228 let newer = boundary
12229 .checked_add(Duration::from_micros(1))
12230 .expect("newer");
12231 let older = boundary
12232 .checked_sub(Duration::from_micros(1))
12233 .expect("older");
12234 assert!(quote_answerable_through_nominal_jitter(newer, now));
12235 assert!(!quote_answerable_through_nominal_jitter(older, now));
12236
12237 // A quote too far in the FUTURE is rejected at `now`, independent of the
12238 // horizon.
12239 let future = now
12240 .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
12241 .and_then(|t| t.checked_add(Duration::from_mins(1)))
12242 .expect("future");
12243 assert!(!quote_answerable_through_nominal_jitter(future, now));
12244 }
12245
12246 /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
12247 /// answerability check fails at promotion is fully state-neutral — it stamps
12248 /// no `first_audited`, no per-peer window, refunds its token, releases its
12249 /// in-flight slot, does not flip the lane, and does not count a launch — and
12250 /// a same-peer, same-count successor enqueued DURING the reservation is
12251 /// retained and becomes the next reservation after the cancel. This is the
12252 /// exact hole the reviewer flagged: suppression must never outlive a launch
12253 /// that did not send.
12254 /// A pending pin that has aged past the answerability horizon must not
12255 /// suppress a live lower-count nomination for the same peer: under token
12256 /// starvation no reserve scan ever collects the dead entry, so without the
12257 /// enqueue-time check the peer would stay unauditable through this path
12258 /// indefinitely (e.g. after a prune legitimately lowered its key count).
12259 #[test]
12260 fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
12261 let obs = Arc::new(FirstAuditObservability::default());
12262 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12263 let peer = test_peer(1);
12264
12265 let dead_quote = SystemTime::now()
12266 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12267 .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12268 .expect("past wall time");
12269 let stale_high = MonetizedPinEvent {
12270 peer,
12271 pin: [1; 32],
12272 key_count: 400,
12273 quote_ts: dead_quote,
12274 };
12275 scheduler.enqueue(stale_high, &obs);
12276 assert_eq!(scheduler.pending_len(), 1);
12277
12278 // A fresh, lower-count nomination (a post-prune commitment).
12279 let fresh_lower = MonetizedPinEvent {
12280 peer,
12281 pin: [2; 32],
12282 key_count: 100,
12283 quote_ts: SystemTime::now(),
12284 };
12285 scheduler.enqueue(fresh_lower, &obs);
12286
12287 assert_eq!(scheduler.pending_len(), 1);
12288 assert_eq!(
12289 scheduler.pending.peek(&peer).map(|e| e.pin),
12290 Some([2; 32]),
12291 "the live nomination replaced the dead incumbent"
12292 );
12293 assert_eq!(
12294 obs.suppressed_lower.load(Ordering::Relaxed),
12295 0,
12296 "no self-erasure signal for displacing a dead pin"
12297 );
12298 assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
12299 assert_eq!(
12300 obs.outside_answerability_window.load(Ordering::Relaxed),
12301 1,
12302 "the dead incumbent is accounted as an expiry"
12303 );
12304 }
12305
12306 /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
12307 /// nomination still loses to an answerable higher-count pending pin.
12308 #[test]
12309 fn first_audit_live_incumbent_still_suppresses_lower_count() {
12310 let obs = Arc::new(FirstAuditObservability::default());
12311 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12312 let peer = test_peer(1);
12313
12314 let live_high = MonetizedPinEvent {
12315 peer,
12316 pin: [1; 32],
12317 key_count: 400,
12318 quote_ts: SystemTime::now(),
12319 };
12320 scheduler.enqueue(live_high, &obs);
12321 let cheaper = MonetizedPinEvent {
12322 peer,
12323 pin: [2; 32],
12324 key_count: 100,
12325 quote_ts: SystemTime::now(),
12326 };
12327 scheduler.enqueue(cheaper, &obs);
12328
12329 assert_eq!(scheduler.pending_len(), 1);
12330 assert_eq!(
12331 scheduler.pending.peek(&peer).map(|e| e.pin),
12332 Some([1; 32]),
12333 "the higher-count live pin is retained"
12334 );
12335 assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
12336 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
12337 }
12338
12339 /// A fresh nomination for peer `b` (distinct pin per peer).
12340 fn live_nomination(b: u8) -> MonetizedPinEvent {
12341 MonetizedPinEvent {
12342 peer: test_peer(b),
12343 pin: [b; 32],
12344 key_count: 100,
12345 quote_ts: SystemTime::now(),
12346 }
12347 }
12348
12349 /// The pending admission cap must equal the number of usable launches the
12350 /// token budget can perform inside one answerability window, counted by
12351 /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
12352 /// tokens at age zero, one refill per launch interval), not by repeating
12353 /// the derivation formula. Any larger and admitted work is guaranteed to
12354 /// expire unlaunched; any smaller and the budget idles while nominations
12355 /// are displaced.
12356 #[test]
12357 fn first_audit_pending_cap_matches_strict_launch_horizon() {
12358 let quote_ts = SystemTime::now();
12359 // Burst launches fire at age zero and must pass the reserve predicate.
12360 assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
12361 let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
12362 let mut refill = 1u32;
12363 loop {
12364 let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
12365 let at = quote_ts + age;
12366 if !quote_answerable_through_nominal_jitter(quote_ts, at) {
12367 break;
12368 }
12369 usable += 1;
12370 refill += 1;
12371 assert!(refill < 10_000, "runaway horizon simulation");
12372 }
12373 assert_eq!(
12374 FIRST_AUDIT_PENDING_CAP, usable,
12375 "cap must match the simulated strict launch horizon"
12376 );
12377 }
12378
12379 /// The pending queue is sized to the launch budget while the dedup set
12380 /// keeps the commitment-cache bound: shrinking `first_audited` would
12381 /// forget audited pins and re-admit duplicates.
12382 #[test]
12383 fn first_audit_pending_cap_independent_of_dedup_cap() {
12384 let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12385 assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
12386 assert_eq!(
12387 scheduler.first_audited.cap().get(),
12388 MAX_LAST_COMMITMENT_BY_PEER
12389 );
12390 }
12391
12392 /// Admission beyond the cap displaces exactly one incumbent per overflow
12393 /// and every displacement is accounted as `capacity_evicted` — the steady
12394 /// overload signal — never silent loss, and never an admission refusal.
12395 #[test]
12396 fn first_audit_admission_beyond_cap_displaces_and_counts() {
12397 let obs = Arc::new(FirstAuditObservability::default());
12398 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12399 let overflow: usize = 5;
12400 let total = FIRST_AUDIT_PENDING_CAP + overflow;
12401
12402 for i in 0..total {
12403 let b = u8::try_from(i + 1).expect("test peer count fits u8");
12404 scheduler.enqueue(live_nomination(b), &obs);
12405 }
12406
12407 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12408 assert_eq!(
12409 obs.capacity_evicted.load(Ordering::Relaxed),
12410 u64::try_from(overflow).expect("overflow fits u64"),
12411 "each admission past the cap displaces exactly one entry"
12412 );
12413 assert_eq!(
12414 obs.queued.load(Ordering::Relaxed),
12415 u64::try_from(total).expect("total fits u64"),
12416 "displacement is not an admission refusal"
12417 );
12418 // Every arrival was admitted (the newest always enters the sample).
12419 let last = u8::try_from(total).expect("test peer count fits u8");
12420 assert!(
12421 scheduler.pending.peek(&test_peer(last)).is_some(),
12422 "the newest arrival always enters the sample"
12423 );
12424 }
12425
12426 /// The reviewer-demonstrated suppression route: a target followed by an
12427 /// ordered batch of distinct-peer nominations, all inside one ingress
12428 /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
12429 /// the token bucket EMPTY so no reservation can intervene. Under the old
12430 /// keep-newest LRU the target was evicted with certainty; under random
12431 /// displacement its per-overflow eviction probability is `1/cap`, so
12432 /// across repeated trials the target must survive some runs and be
12433 /// displaced in others — never deterministically flushed, and every
12434 /// displacement accounted.
12435 #[test]
12436 fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
12437 let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
12438 assert!(FIRST_AUDIT_PENDING_CAP < flood);
12439 assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
12440
12441 let trials = 100u64;
12442 let mut survived = 0u32;
12443 let mut evicted = 0u32;
12444 for trial in 0..trials {
12445 let obs = Arc::new(FirstAuditObservability::default());
12446 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12447 // Deterministic per-trial seed: the run is fully reproducible (no
12448 // flake budget at all) while still exercising 100 distinct
12449 // eviction sequences.
12450 scheduler.rng = StdRng::seed_from_u64(trial);
12451 // Drain the burst tokens so the pre-overflow reservation
12452 // opportunity cannot fire: this isolates pure retention.
12453 scheduler.limiter.reserve_token();
12454 scheduler.limiter.reserve_token();
12455
12456 let target = test_peer(200);
12457 scheduler.enqueue(live_nomination(200), &obs);
12458 for i in 0..flood {
12459 let b = u8::try_from(i + 1).expect("flood peer fits u8");
12460 scheduler.enqueue(live_nomination(b), &obs);
12461 }
12462
12463 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12464 let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
12465 .expect("overflow count fits u64");
12466 assert_eq!(
12467 obs.capacity_evicted.load(Ordering::Relaxed),
12468 overflows,
12469 "every overflow past the cap is accounted, none silent"
12470 );
12471 if scheduler.pending.peek(&target).is_some() {
12472 survived += 1;
12473 } else {
12474 evicted += 1;
12475 }
12476 }
12477 // With eviction probability 1/cap per overflow, P(target survives one
12478 // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
12479 // 100 seeded trials — and the seeds make the split exactly
12480 // reproducible rather than a (vanishingly small) flake budget.
12481 assert!(
12482 survived > 0,
12483 "target must survive some ordered floods — deterministic eviction \
12484 would mean keep-newest retention regressed"
12485 );
12486 assert!(
12487 evicted > 0,
12488 "target must also be displaceable — otherwise overflow is refusing \
12489 admissions instead of sampling"
12490 );
12491 }
12492
12493 /// With a token AVAILABLE, an overflowing arrival must first give pending
12494 /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12495 /// one entry out of the queue, so admission proceeds without any eviction.
12496 #[test]
12497 fn first_audit_overflow_reserves_before_destructive_eviction() {
12498 let obs = Arc::new(FirstAuditObservability::default());
12499 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12500 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12501
12502 for i in 0..FIRST_AUDIT_PENDING_CAP {
12503 let b = u8::try_from(i + 1).expect("test peer count fits u8");
12504 scheduler.enqueue(live_nomination(b), &obs);
12505 }
12506 let overflowing = live_nomination(250);
12507 assert!(scheduler.would_displace(&overflowing));
12508
12509 // The drainer's pre-overflow sequence: reserve, then enqueue.
12510 assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12511 assert!(
12512 !scheduler.would_displace(&overflowing),
12513 "a successful reservation frees the slot"
12514 );
12515 scheduler.enqueue(overflowing, &obs);
12516
12517 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12518 assert_eq!(
12519 obs.capacity_evicted.load(Ordering::Relaxed),
12520 0,
12521 "no destructive eviction when a launch opportunity existed"
12522 );
12523 }
12524
12525 /// Displacement stamps no suppression state: a displaced peer's next
12526 /// nomination re-enters like any newcomer (it is NOT window-deduped or
12527 /// treated as a duplicate), so under overload every peer keeps an
12528 /// unpredictable chance of prompt first audit.
12529 #[test]
12530 fn first_audit_displaced_peer_may_be_renominated() {
12531 let obs = Arc::new(FirstAuditObservability::default());
12532 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12533 let total = FIRST_AUDIT_PENDING_CAP + 1;
12534
12535 for i in 0..total {
12536 let b = u8::try_from(i + 1).expect("test peer count fits u8");
12537 scheduler.enqueue(live_nomination(b), &obs);
12538 }
12539 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12540 // Find whichever peer the random displacement removed.
12541 let displaced = (1..=total)
12542 .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12543 .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12544 .expect("exactly one admitted peer was displaced");
12545
12546 scheduler.enqueue(live_nomination(displaced), &obs);
12547
12548 assert!(
12549 scheduler.pending.peek(&test_peer(displaced)).is_some(),
12550 "the displaced peer re-enters the sample"
12551 );
12552 assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12553 assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12554 assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12555 assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12556 }
12557
12558 /// The periodic sweep collects expired pending entries even when the token
12559 /// bucket is empty — the reserve path returns at the budget gate and never
12560 /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12561 /// honest under fleet-wide starvation.
12562 #[test]
12563 fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12564 let obs = Arc::new(FirstAuditObservability::default());
12565 let mono = Instant::now();
12566 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12567
12568 let dead_quote = SystemTime::now()
12569 .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12570 .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12571 .expect("past wall time");
12572 scheduler.enqueue(
12573 MonetizedPinEvent {
12574 peer: test_peer(1),
12575 pin: [1; 32],
12576 key_count: 100,
12577 quote_ts: dead_quote,
12578 },
12579 &obs,
12580 );
12581 scheduler.enqueue(
12582 MonetizedPinEvent {
12583 peer: test_peer(2),
12584 pin: [2; 32],
12585 key_count: 100,
12586 quote_ts: SystemTime::now(),
12587 },
12588 &obs,
12589 );
12590 assert_eq!(scheduler.pending_len(), 2);
12591
12592 // Empty the bucket so the reserve path is budget-gated (fleet-wide
12593 // starvation) and cannot collect the dead entry itself.
12594 scheduler.limiter.tokens = 0;
12595 let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12596 assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12597 assert_eq!(
12598 scheduler.pending_len(),
12599 2,
12600 "budget-gated reserve scans nothing"
12601 );
12602
12603 let wall_now = SystemTime::now();
12604 assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12605 assert_eq!(scheduler.pending_len(), 1);
12606 assert!(
12607 scheduler.pending.peek(&test_peer(2)).is_some(),
12608 "the live entry survives the sweep"
12609 );
12610 assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12611 let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12612 assert!(
12613 Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12614 "the age gauge reflects only live work after the sweep"
12615 );
12616 }
12617
12618 #[test]
12619 #[allow(clippy::too_many_lines)]
12620 fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12621 let obs = Arc::new(FirstAuditObservability::default());
12622 let mono = Instant::now();
12623 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12624
12625 // A pre-existing window sentinel for an UNRELATED peer must survive the
12626 // cancel byte-for-byte (cancel never touches `recent`).
12627 let sentinel_peer = test_peer(0xAA);
12628 scheduler.limiter.promote(sentinel_peer, 500, mono);
12629 let sentinel_before = scheduler
12630 .limiter
12631 .recent
12632 .peek(&sentinel_peer)
12633 .copied()
12634 .expect("sentinel present");
12635
12636 let peer = test_peer(1);
12637 let a = MonetizedPinEvent {
12638 peer,
12639 pin: [1; 32],
12640 key_count: 100,
12641 quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12642 };
12643 scheduler.enqueue(a, &obs);
12644
12645 let tokens_before = scheduler.tokens();
12646 let lane_before = scheduler.oldest_first_lane;
12647 let launched_before = obs.launched.load(Ordering::Relaxed);
12648 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12649
12650 // Reserve A (jitter 0 so it is immediately due).
12651 let inflight0 = obs.inflight.load(Ordering::Relaxed);
12652 assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12653 assert_eq!(scheduler.reserved_peer(), Some(peer));
12654 assert_eq!(
12655 scheduler.tokens(),
12656 tokens_before - 1,
12657 "reserve consumes a token"
12658 );
12659 assert_eq!(
12660 obs.inflight.load(Ordering::Relaxed),
12661 1,
12662 "reserve holds a slot"
12663 );
12664
12665 // A same-peer, same-count successor arrives DURING the reservation. It
12666 // must be retained (bypasses the window for the reserved peer) and must
12667 // NOT create a second reservation.
12668 let b = MonetizedPinEvent {
12669 peer,
12670 pin: [2; 32],
12671 key_count: 100,
12672 quote_ts: SystemTime::now(),
12673 };
12674 scheduler.enqueue(b, &obs);
12675 assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12676 assert!(
12677 !scheduler.try_reserve(
12678 mono,
12679 obs.inflight.load(Ordering::Relaxed),
12680 Duration::ZERO,
12681 &cooldown,
12682 &obs
12683 ),
12684 "no second reservation while one is outstanding"
12685 );
12686
12687 // Resolve A with an injected wall time PAST A's answerability cutoff.
12688 let reservation = scheduler
12689 .take_due_reservation(mono)
12690 .expect("A is due at jitter 0");
12691 let wall_fail = a
12692 .quote_ts
12693 .checked_add(GOSSIP_ANSWERABILITY_TTL)
12694 .and_then(|t| t.checked_add(Duration::from_secs(1)))
12695 .expect("past-cutoff wall time");
12696 let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12697 assert!(
12698 promoted.is_none(),
12699 "answerability lapsed -> cancelled, not promoted"
12700 );
12701
12702 // State-neutral cancel.
12703 assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12704 assert!(
12705 scheduler.limiter.recent.peek(&peer).is_none(),
12706 "cancel stamps no per-peer window"
12707 );
12708 assert_eq!(
12709 scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12710 Some(sentinel_before),
12711 "unrelated window sentinel untouched"
12712 );
12713 assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12714 assert_eq!(
12715 scheduler.tokens(),
12716 tokens_before,
12717 "token refunded on cancel"
12718 );
12719 assert_eq!(
12720 obs.inflight.load(Ordering::Relaxed),
12721 0,
12722 "in-flight slot released"
12723 );
12724 assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12725 assert_eq!(
12726 obs.launched.load(Ordering::Relaxed),
12727 launched_before,
12728 "no launch counted"
12729 );
12730 assert_eq!(
12731 obs.outside_answerability_window.load(Ordering::Relaxed),
12732 1,
12733 "the cancel reason is recorded"
12734 );
12735
12736 // The successor is still pending and is now fully schedulable: a fresh
12737 // reserve makes B the next reservation (proving eligibility, not merely
12738 // that the limiter would admit it).
12739 assert_eq!(
12740 scheduler.pending_len(),
12741 1,
12742 "successor still pending after cancel"
12743 );
12744 assert!(scheduler.reserved.is_none());
12745 assert!(scheduler.try_reserve(
12746 mono,
12747 obs.inflight.load(Ordering::Relaxed),
12748 Duration::ZERO,
12749 &cooldown,
12750 &obs
12751 ));
12752 assert_eq!(
12753 scheduler.reserved_peer(),
12754 Some(peer),
12755 "the retained successor becomes the next reservation"
12756 );
12757 }
12758
12759 /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12760 /// race, the reserved event is requeued ONLY if no same-peer successor is
12761 /// already pending. A successor arrived after the reservation, so it is the
12762 /// newer nomination (e.g. a count jump) and must not be overwritten by the
12763 /// older reserved event.
12764 #[test]
12765 fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12766 let obs = Arc::new(FirstAuditObservability::default());
12767 let mono = Instant::now();
12768 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12769 let peer = test_peer(1);
12770
12771 // Reserve A.
12772 let a = MonetizedPinEvent {
12773 peer,
12774 pin: [1; 32],
12775 key_count: 100,
12776 quote_ts: SystemTime::now(),
12777 };
12778 scheduler.enqueue(a, &obs);
12779 let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12780 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12781
12782 // A newer same-peer successor B (a count jump) arrives during the
12783 // reservation and is retained.
12784 let b = MonetizedPinEvent {
12785 peer,
12786 pin: [2; 32],
12787 key_count: 400,
12788 quote_ts: SystemTime::now(),
12789 };
12790 scheduler.enqueue(b, &obs);
12791 assert_eq!(scheduler.pending_len(), 1);
12792
12793 // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12794 // is already stamped for the peer, so promotion loses the race.
12795 let reservation = scheduler.take_due_reservation(mono).expect("due");
12796 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12797 cooldown.insert(peer, mono); // freshly on cooldown
12798 let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12799 assert!(promoted.is_none(), "cooldown race -> not promoted");
12800
12801 // B (newer) is preserved; A did NOT overwrite it.
12802 assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12803 assert_eq!(
12804 scheduler.pending.peek(&peer).map(|e| e.pin),
12805 Some([2; 32]),
12806 "the newer successor B is retained, not the older reserved A"
12807 );
12808 assert!(scheduler.first_audited.is_empty());
12809 assert!(scheduler.limiter.recent.peek(&peer).is_none());
12810 }
12811
12812 /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12813 /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12814 /// and saturates to `0` for a future-dated quote (clock skew) without
12815 /// panicking. A climbing value is the pending-work-aging-out signal.
12816 #[test]
12817 fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12818 let now = SystemTime::now();
12819 let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12820 assert_eq!(
12821 scheduler.oldest_pending_quote_age_ms(now),
12822 0,
12823 "empty pending -> zero"
12824 );
12825
12826 // Two peers: quotes 10s and 2s old. The gauge must track the older.
12827 for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12828 let _ = coalesce_first_audit_event(
12829 &mut scheduler.pending,
12830 MonetizedPinEvent {
12831 peer: test_peer(peer_id),
12832 pin,
12833 key_count: 100,
12834 quote_ts: now - Duration::from_secs(secs),
12835 },
12836 true,
12837 &mut scheduler.rng,
12838 );
12839 }
12840 assert_eq!(
12841 scheduler.oldest_pending_quote_age_ms(now),
12842 10_000,
12843 "tracks the oldest (10s), not the newest (2s)"
12844 );
12845
12846 // A future-dated quote (clock skew) saturates to zero, never panics.
12847 let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12848 let _ = coalesce_first_audit_event(
12849 &mut skewed.pending,
12850 MonetizedPinEvent {
12851 peer: test_peer(3),
12852 pin: [3; 32],
12853 key_count: 100,
12854 quote_ts: now + Duration::from_secs(5),
12855 },
12856 true,
12857 &mut skewed.rng,
12858 );
12859 assert_eq!(
12860 skewed.oldest_pending_quote_age_ms(now),
12861 0,
12862 "future quote_ts saturates to zero"
12863 );
12864 }
12865
12866 /// A flood of strictly-lower-count same-peer nominations must neither
12867 /// displace the retained higher pin NOR disturb its recency position (each
12868 /// is suppressed via `peek`, no `push`), and each must be counted as
12869 /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12870 /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12871 /// (the documented `lru` contract that also drives the reserve scan's lane
12872 /// ordering), deliberately independent of the overflow policy: eviction is
12873 /// random-victim, so no assertion may require a particular peer to be
12874 /// displaced.
12875 #[test]
12876 fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12877 let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12878 LruCache::new(NonZeroUsize::new(2).unwrap());
12879 let mut rng = StdRng::seed_from_u64(11);
12880 let victim = test_peer(1);
12881 let other = test_peer(2);
12882 // Victim (high count) inserted first (older), then `other` (newer/MRU).
12883 let _ = coalesce_first_audit_event(
12884 &mut pending,
12885 MonetizedPinEvent {
12886 peer: victim,
12887 pin: [1; 32],
12888 key_count: 400,
12889 quote_ts: SystemTime::now(),
12890 },
12891 true,
12892 &mut rng,
12893 );
12894 let _ = coalesce_first_audit_event(
12895 &mut pending,
12896 MonetizedPinEvent {
12897 peer: other,
12898 pin: [9; 32],
12899 key_count: 100,
12900 quote_ts: SystemTime::now(),
12901 },
12902 true,
12903 &mut rng,
12904 );
12905 let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12906 assert_eq!(
12907 order_before,
12908 vec![other, victim],
12909 "sanity: `other` is MRU, the victim is LRU"
12910 );
12911
12912 // Flood the victim with cheaper nominations.
12913 let mut suppressed = 0u64;
12914 for i in 0..8u8 {
12915 let out = coalesce_first_audit_event(
12916 &mut pending,
12917 MonetizedPinEvent {
12918 peer: victim,
12919 pin: [i; 32],
12920 key_count: 50,
12921 quote_ts: SystemTime::now(),
12922 },
12923 true,
12924 &mut rng,
12925 );
12926 assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12927 suppressed += 1;
12928 }
12929 assert_eq!(suppressed, 8);
12930 // Victim pin/count unchanged.
12931 assert_eq!(
12932 pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12933 Some(([1; 32], 400))
12934 );
12935 // Recency untouched: the iteration order (which the reserve lanes
12936 // consume) is byte-for-byte what it was before the flood.
12937 let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12938 assert_eq!(
12939 order_after, order_before,
12940 "the suppressed-lower flood must not have changed any recency position"
12941 );
12942 }
12943
12944 /// The cooldown-race requeue counts a genuine different-peer capacity
12945 /// eviction (the ADR promises capacity loss is observable).
12946 #[test]
12947 fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12948 let obs = Arc::new(FirstAuditObservability::default());
12949 let mono = Instant::now();
12950 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12951 // Pending capacity 1 so a requeue of a different peer must evict.
12952 scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12953 let reserved_peer = test_peer(1);
12954 let other_peer = test_peer(2);
12955
12956 // Reserve peer 1.
12957 scheduler.enqueue(
12958 MonetizedPinEvent {
12959 peer: reserved_peer,
12960 pin: [1; 32],
12961 key_count: 100,
12962 quote_ts: SystemTime::now(),
12963 },
12964 &obs,
12965 );
12966 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12967 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12968
12969 // A DIFFERENT peer fills the single pending slot during the reservation.
12970 scheduler.enqueue(
12971 MonetizedPinEvent {
12972 peer: other_peer,
12973 pin: [2; 32],
12974 key_count: 100,
12975 quote_ts: SystemTime::now(),
12976 },
12977 &obs,
12978 );
12979 assert_eq!(scheduler.pending_len(), 1);
12980
12981 // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12982 let reservation = scheduler.take_due_reservation(mono).expect("due");
12983 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12984 cooldown.insert(reserved_peer, mono);
12985 let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12986 assert!(scheduler
12987 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12988 .is_none());
12989 assert_eq!(
12990 obs.capacity_evicted.load(Ordering::Relaxed),
12991 cap_before + 1,
12992 "the requeue eviction of a different peer is counted"
12993 );
12994 assert_eq!(
12995 scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12996 Some([1; 32])
12997 );
12998 }
12999
13000 /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
13001 /// nomination arriving while an inflated pin is PENDING must not displace it.
13002 /// The inflated pin stays and is the one launched.
13003 #[test]
13004 fn first_audit_pending_lower_count_does_not_replace_higher() {
13005 let obs = Arc::new(FirstAuditObservability::default());
13006 let mono = Instant::now();
13007 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13008 let peer = test_peer(1);
13009
13010 // Inflated (high-count) sidecar pin lands in pending.
13011 scheduler.enqueue(
13012 MonetizedPinEvent {
13013 peer,
13014 pin: [1; 32],
13015 key_count: 400,
13016 quote_ts: SystemTime::now(),
13017 },
13018 &obs,
13019 );
13020 // A cheaper same-peer settlement arrives right after.
13021 scheduler.enqueue(
13022 MonetizedPinEvent {
13023 peer,
13024 pin: [2; 32],
13025 key_count: 100,
13026 quote_ts: SystemTime::now(),
13027 },
13028 &obs,
13029 );
13030
13031 assert_eq!(scheduler.pending_len(), 1);
13032 assert_eq!(
13033 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13034 Some(([1; 32], 400)),
13035 "the inflated pin must not be erased by the cheaper successor"
13036 );
13037 // The dropped cheaper nomination is counted through the enqueue path.
13038 assert_eq!(
13039 obs.suppressed_lower.load(Ordering::Relaxed),
13040 1,
13041 "the attempted cheaper-pin self-erasure is observable"
13042 );
13043
13044 // It reserves and promotes as the inflated pin/count.
13045 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13046 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13047 let reservation = scheduler.take_due_reservation(mono).expect("due");
13048 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13049 let (event, _slot) = scheduler
13050 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13051 .expect("promotes");
13052 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13053 }
13054
13055 /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
13056 /// loses the cooldown race must be requeued OVER a lower-count same-peer
13057 /// successor that arrived during its jitter, and must remain launchable once
13058 /// the shared cooldown expires — the cheaper successor cannot suppress it.
13059 #[test]
13060 fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
13061 let obs = Arc::new(FirstAuditObservability::default());
13062 let mono = Instant::now();
13063 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13064 let peer = test_peer(1);
13065
13066 // Reserve the inflated pin.
13067 scheduler.enqueue(
13068 MonetizedPinEvent {
13069 peer,
13070 pin: [1; 32],
13071 key_count: 400,
13072 quote_ts: SystemTime::now(),
13073 },
13074 &obs,
13075 );
13076 let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13077 assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13078
13079 // A cheaper successor arrives during the reservation (bypasses the
13080 // window as the reserved peer) and sits in pending.
13081 scheduler.enqueue(
13082 MonetizedPinEvent {
13083 peer,
13084 pin: [2; 32],
13085 key_count: 100,
13086 quote_ts: SystemTime::now(),
13087 },
13088 &obs,
13089 );
13090 assert_eq!(scheduler.pending_len(), 1);
13091
13092 // Resolve: answerability passes but the shared cooldown is already
13093 // stamped, so the reservation loses the race and requeues.
13094 let reservation = scheduler.take_due_reservation(mono).expect("due");
13095 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13096 cooldown.insert(peer, mono);
13097 assert!(scheduler
13098 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13099 .is_none());
13100
13101 // The inflated pin (400) replaced the cheaper successor (100).
13102 assert_eq!(scheduler.pending_len(), 1);
13103 assert_eq!(
13104 scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13105 Some(([1; 32], 400)),
13106 "the inflated reserved pin must survive the requeue over the cheaper successor"
13107 );
13108 assert!(scheduler.first_audited.is_empty());
13109 assert!(scheduler.limiter.recent.peek(&peer).is_none());
13110
13111 // Once the shared cooldown expires, the inflated pin reserves and
13112 // promotes with its intended pin/count.
13113 let later = mono
13114 .checked_add(Duration::from_secs(
13115 config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
13116 ))
13117 .expect("later");
13118 let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
13119 assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
13120 let reservation = scheduler.take_due_reservation(later).expect("due");
13121 let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
13122 let (event, _slot) = scheduler
13123 .resolve(
13124 reservation,
13125 SystemTime::now(),
13126 later,
13127 &mut cooldown_later,
13128 &obs,
13129 )
13130 .expect("promotes after cooldown");
13131 assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13132 }
13133
13134 /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
13135 /// launch lane, driven through the real scheduler (reserve -> resolve ->
13136 /// promote), so a stream of fresh nominations cannot keep every launch on
13137 /// the newest lane and starve the oldest.
13138 #[test]
13139 fn first_audit_lane_alternates_across_promotions() {
13140 let obs = Arc::new(FirstAuditObservability::default());
13141 let mono = Instant::now();
13142 let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13143 let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13144
13145 // Two distinct peers; the newest-inserted is the MRU (newest lane end).
13146 let oldest_peer = test_peer(1);
13147 let newest_peer = test_peer(2);
13148 scheduler.enqueue(
13149 MonetizedPinEvent {
13150 peer: oldest_peer,
13151 pin: [1; 32],
13152 key_count: 100,
13153 quote_ts: SystemTime::now(),
13154 },
13155 &obs,
13156 );
13157 scheduler.enqueue(
13158 MonetizedPinEvent {
13159 peer: newest_peer,
13160 pin: [2; 32],
13161 key_count: 100,
13162 quote_ts: SystemTime::now(),
13163 },
13164 &obs,
13165 );
13166
13167 let mut launched_peers = Vec::new();
13168 for _ in 0..2 {
13169 assert!(scheduler.try_reserve(
13170 mono,
13171 obs.inflight.load(Ordering::Relaxed),
13172 Duration::ZERO,
13173 &cooldown,
13174 &obs
13175 ));
13176 let reservation = scheduler.take_due_reservation(mono).expect("due");
13177 // Answerable wall time == the quote's own time (age 0).
13178 let (event, _slot) = scheduler
13179 .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13180 .expect("fresh in-window quote promotes");
13181 launched_peers.push(event.peer);
13182 }
13183
13184 // First launch takes the newest lane (lane starts false = newest), the
13185 // second takes the oldest lane: strict alternation.
13186 assert_eq!(
13187 launched_peers,
13188 vec![newest_peer, oldest_peer],
13189 "consecutive promotions alternate newest-then-oldest lane"
13190 );
13191 }
13192
13193 #[test]
13194 fn first_audit_count_jump_boundaries() {
13195 // Exactly 1.5x is NOT a jump; strictly above is.
13196 assert!(!first_audit_count_jump(100, 150));
13197 assert!(first_audit_count_jump(100, 151));
13198 // Anything beats an audited zero; zero never jumps.
13199 assert!(first_audit_count_jump(0, 1));
13200 assert!(!first_audit_count_jump(0, 0));
13201 // Equal max counts must not jump (and must not overflow).
13202 assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
13203 }
13204
13205 /// A verified payment's quote list includes the local node's own quote, so
13206 /// the verifier emits a monetized-pin event for the local peer on every
13207 /// payment it verifies. The node cannot network-audit itself, so the
13208 /// scheduler must drop such an event at ingress: never queued, and hence
13209 /// never launched nor marked first-audited.
13210 #[test]
13211 fn first_audit_queue_drops_self_targeting_events() {
13212 let obs = Arc::new(FirstAuditObservability::default());
13213 let self_peer = test_peer(1);
13214 let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
13215 let self_event = MonetizedPinEvent {
13216 peer: self_peer,
13217 pin: [7; 32],
13218 key_count: 1,
13219 quote_ts: SystemTime::now(),
13220 };
13221
13222 scheduler.enqueue(self_event, &obs);
13223 assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
13224 assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
13225 assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
13226
13227 // A remote peer's event still queues normally under the same filter.
13228 let remote_event = MonetizedPinEvent {
13229 peer: test_peer(2),
13230 pin: [8; 32],
13231 ..self_event
13232 };
13233 scheduler.enqueue(remote_event, &obs);
13234 assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
13235 assert_eq!(scheduler.pending_len(), 1);
13236 assert_eq!(
13237 obs.self_target_skipped.load(Ordering::Relaxed),
13238 1,
13239 "remote event must not count as a self-target skip"
13240 );
13241 }
13242
13243 #[test]
13244 fn fresh_offer_runs_store_admission_payment_checks() {
13245 let context = fresh_offer_payment_context();
13246 assert_eq!(context, VerificationContext::FreshReplication);
13247 // Fresh replication must keep verifying exactly like a direct client
13248 // PUT (store-strength cache, same live checks); the variant only
13249 // exists so price-floor telemetry can tell the two paths apart.
13250 assert!(context.is_store_admission());
13251 }
13252
13253 #[test]
13254 fn paid_notify_uses_paid_list_admission_payment_checks() {
13255 assert_eq!(
13256 paid_notify_payment_context(),
13257 VerificationContext::PaidListAdmission
13258 );
13259 }
13260
13261 /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
13262 /// signed quote inside the answerability window, fail-closed on BOTH ends so a
13263 /// stale or future/skewed client-forwarded quote cannot frame an honest node.
13264 #[test]
13265 fn monetized_quote_audit_window_fails_closed_both_ends() {
13266 let now = SystemTime::now();
13267 // Fresh (just quoted) and small future/past skew -> audited.
13268 assert!(quote_within_audit_window(now, now));
13269 assert!(quote_within_audit_window(now + Duration::from_mins(1), now));
13270 assert!(quote_within_audit_window(
13271 now - Duration::from_hours(1),
13272 now
13273 ));
13274 // Far future (badly-skewed / replayed) -> skipped.
13275 assert!(!quote_within_audit_window(
13276 now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_mins(1),
13277 now
13278 ));
13279 // Older than the window -> skipped (pin may have aged out).
13280 assert!(!quote_within_audit_window(
13281 now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
13282 now
13283 ));
13284 }
13285
13286 #[tokio::test]
13287 async fn replication_branch_lagged_events_are_counted() {
13288 let before = audit_metrics::replication_event_lagged_total();
13289 let flow = handle_replication_event_recv_error(
13290 &tokio::sync::broadcast::error::RecvError::Lagged(3),
13291 );
13292 assert_eq!(flow, std::ops::ControlFlow::Continue(()));
13293 let after = audit_metrics::replication_event_lagged_total();
13294 assert_eq!(after.saturating_sub(before), 3);
13295 }
13296
13297 #[tokio::test]
13298 async fn replication_branch_closed_events_stop_the_loop() {
13299 let flow =
13300 handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
13301 assert_eq!(flow, std::ops::ControlFlow::Break(()));
13302 }
13303
13304 #[tokio::test]
13305 async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
13306 let (sender, mut receiver) = mpsc::channel(1);
13307 let dropped_body =
13308 ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
13309 keys: Vec::new(),
13310 paid_list_check_indices: Vec::new(),
13311 });
13312 let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13313 let first = InboundReplicationMessage {
13314 source: test_peer(0xC1),
13315 msg: ReplicationMessage {
13316 request_id: 1,
13317 body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
13318 key: test_key(1),
13319 }),
13320 },
13321 rr_message_id: None,
13322 received_at: Instant::now(),
13323 };
13324 let second = InboundReplicationMessage {
13325 source: test_peer(0xC2),
13326 msg: ReplicationMessage {
13327 request_id: 2,
13328 body: dropped_body.clone(),
13329 },
13330 rr_message_id: None,
13331 received_at: Instant::now(),
13332 };
13333
13334 assert!(try_enqueue_serial_message(&sender, first).is_ok());
13335 let dropped = try_enqueue_serial_message(&sender, second)
13336 .expect_err("a full serial queue must refuse the second message");
13337 assert_eq!(dropped.reason, SerialQueueDropReason::Full);
13338 assert_eq!(dropped.message_class, "verification_request");
13339 assert_eq!(dropped.queue_depth, 1);
13340 let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13341 assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
13342
13343 let queued = receiver
13344 .recv()
13345 .await
13346 .expect("first message should remain queued");
13347 assert_eq!(queued.msg.request_id, 1);
13348 assert!(receiver.try_recv().is_err());
13349 }
13350
13351 #[tokio::test]
13352 async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
13353 let peer = test_peer(0x44);
13354 let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
13355
13356 let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
13357 let mut digest_guards = Vec::new();
13358 for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
13359 let guard = admit_audit_responder(
13360 &semaphore,
13361 &digest_inflight,
13362 &peer,
13363 AuditResponderClass::Digest,
13364 )
13365 .await;
13366 assert!(guard.is_ok());
13367 digest_guards.push(guard);
13368 }
13369 assert!(
13370 admit_audit_responder(
13371 &semaphore,
13372 &digest_inflight,
13373 &peer,
13374 AuditResponderClass::Digest,
13375 )
13376 .await
13377 .is_err(),
13378 "digest class must stop at its documented per-source cap"
13379 );
13380 drop(digest_guards);
13381
13382 let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
13383 let mut subtree_guards = Vec::new();
13384 for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
13385 let guard = admit_audit_responder(
13386 &semaphore,
13387 &subtree_inflight,
13388 &peer,
13389 AuditResponderClass::Subtree,
13390 )
13391 .await;
13392 assert!(guard.is_ok());
13393 subtree_guards.push(guard);
13394 }
13395 assert!(
13396 admit_audit_responder(
13397 &semaphore,
13398 &subtree_inflight,
13399 &peer,
13400 AuditResponderClass::Subtree,
13401 )
13402 .await
13403 .is_err(),
13404 "subtree class must retain the deployed cap of two"
13405 );
13406 drop(subtree_guards);
13407 }
13408
13409 #[test]
13410 fn in_scope_audit_deadlines_share_one_formula() {
13411 let config = config::ReplicationConfig::default();
13412 for key_count in [1, 4, 16] {
13413 assert_eq!(
13414 audit::responsible_audit_response_timeout(&config, key_count),
13415 config.audit_response_timeout(key_count)
13416 );
13417 assert_eq!(
13418 pruning::prune_audit_response_timeout(&config, key_count),
13419 config.audit_response_timeout(key_count)
13420 );
13421 }
13422 assert_eq!(
13423 possession::possession_probe_response_timeout(&config),
13424 config.audit_response_timeout(1)
13425 );
13426 }
13427
13428 #[test]
13429 fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
13430 const EXISTING_SOURCE_ID: u8 = 1;
13431 const HINT_SENDER_ID: u8 = 2;
13432
13433 let existing_source = test_peer(EXISTING_SOURCE_ID);
13434 let hint_sender = test_peer(HINT_SENDER_ID);
13435 let mut sources = vec![existing_source];
13436
13437 let hint_sources = HashSet::from([hint_sender]);
13438 add_replica_hint_sources(&mut sources, &hint_sources);
13439 add_replica_hint_sources(&mut sources, &hint_sources);
13440
13441 // A paid-only advertiser leaves the claim set empty (see
13442 // `queue_admitted_hints`), so it contributes no fetch source.
13443 add_replica_hint_sources(&mut sources, &HashSet::new());
13444
13445 assert_eq!(sources, vec![existing_source, hint_sender]);
13446 }
13447
13448 #[test]
13449 fn audit_timeout_preserves_active_bootstrap_claim() {
13450 assert!(!audit_failure_clears_bootstrap_claim(
13451 &AuditFailureReason::Timeout
13452 ));
13453 }
13454
13455 fn strike_peer(b: u8) -> PeerId {
13456 let mut bytes = [0u8; 32];
13457 bytes[0] = b;
13458 PeerId::from_bytes(bytes)
13459 }
13460
13461 // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
13462 // cooldown must collapse a gossip flood into at most one audit per window.
13463
13464 #[test]
13465 fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
13466 let peer = strike_peer(1);
13467 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13468 let t0 = Instant::now();
13469 // First gossip in the window passes; a burst of further gossips at the
13470 // same instant are all suppressed.
13471 assert!(cooldown_allows_audit(&mut map, &peer, t0));
13472 let mut passed = 1;
13473 for _ in 0..100 {
13474 if cooldown_allows_audit(&mut map, &peer, t0) {
13475 passed += 1;
13476 }
13477 }
13478 assert_eq!(
13479 passed, 1,
13480 "a flood at one instant must trigger exactly one audit"
13481 );
13482 }
13483
13484 // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
13485 // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
13486 // consumes the window. This is the property the isolated cooldown tests above
13487 // cannot see: they never sample the lottery, so a regression that reordered
13488 // the gates (sample probability first, only stamp the cooldown on a win)
13489 // would still pass them while breaking flood-resistance: a flood would then
13490 // re-roll the lottery on EVERY message until one won, multiplying audits.
13491 //
13492 // We model the exact production gate order (attempt-window, lottery,
13493 // shared cooldown) with a lottery driven by a fixed outcome instead of
13494 // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13495 // messages all WIN. With the production order, the losing first ticket
13496 // burns the ATTEMPT window and every later winner in the same window is
13497 // blocked, so there are 0 audits this window. If the gates were flipped,
13498 // the second message's winning ticket would slip through. The window only
13499 // reopens after it elapses.
13500 //
13501 // FLIPS IF: the lottery is sampled before the attempt-window
13502 // check-and-stamp (a losing ticket no longer consumes the window),
13503 // re-enabling a flood-amplified audit storm.
13504 #[test]
13505 fn losing_lottery_still_consumes_attempt_window() {
13506 // Calls the SHIPPED `audit_launch_decision` (the same function
13507 // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13508 // production fails this test — not a local reimplementation.
13509 let peer = strike_peer(3);
13510 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13511 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13512 let t0 = Instant::now();
13513
13514 // First flooded message at t0 LOSES the lottery, but the attempt window
13515 // is stamped BEFORE the lottery is consulted, so the window is consumed.
13516 assert!(
13517 !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13518 "a losing ticket launches no audit"
13519 );
13520
13521 // 99 more flooded messages at the same instant would all WIN the lottery,
13522 // yet every one must be blocked by the attempt window the loser stamped.
13523 // (If production sampled the lottery FIRST, these would each get a fresh
13524 // roll and audits would multiply — this assertion catches that reorder.)
13525 let mut audits = 0;
13526 for _ in 0..99 {
13527 if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13528 audits += 1;
13529 }
13530 }
13531 assert_eq!(
13532 audits, 0,
13533 "a losing first ticket must consume the attempt window so no later \
13534 flooded message in the same window can audit"
13535 );
13536
13537 // The window only reopens after it elapses; the next winning ticket
13538 // then launches exactly one audit and stamps the SHARED cooldown.
13539 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13540 assert!(
13541 audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13542 "after the window a winning ticket audits again"
13543 );
13544 assert!(
13545 launched.contains_key(&peer),
13546 "a real launch stamps the shared cooldown"
13547 );
13548 }
13549
13550 /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13551 /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13552 /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13553 /// first audit deferred until its answerability window expires.
13554 ///
13555 /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13556 /// loss (the pre-split behavior, where both paths shared one map).
13557 #[test]
13558 fn losing_lottery_does_not_suppress_monetized_first_audit() {
13559 let peer = strike_peer(4);
13560 let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13561 let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13562 let t0 = Instant::now();
13563
13564 // A losing ticket consumes the gossip attempt window...
13565 assert!(!audit_launch_decision(
13566 &mut attempts,
13567 &mut launched,
13568 &peer,
13569 t0,
13570 false
13571 ));
13572 // ...but leaves the shared map untouched, so the first-audit reserve
13573 // gate (read-only) and the authoritative promotion check-and-stamp both
13574 // still allow the paid audit to launch immediately.
13575 assert!(
13576 cooldown_would_allow(&launched, &peer, t0),
13577 "reserve gate must not see a losing ticket as audit coverage"
13578 );
13579 assert!(
13580 cooldown_allows_audit(&mut launched, &peer, t0),
13581 "promotion must not be deferred by a losing ticket"
13582 );
13583
13584 // Conversely a WINNING ticket (real audit sent) does suppress the
13585 // first audit for the window, which is the intended shared semantics.
13586 let peer_won = strike_peer(5);
13587 assert!(audit_launch_decision(
13588 &mut attempts,
13589 &mut launched,
13590 &peer_won,
13591 t0,
13592 true
13593 ));
13594 assert!(
13595 !cooldown_would_allow(&launched, &peer_won, t0),
13596 "a real gossip audit still covers the peer for the window"
13597 );
13598 }
13599
13600 #[test]
13601 fn cooldown_lets_audit_through_after_the_window() {
13602 let peer = strike_peer(2);
13603 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13604 let t0 = Instant::now();
13605 assert!(cooldown_allows_audit(&mut map, &peer, t0));
13606 // Within the window: suppressed.
13607 let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13608 assert!(!cooldown_allows_audit(&mut map, &peer, within));
13609 // Past the window: allowed again.
13610 let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13611 assert!(cooldown_allows_audit(&mut map, &peer, after));
13612 }
13613
13614 #[test]
13615 fn cooldown_is_per_peer_independent() {
13616 let mut map: HashMap<PeerId, Instant> = HashMap::new();
13617 let t0 = Instant::now();
13618 // Different peers each get their own first-audit pass at the same instant.
13619 for i in 0..20u8 {
13620 assert!(
13621 cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13622 "peer {i} should be auditable independently"
13623 );
13624 }
13625 }
13626
13627 #[test]
13628 fn audit_on_gossip_constants_match_adr() {
13629 // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13630 // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13631 // values above 5 would silently never be requested).
13632 assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13633 assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13634 assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13635 }
13636
13637 // (d) A confirmed storage-integrity failure penalizes immediately and
13638 // revokes credit; it is not a timeout.
13639 #[test]
13640 fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13641 assert!(audit_failure_clears_bootstrap_claim(
13642 &AuditFailureReason::DigestMismatch
13643 ));
13644 assert!(audit_failure_revokes_holder_credit(
13645 &AuditFailureReason::DigestMismatch
13646 ));
13647 }
13648
13649 /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13650 /// uses: confirmed failures revoke credit, `Timeout` does not.
13651 #[test]
13652 fn confirmed_failures_revoke_credit_timeout_does_not() {
13653 for reason in [
13654 AuditFailureReason::MalformedResponse,
13655 AuditFailureReason::DigestMismatch,
13656 AuditFailureReason::KeyAbsent,
13657 AuditFailureReason::Rejected,
13658 ] {
13659 assert!(
13660 audit_failure_revokes_holder_credit(&reason),
13661 "confirmed failure {reason:?} must revoke holder credit"
13662 );
13663 }
13664 assert!(
13665 !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13666 "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13667 );
13668 }
13669
13670 /// Wiring test for the security fix: the helper the handler calls
13671 /// actually strips a credited peer on a confirmed failure
13672 /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13673 /// Records genuine credit first so neither assertion is vacuous;
13674 /// this fails if `forget_peer` stops being called, or if the
13675 /// `Timeout` exclusion is dropped (both verified by mutation).
13676 #[test]
13677 fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13678 let peer = test_peer(0xAB);
13679 let key = test_key(1);
13680 let hash = [0xCD; 32];
13681
13682 // Confirmed failure -> credit revoked.
13683 let mut provers = RecentProvers::new();
13684 provers.record_proof(key, peer, hash, Instant::now());
13685 assert!(
13686 provers.is_credited_holder(&key, &peer, &hash),
13687 "precondition: peer credited before failure"
13688 );
13689 apply_audit_failure_credit_revocation(
13690 &mut provers,
13691 &peer,
13692 &AuditFailureReason::DigestMismatch,
13693 );
13694 assert!(
13695 !provers.is_credited_holder(&key, &peer, &hash),
13696 "DigestMismatch must strip the peer's holder credit"
13697 );
13698
13699 // Timeout -> credit retained.
13700 let mut provers_timeout = RecentProvers::new();
13701 provers_timeout.record_proof(key, peer, hash, Instant::now());
13702 apply_audit_failure_credit_revocation(
13703 &mut provers_timeout,
13704 &peer,
13705 &AuditFailureReason::Timeout,
13706 );
13707 assert!(
13708 provers_timeout.is_credited_holder(&key, &peer, &hash),
13709 "Timeout must retain holder credit (deliberate liveness cushion)"
13710 );
13711 }
13712
13713 #[test]
13714 fn decoded_audit_failures_clear_active_bootstrap_claim() {
13715 for reason in [
13716 AuditFailureReason::MalformedResponse,
13717 AuditFailureReason::DigestMismatch,
13718 AuditFailureReason::KeyAbsent,
13719 AuditFailureReason::Rejected,
13720 ] {
13721 assert!(
13722 audit_failure_clears_bootstrap_claim(&reason),
13723 "decoded non-bootstrap failure {reason:?} should clear active claim"
13724 );
13725 }
13726 }
13727
13728 #[test]
13729 fn first_failed_key_label_truncates_to_16_hex_chars() {
13730 // The high-order 8 bytes of the XorName determine the label so an
13731 // operator can group audit-failures on the same chunk prefix.
13732 let mut key = [0u8; 32];
13733 key[0] = 0x18;
13734 key[7] = 0xff;
13735 // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13736 // to verify they are NOT included in the label.
13737 for byte in &mut key[8..] {
13738 *byte = 0xAA;
13739 }
13740 let label = first_failed_key_label(&[key]);
13741 // Only the first 8 bytes are encoded, low-order bytes are dropped.
13742 assert_eq!(label, "0x18000000000000ff");
13743 assert_eq!(label.len(), "0x".len() + 16);
13744 }
13745
13746 #[test]
13747 fn first_failed_key_label_falls_back_when_empty() {
13748 // Should never happen in production (audit failure handling rejects
13749 // empty sets), but the formatter must still produce a valid label
13750 // so the log line doesn't contain a misleading default.
13751 assert_eq!(first_failed_key_label(&[]), "0x");
13752 }
13753
13754 #[test]
13755 fn first_failed_key_label_uses_first_key_only() {
13756 let first = [0x11u8; 32];
13757 let second = [0x22u8; 32];
13758 assert_eq!(
13759 first_failed_key_label(&[first, second]),
13760 format!("0x{}", hex::encode(&first[..8]))
13761 );
13762 }
13763
13764 // -- apply_fetch_result --------------------------------------------------
13765 //
13766 // The worker's disposition of a fetch outcome. Note there is no trust
13767 // handle in `apply_fetch_result`'s signature: the worker cannot report a
13768 // trust event for ANY outcome, and `execute_single_fetch` returns
13769 // `NoLongerResponsible` before its trust-reporting paths — the source did
13770 // nothing wrong when this node's own responsibility lapsed.
13771
13772 /// Route `key` through the real pipeline stages (pending → promoted →
13773 /// dequeued → in-flight) so it carries a verification retry-slot
13774 /// reservation, exactly as a worker-dequeued key does. Returns the
13775 /// in-flight source.
13776 fn drive_key_in_flight(
13777 q: &mut ReplicationQueues,
13778 key: XorName,
13779 sources: Vec<PeerId>,
13780 ) -> PeerId {
13781 let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13782 let now = Instant::now();
13783 let entry = VerificationEntry {
13784 state: VerificationState::PendingVerify,
13785 verified_sources: Vec::new(),
13786 tried_sources: HashSet::new(),
13787 created_at: now,
13788 next_verify_at: now,
13789 hint_sources: HashSet::from([hinter]),
13790 replica_hint_sources: HashSet::from([hinter]),
13791 unresolved_retries: 0,
13792 no_holder_reported: false,
13793 };
13794 assert!(q.add_pending_verify(key, entry).admitted());
13795 assert!(q.promote_pending_to_fetch(key, key, sources));
13796 let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13797 let source = *candidate.sources.first().expect("candidate has a source");
13798 q.start_dequeued_fetch(candidate, source);
13799 source
13800 }
13801
13802 #[test]
13803 fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13804 const RETRY_AFTER: Duration = Duration::from_mins(1);
13805
13806 let mut q = ReplicationQueues::new();
13807 let key = test_key(0xAB);
13808 drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13809 assert_eq!(q.retry_reserved_slot_count(), 1);
13810
13811 let follow_up =
13812 apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13813
13814 assert_eq!(
13815 follow_up,
13816 FetchFollowUp::Terminal,
13817 "lapsed responsibility must run the caller's terminal bootstrap accounting"
13818 );
13819 assert!(
13820 !q.contains_key(&key),
13821 "the key must leave every pipeline stage — alternate sources included"
13822 );
13823 assert_eq!(
13824 q.pending_count(),
13825 0,
13826 "a lapsed-responsibility key must not be requeued for verification"
13827 );
13828 assert_eq!(
13829 q.retry_reserved_slot_count(),
13830 0,
13831 "terminal exit must release the verification retry-slot reservation"
13832 );
13833 }
13834
13835 #[test]
13836 fn no_longer_responsible_shares_the_stored_terminal_path() {
13837 const RETRY_AFTER: Duration = Duration::from_mins(1);
13838
13839 // Both variants must walk the identical terminal gate so the
13840 // battle-tested Stored accounting (retry-slot release + bootstrap
13841 // pending-set shrink in the caller) covers lapsed responsibility too.
13842 for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13843 let mut q = ReplicationQueues::new();
13844 let key = test_key(0xCD);
13845 drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13846
13847 let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13848
13849 assert_eq!(follow_up, FetchFollowUp::Terminal);
13850 assert!(!q.contains_key(&key));
13851 assert_eq!(q.retry_reserved_slot_count(), 0);
13852 }
13853 }
13854
13855 #[test]
13856 fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13857 const RETRY_AFTER: Duration = Duration::from_mins(1);
13858
13859 let mut q = ReplicationQueues::new();
13860 let key = test_key(0xEF);
13861 let first = test_peer(0x04);
13862 let second = test_peer(0x05);
13863 drive_key_in_flight(&mut q, key, vec![first, second]);
13864
13865 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13866 assert_eq!(
13867 follow_up,
13868 FetchFollowUp::RetryFrom(second),
13869 "a failed source must not abandon the remaining verified sources"
13870 );
13871 assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13872
13873 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13874 assert_eq!(
13875 follow_up,
13876 FetchFollowUp::RequeuedForVerification,
13877 "exhausted sources must restore the reserved verification entry"
13878 );
13879 assert_eq!(q.pending_count(), 1);
13880 assert_eq!(
13881 q.retry_reserved_slot_count(),
13882 0,
13883 "the reservation converts back into the pending entry itself"
13884 );
13885 }
13886
13887 #[test]
13888 fn source_failure_without_retry_metadata_is_terminal() {
13889 const RETRY_AFTER: Duration = Duration::from_mins(1);
13890
13891 // Direct enqueue (no pending entry) models a fetch with no
13892 // verification retry reservation to restore.
13893 let mut q = ReplicationQueues::new();
13894 let key = test_key(0x1F);
13895 let source = test_peer(0x06);
13896 assert!(q.enqueue_fetch(key, key, vec![source]));
13897 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13898 q.start_dequeued_fetch(candidate, source);
13899
13900 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13901
13902 assert_eq!(follow_up, FetchFollowUp::Terminal);
13903 assert!(!q.contains_key(&key));
13904 }
13905
13906 #[test]
13907 fn already_held_key_leaves_the_pipeline_terminally() {
13908 const RETRY_AFTER: Duration = Duration::from_mins(1);
13909
13910 let mut q = ReplicationQueues::new();
13911 let key = test_key(0x4C);
13912 let source = test_peer(0x0B);
13913 drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13914
13915 let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13916
13917 assert_eq!(
13918 follow_up,
13919 FetchFollowUp::Terminal,
13920 "holding the key already discharges the duty, so the key must leave \
13921 the pipeline exactly as a completed fetch does — requeueing it \
13922 would re-verify a key that needs nothing"
13923 );
13924 assert!(!q.contains_key(&key));
13925 assert_eq!(
13926 q.retry_reserved_slot_count(),
13927 0,
13928 "the terminal path must release the retry-slot reservation, or the \
13929 owner's verification budget leaks"
13930 );
13931 }
13932
13933 #[test]
13934 fn local_write_failure_does_not_conscript_the_remaining_sources() {
13935 const RETRY_AFTER: Duration = Duration::from_mins(1);
13936
13937 let mut q = ReplicationQueues::new();
13938 let key = test_key(0x2A);
13939 let first = test_peer(0x07);
13940 let second = test_peer(0x08);
13941 let third = test_peer(0x09);
13942 drive_key_in_flight(&mut q, key, vec![first, second, third]);
13943
13944 let follow_up =
13945 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13946
13947 assert_eq!(
13948 follow_up,
13949 FetchFollowUp::RequeuedForVerification,
13950 "a local write failure must go straight back to verification: the two \
13951 untried sources would each re-upload the same chunk into the same \
13952 full disk, and neither of them did anything wrong"
13953 );
13954 assert_eq!(q.in_flight_count(), 0);
13955 assert_eq!(
13956 q.pending_count(),
13957 1,
13958 "the key must come back — capacity frees up, and a stranded key is \
13959 a replica this node silently stops owing"
13960 );
13961 assert_eq!(q.retry_reserved_slot_count(), 0);
13962 }
13963
13964 #[test]
13965 fn local_write_failure_without_retry_metadata_is_terminal() {
13966 const RETRY_AFTER: Duration = Duration::from_mins(1);
13967
13968 // No pending entry to restore, so the only way not to strand the key
13969 // in `in_flight_fetch` forever — which would also stall bootstrap
13970 // drain — is the terminal path.
13971 let mut q = ReplicationQueues::new();
13972 let key = test_key(0x3B);
13973 let source = test_peer(0x0A);
13974 assert!(q.enqueue_fetch(key, key, vec![source]));
13975 let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13976 q.start_dequeued_fetch(candidate, source);
13977
13978 let follow_up =
13979 apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13980
13981 assert_eq!(follow_up, FetchFollowUp::Terminal);
13982 assert!(!q.contains_key(&key));
13983 assert_eq!(q.retry_reserved_slot_count(), 0);
13984 }
13985}