ant_node/replication/config.rs
1//! Tunable parameters for the replication subsystem.
2//!
3//! All values below are a reference profile used for logic validation.
4//! Parameter safety constraints (Section 4):
5//! 1. `1 <= QUORUM_THRESHOLD <= CLOSE_GROUP_SIZE`
6//! 2. Effective paid-list threshold is per-key dynamic:
7//! `ConfirmNeeded(K) = floor(PaidGroupSize(K)/2)+1`
8//! 3. If constraints are violated at runtime reconfiguration, node MUST reject
9//! the config.
10
11#![allow(clippy::module_name_repetitions)]
12
13use std::time::Duration;
14
15use rand::Rng;
16
17use crate::ant_protocol::CLOSE_GROUP_SIZE;
18use crate::logging::{debug, info, warn};
19use saorsa_core::identity::PeerId;
20use saorsa_core::{P2PNode, TrustEvent};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::Arc;
23
24// ---------------------------------------------------------------------------
25// Static constants (compile-time reference profile)
26// ---------------------------------------------------------------------------
27
28/// Maximum number of peers per k-bucket in the Kademlia routing table.
29pub const K_BUCKET_SIZE: usize = 20;
30
31/// Extra local-routing-table positions accepted for local chunk storage
32/// admission and stored-record pruning.
33///
34/// This margin absorbs small local RT disagreement between peers. It does not
35/// widen audit, quorum, or paid-list target sets; those remain strict
36/// `close_group_size` / paid-list group checks.
37pub const STORAGE_ADMISSION_MARGIN: usize = 2;
38
39/// Full-network target for required positive presence votes.
40///
41/// Effective per-key threshold is
42/// `QuorumNeeded(K) = min(QUORUM_THRESHOLD, floor(|QuorumTargets|/2)+1)`.
43pub const QUORUM_THRESHOLD: usize = 4; // floor(CLOSE_GROUP_SIZE / 2) + 1
44
45/// Maximum number of closest nodes tracking paid status for a key.
46pub const PAID_LIST_CLOSE_GROUP_SIZE: usize = 20;
47
48/// Maximum number of furthest paid-list close-group peers treated as churny
49/// edge voters.
50///
51/// Once the paid-list close group reaches [`PAID_LIST_CLOSE_GROUP_SIZE`], edge
52/// peers are queried, but a negative edge paid-list response does not count
53/// into the paid-list majority denominator. A positive edge response does
54/// count. This absorbs local routing-table disagreement at the boundary of the
55/// paid close group. Undersized groups keep their ordinary strict majority.
56///
57/// This is a **ceiling**, not a fixed width: the effective edge is scaled to
58/// the group by [`ReplicationConfig::paid_list_flex_edge_count`] so the discount stays
59/// proportionate. A fixed four peers is a fifth of the production width but
60/// would be four fifths of a configured width of five, collapsing the voting
61/// core to a single peer.
62pub const PAID_LIST_FLEX_EDGE_COUNT: usize = 4;
63
64/// Divisor fixing the edge as a proportion of the paid close group.
65///
66/// Five gives the production ratio: 20 / 5 = 4 edge voters, matching
67/// [`PAID_LIST_FLEX_EDGE_COUNT`] exactly, so default behaviour is unchanged.
68const PAID_LIST_FLEX_EDGE_DIVISOR: usize = 5;
69
70/// Minimum `Confirmed` paid-list votes required to authorize a key, whatever
71/// the flexible edge does to the denominator.
72///
73/// The edge discount shrinks the denominator, and with it the majority
74/// threshold. Without an absolute floor a sufficiently small or sufficiently
75/// silent group authorizes on a single confirmation — and `PaidListVerified`
76/// writes the paid list and enables repair fetches, so that is the gate
77/// deciding what a node fetches and retains. Three independent confirmations
78/// keeps a lone voter (honest or not) from being decisive; groups genuinely
79/// smaller than this fall back to their strict majority via the `min` in
80/// [`ReplicationConfig::paid_confirm_needed`], since a floor above the group
81/// size would make authorization impossible rather than merely strict.
82pub const PAID_LIST_ABSOLUTE_CONFIRM_FLOOR: usize = 3;
83
84/// Number of closest peers to self eligible for neighbor sync.
85pub const NEIGHBOR_SYNC_SCOPE: usize = 20;
86
87/// Number of close-neighbor peers synced concurrently per round-robin repair
88/// round.
89pub const NEIGHBOR_SYNC_PEER_COUNT: usize = 4;
90
91/// Best-effort delivery retries for a fresh-replication push, per peer.
92///
93/// ADR-0003: on a transport/send failure the offer is retried up to this many
94/// times so a transient hiccup does not silently drop it. This is delivery
95/// assurance only — possession is judged separately by the delayed possession
96/// check, which still penalises a close peer that lacks the chunk even if the
97/// push never reached it.
98pub const FRESH_REPLICATION_DELIVERY_MAX_RETRIES: u32 = 2;
99
100const POSSESSION_CHECK_DELAY_MIN_SECS: u64 = 5 * 60;
101const POSSESSION_CHECK_DELAY_MAX_SECS: u64 = 15 * 60;
102
103/// Lower bound of the delay before a fresh-replication possession check runs
104/// (ADR-0003).
105///
106/// The delay lets replication settle so an honest peer still mid-store is not
107/// judged prematurely, and makes the check unpredictable to the peer.
108pub const POSSESSION_CHECK_DELAY_MIN: Duration =
109 Duration::from_secs(POSSESSION_CHECK_DELAY_MIN_SECS);
110
111/// Upper bound of the possession-check delay (ADR-0003).
112pub const POSSESSION_CHECK_DELAY_MAX: Duration =
113 Duration::from_secs(POSSESSION_CHECK_DELAY_MAX_SECS);
114
115// The possession probe reuses the `AuditChallenge` wire and the bandwidth-
116// calibrated `audit_response_timeout(1)` deadline, so it needs no bespoke
117// per-probe timeout or retry constants.
118
119/// Width used when deciding whether this node may locally store or retain a
120/// chunk.
121#[must_use]
122pub const fn storage_admission_width(close_group_size: usize) -> usize {
123 close_group_size.saturating_add(STORAGE_ADMISSION_MARGIN)
124}
125
126/// Minimum neighbor-sync cadence. Actual interval is randomized within
127/// `[min, max]`.
128const NEIGHBOR_SYNC_INTERVAL_MIN_SECS: u64 = 10 * 60;
129/// Maximum neighbor-sync cadence.
130const NEIGHBOR_SYNC_INTERVAL_MAX_SECS: u64 = 20 * 60;
131
132/// Neighbor sync cadence range (min).
133pub const NEIGHBOR_SYNC_INTERVAL_MIN: Duration =
134 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MIN_SECS);
135
136/// Neighbor sync cadence range (max).
137pub const NEIGHBOR_SYNC_INTERVAL_MAX: Duration =
138 Duration::from_secs(NEIGHBOR_SYNC_INTERVAL_MAX_SECS);
139
140/// Per-peer minimum spacing between successive syncs with the same peer.
141const NEIGHBOR_SYNC_COOLDOWN_SECS: u64 = 60 * 60; // 1 hour
142/// Per-peer minimum spacing between successive syncs with the same peer.
143pub const NEIGHBOR_SYNC_COOLDOWN: Duration = Duration::from_secs(NEIGHBOR_SYNC_COOLDOWN_SECS);
144
145/// Minimum age for a replica repair hint before the hinted peer can be audited
146/// for that key.
147const REPAIR_HINT_MIN_AGE_SECS: u64 = 60 * 60; // 1 hour
148/// Minimum age for a replica repair hint before the hinted peer can be audited
149/// for that key.
150pub const REPAIR_HINT_MIN_AGE: Duration = Duration::from_secs(REPAIR_HINT_MIN_AGE_SECS);
151
152/// Minimum self-lookup cadence.
153const SELF_LOOKUP_INTERVAL_MIN_SECS: u64 = 5 * 60;
154/// Maximum self-lookup cadence.
155const SELF_LOOKUP_INTERVAL_MAX_SECS: u64 = 10 * 60;
156
157/// Periodic self-lookup cadence range (min) to keep close neighborhood
158/// current.
159pub const SELF_LOOKUP_INTERVAL_MIN: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MIN_SECS);
160
161/// Periodic self-lookup cadence range (max).
162pub const SELF_LOOKUP_INTERVAL_MAX: Duration = Duration::from_secs(SELF_LOOKUP_INTERVAL_MAX_SECS);
163
164/// Maximum number of concurrent outbound replication sends.
165///
166/// Caps how many fresh-replication chunk transfers can be in-flight at once
167/// across the entire replication engine. Prevents bandwidth saturation on
168/// home broadband connections when multiple chunks arrive simultaneously.
169/// Each send transfers up to 4 MB (`MAX_CHUNK_SIZE`), so a limit of 3 means
170/// at most ~12 MB queued for the upload link at any instant.
171pub const MAX_CONCURRENT_REPLICATION_SENDS: usize = 3;
172
173/// Maximum number of encoded fresh-replication offers held in memory.
174///
175/// Each accepted write is encoded once (chunk plus proof, up to ~4 MB) and
176/// that buffer stays alive until the last of its per-peer sends completes.
177/// With only `MAX_CONCURRENT_REPLICATION_SENDS` transfers in flight, a write
178/// rate above the network's send rate would otherwise queue an unbounded
179/// number of encoded offers behind the send permits. The offer dispatcher
180/// takes one of these permits before it reads and encodes a chunk, so the
181/// backlog waits as small queued events instead of chunk-sized buffers.
182pub const MAX_PENDING_FRESH_OFFERS: usize = 8;
183
184/// How many times the offer dispatcher tries to read an accepted chunk back
185/// from storage before giving up on its fresh offers.
186///
187/// The chunk was stored moments earlier, so a failed read is a transient
188/// fault (exhausted descriptors, an I/O hiccup) far more often than a lost
189/// chunk, and such a fault is usually store-wide: every queued write fails
190/// at once. The retries back off (see [`fresh_read_retry_delay`]), so these
191/// attempts span about a minute and a fault shorter than that costs no
192/// offers. A lost chunk reports `None` and is skipped without retry.
193pub const MAX_FRESH_READ_ATTEMPTS: u32 = 7;
194
195/// Pause before the first retry of a failed chunk read-back in the offer
196/// dispatcher; each later retry waits [`FRESH_READ_RETRY_BACKOFF_FACTOR`]
197/// times longer than the one before.
198pub const FRESH_READ_RETRY_DELAY: Duration = Duration::from_secs(1);
199
200/// Growth of the pause between successive read-back retries.
201pub const FRESH_READ_RETRY_BACKOFF_FACTOR: u32 = 2;
202
203/// Pause before retrying a read-back that has failed `failed_attempts` times.
204///
205/// [`FRESH_READ_RETRY_DELAY`], grown by [`FRESH_READ_RETRY_BACKOFF_FACTOR`]
206/// per earlier failure. With [`MAX_FRESH_READ_ATTEMPTS`] the retries come 1,
207/// 2, 4, 8, 16 and 32 seconds apart.
208#[must_use]
209pub fn fresh_read_retry_delay(failed_attempts: u32) -> Duration {
210 let growth = FRESH_READ_RETRY_BACKOFF_FACTOR.saturating_pow(failed_attempts.saturating_sub(1));
211 FRESH_READ_RETRY_DELAY.saturating_mul(growth)
212}
213
214/// Maximum number of concurrent in-flight audit-responder tasks.
215///
216/// The LIGHT audit-responder handlers — responsible-chunk audits and subtree
217/// slice (round 2) — are spawned off the serial replication message loop so their
218/// disk reads don't stall replication. (The HEAVY subtree round 1 has its own
219/// tighter pool, [`MAX_CONCURRENT_SUBTREE_ROUND1`].) This caps how many run at once
220/// across the engine, restoring backpressure: a peer flooding audit challenges
221/// cannot fan out unbounded `get_raw` reads. When the cap is hit, the challenge
222/// is dropped and the caller's audit-specific timeout policy applies. The cap
223/// must therefore stay high enough for honest audit traffic while still
224/// throttling flooders.
225/// Sized to cover a handful of concurrent honest auditors (the per-peer
226/// gossip-audit cooldown is 30 min, so genuine concurrent audits are few) while
227/// bounding the round-2 worst-case disk reads (each request reads at most
228/// `BYTE_SPOTCHECK_MAX` distinct chunks — the openings are coalesced and the
229/// distinct-key count is capped — to build its slice proofs).
230pub const MAX_CONCURRENT_AUDIT_RESPONSES: usize = 32;
231
232/// Maximum concurrent in-flight audit-responder tasks from any SINGLE peer.
233///
234/// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] ceiling alone is not
235/// flood-fair: one peer spamming challenges could occupy every slot and starve
236/// honest auditors (whose dropped challenges convert to audit failures or
237/// timeout verdicts on the challenged peers). This per-peer cap guarantees no
238/// source holds more than its share, so a flood self-throttles. Audits are
239/// cooldown-gated (one
240/// gossip-triggered audit per peer per 30 min), so 4 in-flight per peer leaves
241/// headroom beyond the legitimate round-1 + round-2 overlap.
242pub const MAX_AUDIT_RESPONSES_PER_PEER: u32 = 4;
243
244/// Maximum concurrent digest-only `AuditChallenge` responses from any single
245/// source peer.
246///
247/// Digest challenges are KB-scale replies: at most
248/// `max_incoming_audit_keys(stored_chunks)` bounded disk reads plus BLAKE3
249/// digests. A higher per-source allowance absorbs the three legitimate issuer
250/// subsystems (responsible-chunk audit, prune confirmation, and possession
251/// checks) from one auditor without weakening the existing subtree/byte audit
252/// budget. The multi-MiB subtree and byte challenge paths intentionally keep
253/// [`MAX_AUDIT_RESPONSES_PER_PEER`] exactly unchanged.
254pub const MAX_DIGEST_AUDIT_RESPONSES_PER_PEER: u32 = 8;
255
256/// Cadence of audit-responder capacity and slow-processing summaries.
257///
258/// Each window is reset after logging, so the ranked origins describe current
259/// testnet load rather than being permanently dominated by an old burst.
260pub const AUDIT_RESPONDER_SUMMARY_INTERVAL: Duration = Duration::from_mins(1);
261
262/// Number of busiest source peers included in each responder summary window.
263pub const AUDIT_RESPONDER_TOP_ORIGINS: usize = 10;
264
265/// Dedicated global concurrency cap for the HEAVY subtree-audit round 1.
266///
267/// Round 1 hashes every leaf of the selected `sqrt(key_count)` subtree (up to
268/// ~1000 chunks × `MAX_CHUNK_SIZE` for a maximal commitment), far heavier than a
269/// responsible-chunk or slice (round-2) response. Giving it its own tiny pool —
270/// rather than sharing [`MAX_CONCURRENT_AUDIT_RESPONSES`] — keeps a burst of
271/// round-1 proofs from starving the light audits, and bounds concurrent
272/// multi-gigabyte hashing to this many at once. Two allows overlap without
273/// admitting many simultaneous full-subtree hashes; there is little benefit in
274/// more concurrent large LMDB scans against one disk.
275pub const MAX_CONCURRENT_SUBTREE_ROUND1: usize = 2;
276
277/// Per-peer concurrency cap for the heavy subtree-audit round 1. One in-flight
278/// round-1 proof per source at a time (an honest auditor never needs more).
279pub const MAX_SUBTREE_ROUND1_PER_PEER: u32 = 1;
280
281/// Per-peer responder-side cooldown between heavy subtree round-1 proofs.
282///
283/// An honest auditor already self-limits to one gossip-triggered subtree audit
284/// per peer per 30 min, so matching that as a responder-side floor costs honest
285/// traffic nothing while bounding the sustained round-1 work a single identity
286/// can extract (a concurrency cap alone lets a peer refill its slot forever).
287pub const SUBTREE_ROUND1_RESPONDER_COOLDOWN: Duration = Duration::from_mins(30);
288
289/// Lifetime of a single-use round-1 → round-2 session.
290///
291/// A round-2 slice challenge is only served if the same peer completed a matching
292/// round 1 within this window. Long enough for the auditor to verify round 1 and
293/// send round 2, far shorter than commitment retention; ephemeral, so a loss
294/// across a restart just
295/// drops that round to the (graced) timeout lane.
296pub const SUBTREE_SESSION_TTL: Duration = Duration::from_mins(2);
297
298/// Capacity backstop on the live round-1 session map (bounds memory if many
299/// peers open sessions; oldest are evicted past this).
300pub const MAX_SUBTREE_SESSIONS: usize = 4 * MAX_CONCURRENT_SUBTREE_ROUND1 * 256;
301
302/// Most pointer bindings every live round-1 session holds together
303/// (ADR-0019): 4 MiB of keys and roots at the cap, before the maps' own
304/// overhead.
305///
306/// A session keeps one per pointer its round 1 proved, and a round-1 subtree
307/// can hold about a thousand leaves, so [`MAX_SUBTREE_SESSIONS`] full sessions
308/// would otherwise hold two million. A round 1 whose bindings would not fit
309/// withholds its proof and answers `Transient`, and no session already
310/// answered gives its bindings up.
311pub const MAX_SESSION_POINTER_BINDINGS: usize = 1 << 16;
312
313/// Sustained rate at which the responder-wide round-1 work budget refills, in
314/// bytes of chunk content per second.
315///
316/// [`MAX_CONCURRENT_SUBTREE_ROUND1`] bounds how many round-1 proofs run at once
317/// and [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] bounds how often one peer id may
318/// ask, but neither bounds sustained work: the cooldown is keyed by identity, so
319/// a party holding several identities refills its allowance by rotating between
320/// them and keeps the small pool permanently busy. This budget is keyed by
321/// nothing at all — it is charged for the bytes read and hashed no matter who
322/// asked — so identity count cannot buy more of it.
323///
324/// Sized to clear honest demand even at the worst commitment size, since
325/// starving honest audits would cost more than it saves. The 990-node run
326/// served about 24 audits per node per hour. At the `MAX_COMMITMENT_KEY_COUNT`
327/// cap one proof reads close to 4 GiB, so honest demand there is ~96 GiB/h,
328/// against the 225 GiB/h this allows — and a flooder is held to about twice
329/// honest load rather than to whatever the disk will bear. For the far more
330/// common mid-sized commitment, where a proof reads a few hundred MiB, the
331/// headroom is more than an order of magnitude.
332///
333/// Signed because the budget it refills carries debt when a proof costs more
334/// than is left.
335pub const SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC: i64 = 64 * 1024 * 1024;
336
337/// Burst capacity of the round-1 work budget, in bytes of chunk content.
338///
339/// Also its starting fill, so a freshly started node can serve audits at once.
340/// Two maximal proofs' worth, matching [`MAX_CONCURRENT_SUBTREE_ROUND1`], so a
341/// legitimate burst is never refused for arriving together — the budget limits
342/// the sustained rate, which is what a concurrency cap cannot do.
343pub const SUBTREE_ROUND1_WORK_BURST_BYTES: i64 = 8 * 1024 * 1024 * 1024;
344
345/// Floor charged against the round-1 work budget per leaf attempted, in bytes.
346///
347/// The budget counts content bytes, which is the right unit for the hashing but
348/// misses what a leaf costs before its size is known: an LMDB point lookup with
349/// its retries, and a `spawn_blocking` dispatch and join. Nothing bounds a
350/// chunk from below, so a commitment made of a million tiny records would run a
351/// full subtree of reads and task round-trips per audit while charging almost
352/// nothing, and a leaf that fails to read charged nothing at all. Since the
353/// per-peer cooldown is escapable by rotating identity, the budget is the only
354/// bound that applies, so it has to see that cost.
355///
356/// Charged at the attempt, then topped up by whatever the content exceeds it
357/// by, so a leaf costs `max(bytes, this)`. At 4 KiB an honest chunk is almost
358/// always above it and pays exactly its bytes, which leaves the sizing of the
359/// refill rate above unchanged.
360pub const SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES: i64 = 4 * 1024;
361
362/// Concurrent fetches cap, derived from hardware thread count.
363///
364/// Uses `std::thread::available_parallelism()` so the node scales to the
365/// machine it runs on. Falls back to 4 if the OS query fails.
366const AVAILABLE_PARALLELISM_FALLBACK: usize = 4;
367
368/// Returns the number of hardware threads available, used as the fetch
369/// concurrency limit.
370#[allow(clippy::incompatible_msrv)] // NonZero::get is stable since 1.79; MSRV lint conflicts with redundant_closure
371pub fn max_parallel_fetch() -> usize {
372 std::thread::available_parallelism()
373 .map_or(AVAILABLE_PARALLELISM_FALLBACK, std::num::NonZero::get)
374}
375
376/// Minimum audit-scheduler cadence.
377const AUDIT_TICK_INTERVAL_MIN_SECS: u64 = 10 * 60;
378/// Maximum audit-scheduler cadence.
379const AUDIT_TICK_INTERVAL_MAX_SECS: u64 = 20 * 60;
380
381/// Audit scheduler cadence range (min).
382pub const AUDIT_TICK_INTERVAL_MIN: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MIN_SECS);
383
384/// Audit scheduler cadence range (max).
385pub const AUDIT_TICK_INTERVAL_MAX: Duration = Duration::from_secs(AUDIT_TICK_INTERVAL_MAX_SECS);
386
387/// Floor on the audit response deadline (independent of challenge size).
388///
389/// Sized to absorb worst-case global RTT for the audit envelope
390/// (the request + response messages are KB-scale, not chunk-scale)
391/// plus scheduling jitter. Tokyo↔NY round-trip is ~150ms each way,
392/// so 4 seconds comfortably covers cross-continent communication
393/// for the round-1 proof, whose payload is hashes (KB-scale).
394const AUDIT_RESPONSE_FLOOR_SECS: u64 = 4;
395
396/// Floor on the round-2 SLICE-challenge deadline.
397///
398/// The round-2 reply is only a few KB per opening (a 1 KiB block plus two short
399/// hash chains), but an honest responder still reads each opened chunk's full
400/// bytes from disk to build its Bao slice and nonced opening, so the floor must
401/// cover a cold QUIC handshake plus a busy honest peer's full-chunk disk read.
402/// The round-1 4 s floor is sized for a hashes-only reply; round 2 keeps a
403/// slightly larger 5 s base for the disk-read envelope, with the per-byte scaled
404/// term (one full chunk per opening) added on top.
405const BYTE_AUDIT_RESPONSE_FLOOR_SECS: u64 = 5;
406
407/// Conservative honest-responder read throughput, in bytes per second.
408///
409/// Used to size the audit response deadline. An honest peer answers
410/// a k-key challenge by reading k chunks from local disk, computing
411/// BLAKE3 + path proofs, and signing the response. The bottleneck is
412/// disk read; BLAKE3 at ~3 GB/s + ML-DSA signing at ~3 ms are
413/// negligible.
414///
415/// Set conservatively below any modern SSD (typical: 500 MB/s+).
416/// At 50 MB/s, a k=10 sample at 4 MiB chunks reads in ~0.8s, well
417/// inside even an aggressive timeout. A relay attacker who must
418/// fetch the same 40 MB over the network at typical bandwidth
419/// (100 Mbps = 12.5 MB/s) takes 3+ seconds for the data alone, plus
420/// per-chunk network round-trips. At larger sample sizes the gap
421/// is exponential in the relay's disadvantage.
422const AUDIT_HONEST_READ_BPS: u64 = 50 * 1024 * 1024;
423
424/// Slack multiplier on the honest-read estimate.
425///
426/// Set so an honest peer that's slower than `HONEST_READ_BPS` (e.g. an
427/// HDD-backed node, or one under load) still answers within the
428/// timeout. 5× is generous; a relay peer fetching the same data over a
429/// residential link (~5-12 MB/s) sees ~10-100× higher latency than disk
430/// and misses the budget. This is an economic deterrent calibrated for
431/// residential bandwidth, NOT a hard cryptographic bound — a relay on a
432/// datacenter cross-connect could still fetch fast enough to answer in
433/// time (see the §7 note on `audit_response_timeout`).
434const AUDIT_RESPONSE_HONEST_MULTIPLIER: u64 = 5;
435
436/// Maximum duration a peer may claim bootstrap status before penalties apply.
437const BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS: u64 = 24 * 60 * 60; // 24 h
438/// Maximum duration a peer may claim bootstrap status before penalties apply.
439pub const BOOTSTRAP_CLAIM_GRACE_PERIOD: Duration =
440 Duration::from_secs(BOOTSTRAP_CLAIM_GRACE_PERIOD_SECS);
441
442/// Minimum continuous out-of-range duration before pruning a key.
443const PRUNE_HYSTERESIS_DURATION_SECS: u64 = 3 * 24 * 60 * 60; // 3 days
444/// Minimum continuous out-of-range duration before pruning a key.
445pub const PRUNE_HYSTERESIS_DURATION: Duration = Duration::from_secs(PRUNE_HYSTERESIS_DURATION_SECS);
446
447/// Protocol identifier for core replication operations, including the
448/// digest-based responsible-chunk, possession, and prune-confirmation audits.
449///
450/// Kept at `v2`: the V2-685 work changes only the subtree-audit wire family.
451/// Fresh replication, neighbour sync, fetch, repair, verification, and the
452/// digest-based audit lanes therefore continue interoperating on this id. A node
453/// filters inbound messages by exact topic match (see the dispatch in `mod.rs`).
454pub const REPLICATION_PROTOCOL_ID: &str = "autonomi.ant.replication.v2";
455
456/// Protocol identifier for the subtree storage-commitment audit (ADR-0002 /
457/// V2-685), both rounds: `SubtreeAuditChallenge`/`Response` (round 1) and
458/// `SubtreeSliceChallenge`/`Response` (round 2).
459///
460/// These are the only replication messages whose wire format changed for the
461/// slice audit (round 1's `SubtreeLeaf` now carries `content_len` + `nonced_root`
462/// instead of a flat `nonced_hash`; round 2 replaced full-byte responses with Bao
463/// verified slices). Routing them on their own id — instead of bumping the whole
464/// [`REPLICATION_PROTOCOL_ID`] — means a mixed-version fleet keeps doing fresh
465/// replication, neighbour sync, fetch and repair across versions; only
466/// cross-version subtree *audits* pause during the ~24 h auto-upgrade window.
467///
468/// Rollout effect is bounded, not zero: `saorsa-core`'s `send_request` records a
469/// unit trust failure on any unanswered request (before ant-node's graced-timeout
470/// policy), so a v3 auditor's subtree challenge to a still-v2 peer (and the
471/// reverse, where a v2 subtree audit is dropped by the id/body guard) each ding
472/// that peer's EMA trust once per 30-minute audit cooldown. Trust decays back to
473/// neutral (a worst-case dip recovers above the 0.35 routing-swap threshold in
474/// ~1 online day, and a successful audit after upgrade adds a unit success), and
475/// crossing 0.35 only makes a peer replaceable in a full bucket — it does not
476/// delete data or ban the peer. This is strictly milder than bumping the shared
477/// id, which would fail every cross-version request path (sync/quorum/prune/
478/// possession/repair/commitment-fetch) with no per-peer limiter. A truly
479/// zero-penalty rollout needs an upstream `send_request` that does not
480/// auto-report trust; tracked as a saorsa-core follow-up.
481///
482/// `v2` (ADR-0016): commitments carry pointer leaves, committed as
483/// `(address, pointer_leaf_hash(address))`, and round 2 answers one with the
484/// whole signed record. A `v1` auditor would reject a pointer leaf in round 1
485/// as a content-address mismatch and penalise an honest holder, so the two
486/// versions must not audit each other: the same bounded pause as the `v1`
487/// introduction, for the same reason.
488pub const SUBTREE_AUDIT_PROTOCOL_ID: &str = "autonomi.ant.replication.subtree-audit.v2";
489
490/// 10 MiB — maximum replication wire message size (accommodates hint batches).
491const REPLICATION_MESSAGE_SIZE_MIB: usize = 10;
492/// Maximum replication wire message size.
493pub const MAX_REPLICATION_MESSAGE_SIZE: usize = REPLICATION_MESSAGE_SIZE_MIB * 1024 * 1024;
494
495/// Maximum wire size for a message in the subtree-audit protocol family.
496///
497/// The 10 MiB core ceiling is sized for hint batches, which no subtree-audit
498/// body carries. Applying it to the subtree family would let a peer make this node
499/// allocate and decode megabytes of attacker-shaped collection before any
500/// family, session or admission check has run — those checks all read fields of
501/// the decoded body, so they cannot come first. Checking the encoded length
502/// against a family-appropriate ceiling can, because it needs nothing but the
503/// byte count.
504///
505/// Sized against the largest legitimate audit body, the round-1
506/// `SubtreeAuditResponse::Proof`: at the `MAX_COMMITMENT_KEY_COUNT` cap a
507/// subtree is at most 1,024 leaves of ~100 bytes each, plus the sibling cut
508/// hashes and the signed commitment, so ~110 KiB. Every other subtree body is
509/// far smaller. This leaves roughly
510/// 4x headroom over the worst legitimate case while cutting the pre-admission
511/// allocation ceiling by a factor of 20.
512pub const MAX_SUBTREE_AUDIT_MESSAGE_SIZE: usize = 512 * 1024;
513const _: () = assert!(
514 MAX_SUBTREE_AUDIT_MESSAGE_SIZE < MAX_REPLICATION_MESSAGE_SIZE,
515 "the subtree-audit ceiling must be tighter than the core one, or it is pointless"
516);
517
518/// Maximum block openings per round-2 [`SubtreeSliceChallenge`].
519///
520/// Each opening is a Bao verified slice (a 1 KiB block plus O(log n) BLAKE3
521/// parent hashes) plus a nonced block-tree sibling chain — a few KB, so even
522/// this many openings encode far under [`MAX_REPLICATION_MESSAGE_SIZE`] with no
523/// batching. The auditor draws up to *two* openings per sampled leaf — one
524/// fresh-random block (possession) and one at the claimed final block (a length
525/// pin: opening the final block forces Bao's EOF validation, which authenticates
526/// the true content length and defeats a forged-short `content_len` that would
527/// otherwise shrink the challenge space). With at most `BYTE_SPOTCHECK_MAX`
528/// leaves that is `2 × BYTE_SPOTCHECK_MAX` openings; this cap sits just above
529/// that, and the responder rejects any challenge requesting more (a forged-
530/// auditor guard: each opening forces one full chunk read to build its proof).
531///
532/// [`SubtreeSliceChallenge`]: crate::replication::protocol::SubtreeSliceChallenge
533pub const MAX_SLICE_OPENINGS: usize = 10;
534const _: () = assert!(
535 MAX_SLICE_OPENINGS >= 1,
536 "at least one block opening must be allowed per slice challenge"
537);
538
539/// Rollout gate for ADR-0004 quote-arithmetic enforcement.
540///
541/// When `true`, the payment verifier rejects any quote whose signed price does
542/// not lie exactly on the public pricing curve, i.e. there is no integer
543/// `key_count` for which `calculate_price(key_count) == quote.price`. The check
544/// is exact recomputation against the curve, never price-inversion (which
545/// rounds), per ADR-0004's "never by inverting the price" rule.
546///
547/// When `false`, the check still runs and logs every would-be rejection, but
548/// does not reject — matching the ADR-0004 rollout: ship observe-only first,
549/// enforce only once the fleet has upgraded. Off-curve quotes are honest
550/// errors, not signs of an old node (every honest implementation derives its
551/// price from the same public formula), so flipping this to `true` does not
552/// risk evicting un-upgraded peers; it only catches modified nodes that minted
553/// prices off the curve.
554///
555/// This is a reject-only gate: an off-curve quote produces no trust evidence
556/// and no audit, per ADR-0004 ("an off-curve quote is reject-only"). It does
557/// NOT gate the quote/commitment mismatch trust report — see
558/// [`QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED`] for that, kept separate because
559/// the two have different ADR-0004 contracts (this one rejects with no trust
560/// action; that one reports a deterministic contradiction to the trust engine).
561///
562/// Enabled after the observe-only canary came back clean on ant-prod-01. Over
563/// the 2026-07-29 to 2026-08-04 window the check ran against every quote in
564/// more than 70,000 verified bundles across 912 of 913 node instances and
565/// flagged nothing: no off-curve price, no invalid binding shape, no
566/// price/count mismatch. Honest traffic therefore sits exactly on the curve, so
567/// enforcing rejects nothing that is accepted today.
568pub const QUOTE_ARITHMETIC_RECHECK_ENABLED: bool = true;
569
570/// Rollout gate for ADR-0004 quote/commitment **mismatch** trust reporting.
571///
572/// When a client-put quote's signed `committed_key_count` contradicts the
573/// `key_count` of the commitment it pinned (resolved from the gossip cache, a
574/// sidecar, or a fetch), that is two artifacts signed by the same key that
575/// contradict each other — a deterministic, first-occurrence misbehaviour. When
576/// `true`, the cross-check reports it to the trust engine as an
577/// `ApplicationFailure` (the same lane as a confirmed deterministic audit
578/// failure, NOT the timeout silence lane). When `false`, the cross-check only
579/// logs the would-be report (observe-only).
580///
581/// Kept independent of [`QUOTE_ARITHMETIC_RECHECK_ENABLED`] (which is
582/// reject-only with no trust action): a confirmed mismatch is not a mere
583/// off-curve price, so it deserves its own dial.
584pub const QUOTE_COMMITMENT_MISMATCH_TRUST_ENABLED: bool = false;
585
586/// Instant from which a merkle batch payment must carry the same 3x settlement
587/// multiplier the single-node path has always applied (ADR-0008). Unix seconds.
588///
589/// The single-node path settles a chunk at 3x the median quoted price. The
590/// merkle path submitted the bare quoted price as the on-chain payable amount,
591/// so the contract's `median16(amount) x 2^depth` came to 1x the median per
592/// padded leaf: the same chunk, stored and replicated identically, earned a
593/// third as much when it arrived in a batch.
594///
595/// **The rollout is client-first, and this constant is only its second half.**
596/// ant-client (ant-client#161) pays 3x immediately and unconditionally once
597/// released — no date, no flag — and un-upgraded nodes accept that, because 3x
598/// clears the 1x minimum they require. So the network is paid correctly from
599/// the moment the client ships. This instant is when upgraded nodes stop
600/// accepting anything less.
601///
602/// **Enforcement is on by default.** There is no shadow mode and no flag to
603/// flip later: a receipt stamped at or after this instant must settle at 3x or
604/// the store is refused. What the boundary buys is not a soft launch, it is
605/// compatibility with money that was already spent:
606///
607/// - A receipt stamped **before** the boundary is held to the historic 1x. It
608/// was paid in good faith under the old rule and the payer cannot get it
609/// back, so refusing it would destroy value rather than protect it.
610/// - Merkle receipts expire after `MERKLE_PAYMENT_EXPIRATION` (one week), and
611/// a receipt stamped in the future is refused outright. So once
612/// `boundary + one week` has passed, **every** still-valid receipt is
613/// necessarily stamped at or after the boundary and the 1x branch becomes
614/// unreachable. It retires itself; nobody has to remember to turn it off.
615/// - Backdating is **not** prevented during that week. The timestamp is
616/// client-chosen — it is a `payForMerkleTree` argument, the contract only
617/// rejects future and week-old stamps, and quoting nodes sign whatever stamp
618/// the request carries — so a modified client can stamp just before the
619/// boundary and keep paying 1x until such a stamp expires. Expiry is what
620/// closes the route, not detection, and it closes it at
621/// `boundary + one week`. The same branch protects honest in-flight receipts,
622/// so the window cannot be narrowed without also destroying those.
623///
624/// Set to 2026-08-04 15:00 UTC, after the client release with room for
625/// adoption. Two invariants when moving it: **it must never be earlier than the
626/// client release that pays 3x** (an earlier value refuses receipts bought
627/// under the previous rule, the one outcome this constant exists to avoid), and
628/// it must move forward if that **client** release slips — a node enforcing
629/// before clients pay fails every batch upload. A slip in *node* rollout needs
630/// no change: it only means fewer nodes enforce for a while.
631pub const MERKLE_PARITY_ENFORCED_FROM_UNIX: u64 = 1_785_855_600;
632
633/// ADR-0004: max unresolved quote pins to fetch per payment bundle.
634///
635/// A bundle has at most `CLOSE_GROUP_SIZE` quotes; capping fetches per bundle
636/// bounds the amplification a single malicious upload (many distinct unknown
637/// pins) can drive. Excess unresolved pins in one bundle are dropped (left
638/// unresolved, i.e. graced — the audit funnel still catches a serving cheater).
639pub const MAX_PIN_FETCHES_PER_BUNDLE: usize = 3;
640
641/// ADR-0004: capacity of the per-peer negative cache for unresolved pin fetches.
642///
643/// A pin that a peer answered `NotRetained` (or that timed out) is remembered so
644/// repeated bundles citing the same unknown pin don't re-fetch.
645pub const PIN_FETCH_NEGATIVE_CACHE_CAPACITY: usize = 4096;
646
647/// ADR-0004: timeout for a `GetCommitmentByPin` fetch.
648///
649/// Sized for a single small round-trip plus the responder's bounded in-memory
650/// lookup; a fetch is off the payment hot path, so this only bounds the
651/// background cross-check.
652pub const PIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
653
654/// Verification request timeout (per-batch).
655const VERIFICATION_REQUEST_TIMEOUT_SECS: u64 = 15;
656/// Verification request timeout (per-batch).
657pub const VERIFICATION_REQUEST_TIMEOUT: Duration =
658 Duration::from_secs(VERIFICATION_REQUEST_TIMEOUT_SECS);
659
660/// Ceiling on the exponential backoff applied to a pending key that keeps
661/// failing to resolve.
662///
663/// [`VERIFICATION_REQUEST_TIMEOUT`] is the *first* retry delay, not a flat
664/// cadence. A key whose presence probe finds no holder is almost always in that
665/// state because the answer has not changed — a new node that claims a slice of
666/// the keyspace its routing table cannot yet resolve keeps asking the same peers
667/// the same question. Re-asking every 15 seconds costs a verification round trip
668/// per key per retry and produces one log line each time, for no new
669/// information.
670///
671/// Doubling from 15s and capping here gives roughly ten attempts inside one
672/// [`PENDING_VERIFY_MAX_AGE`] residency instead of roughly a hundred and ten,
673/// while bounding the worst-case delay in noticing that a holder *has* appeared
674/// to this value.
675const VERIFICATION_RETRY_BACKOFF_MAX_SECS: u64 = 5 * 60;
676/// Ceiling on the exponential backoff applied to an unresolved pending key.
677pub const VERIFICATION_RETRY_BACKOFF_MAX: Duration =
678 Duration::from_secs(VERIFICATION_RETRY_BACKOFF_MAX_SECS);
679
680/// Maximum ready hints processed by one verification cycle.
681///
682/// The pending queue may be much larger. Each cycle takes a sender-fair bounded
683/// sample, retaining corroboration/age priority within each sender's share.
684/// This value keeps today's roughly 6k-chunk average bootstrap within one cycle
685/// while preventing a full emergency-cap queue from creating one enormous
686/// verification round.
687pub const MAX_VERIFICATION_KEYS_PER_CYCLE: usize = 8_192;
688
689/// Maximum keys accepted in one incoming verification request.
690///
691/// Senders aggregate all keys for a peer into one request. Matching this limit
692/// to the cycle bound lets an honest round use one request per peer while still
693/// bounding the LMDB work performed on the responder's serial replication
694/// message path. Oversized requests are rejected as an empty, wire-compatible
695/// verification response.
696pub const MAX_INCOMING_VERIFICATION_KEYS: usize = MAX_VERIFICATION_KEYS_PER_CYCLE;
697
698/// Maximum simultaneous verification request/response exchanges.
699/// Larger rounds remain fully batched but wait for a permit instead of
700/// launching hundreds or thousands of network requests at once.
701pub const MAX_CONCURRENT_VERIFICATION_REQUESTS: usize = 32;
702
703/// Fetch request timeout.
704const FETCH_REQUEST_TIMEOUT_SECS: u64 = 30;
705/// Fetch request timeout.
706pub const FETCH_REQUEST_TIMEOUT: Duration = Duration::from_secs(FETCH_REQUEST_TIMEOUT_SECS);
707
708/// Maximum age for pending-verification entries before stale eviction.
709const PENDING_VERIFY_MAX_AGE_SECS: u64 = 30 * 60;
710/// Maximum age for pending-verification entries before stale eviction.
711pub const PENDING_VERIFY_MAX_AGE: Duration = Duration::from_secs(PENDING_VERIFY_MAX_AGE_SECS);
712
713/// How long a key waits for another look once this node's disk is **full**.
714///
715/// Only a full disk, not any refused write: a space query that fails says
716/// nothing about available space and keeps the ordinary retry schedule.
717///
718/// A node that cannot write cannot finish an acquisition, so before this gate
719/// the key came straight back. At [`VERIFICATION_REQUEST_TIMEOUT`] that was a
720/// close-group probe as often as every 15 s for every key the node owes — the
721/// requested delay, so cycle polling, round duration and bounded per-cycle
722/// selection make it an upper rate rather than an observed cadence. The owed set
723/// grows with the network rather than with anything this node does — 25.6% of a
724/// 195-service testnet, held full, produced 99.6% of every verification-request
725/// byte on the network (V2-987).
726///
727/// What this schedules is a *look*: the cycle re-reads local capacity and only
728/// probes if space has returned. A key that stays full and authorized sends no
729/// probes at all, because the gate stops the round before it is sent.
730///
731/// Five minutes is chosen against [`PENDING_VERIFY_MAX_AGE`], which it is well
732/// inside. That is not a guarantee that freed space is noticed while the entry
733/// lives: one deferred inside its final five minutes expires first, and a
734/// backlog can delay selection further.
735///
736/// This is deliberately a constant rather than a [`ReplicationConfig`] field.
737/// The struct is publicly re-exported and is not `#[non_exhaustive]`, so a new
738/// field would break downstream exhaustive construction for a knob nothing
739/// needs to tune at runtime.
740///
741/// Applied flat, through the ordinary `defer_pending`. A key deferred inside the
742/// last five minutes of its entry's life therefore expires at
743/// [`PENDING_VERIFY_MAX_AGE`] without a further look and comes back on the next
744/// neighbour-sync hint. An earlier revision clamped the delay to half the
745/// entry's remaining life to avoid that; it was cut because the extra looks it
746/// bought near expiry can themselves become ungated quorum rounds.
747const CAPACITY_BLOCKED_RETRY_SECS: u64 = 5 * 60;
748/// How long a key waits for another look once this node's disk is full.
749pub(crate) const CAPACITY_BLOCKED_RETRY: Duration =
750 Duration::from_secs(CAPACITY_BLOCKED_RETRY_SECS);
751
752/// Trust event weight for confirmed audit failures.
753pub const AUDIT_FAILURE_TRUST_WEIGHT: f64 = 5.0;
754
755/// Whether this build penalises a peer for not holding a chunk it was supposed to hold.
756///
757/// **`true` while the fleet moves off the legacy LMDB chunk store; back to `false` once it
758/// has.** Flipping it is a one-line change in one release.
759///
760/// Deliberately narrow. It covers exactly one accusation: "you did not have a chunk you
761/// were supposed to be holding". It does **not** cover the commitment-bound subtree audit,
762/// where a peer published a signed claim to hold specific keys and could not answer for
763/// them. That contract stays enforced in every release.
764///
765/// The reason it has to exist at all is that the penalty is the *auditor's* decision. A
766/// node that has to give up chunks, because it cannot fit them while it moves them out of
767/// a store that never returns disk, cannot stop its peers penalising it for that. So the
768/// peers stop first, one release ahead, and the node moves in the next one.
769///
770/// A build constant rather than a config field on purpose: a node writes its effective
771/// configuration back to disk, so shipping this as an ordinary setting would bake this
772/// release's value into every operator's file and the next release would change nothing.
773pub const RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY: bool = true;
774
775/// Environment override for [`RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY`], for a canary.
776pub const SUSPEND_CLOSE_GROUP_STORAGE_PENALTY_ENV: &str = "ANT_SUSPEND_UNHELD_CHUNK_PENALTY";
777
778/// The live switch.
779///
780/// Initialised **from the release constant**, not to `false`. That matters: a code path
781/// that never applies the policy then behaves like this release rather than the previous
782/// one. Defaulting the other way meant any constructor that skipped the startup call would
783/// keep penalising nodes for the very thing this release exists to stop penalising, and
784/// `ReplicationEngine::new` is public and is constructed directly by test harnesses.
785///
786/// Process-wide rather than threaded through a parameter because it is exactly that: one
787/// release-level decision that every affected site has to obey identically, and those
788/// sites are spread across call graphs that share no configuration object.
789static CLOSE_GROUP_STORAGE_PENALTY_SUSPENDED: AtomicBool =
790 AtomicBool::new(RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY);
791
792/// Apply this release's decision. Called once, before anything can audit.
793pub fn apply_close_group_storage_penalty_policy() {
794 let Ok(raw) = std::env::var(SUSPEND_CLOSE_GROUP_STORAGE_PENALTY_ENV) else {
795 apply_and_announce(RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY);
796 return;
797 };
798 let suspended = match raw.trim().to_ascii_lowercase().as_str() {
799 "1" | "true" | "yes" | "on" => true,
800 "0" | "false" | "no" | "off" => false,
801 other => {
802 warn!(
803 "{SUSPEND_CLOSE_GROUP_STORAGE_PENALTY_ENV}={other} is not a boolean; \
804 using the build default {RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY}"
805 );
806 RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY
807 }
808 };
809 apply_and_announce(suspended);
810}
811
812/// Set the switch and say so, once, where an operator will see it.
813///
814/// Both states are logged. An operator reading "penalties are suspended" and an operator
815/// reading nothing at all cannot tell the second from a missing log line, and the state
816/// that most needs to be visible is the one that disagrees with what the release intended.
817fn apply_and_announce(suspended: bool) {
818 set_close_group_storage_penalty_suspended(suspended);
819 if suspended != RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY {
820 warn!(
821 close_group_storage_penalty_suspended = suspended,
822 "{SUSPEND_CLOSE_GROUP_STORAGE_PENALTY_ENV} overrides this build: the penalty \
823 for not holding a close-group chunk is {}, where the release intends {}. \
824 Clear that variable unless this node is a deliberate canary.",
825 if suspended { "SUSPENDED" } else { "APPLIED" },
826 if RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY {
827 "SUSPENDED"
828 } else {
829 "APPLIED"
830 }
831 );
832 }
833 if suspended {
834 info!(
835 close_group_storage_penalty_suspended = true,
836 "This release does NOT penalise a peer for failing to hold a close-group \
837 chunk. Commitment-bound audits still penalise. Audits run and record \
838 throughout."
839 );
840 } else {
841 info!(
842 close_group_storage_penalty_suspended = false,
843 "This release penalises a peer for failing to hold a close-group chunk."
844 );
845 }
846}
847
848/// Set whether failing to hold a close-group chunk penalises.
849///
850/// Startup applies the release policy through this. Tests that mean to exercise the
851/// penalty itself set it explicitly, so what they assert is not an accident of whichever
852/// release they happen to be compiled against.
853pub fn set_close_group_storage_penalty_suspended(suspended: bool) {
854 CLOSE_GROUP_STORAGE_PENALTY_SUSPENDED.store(suspended, Ordering::Relaxed);
855}
856
857/// Whether failing to hold a close-group chunk currently penalises.
858#[must_use]
859pub fn close_group_storage_penalty_suspended() -> bool {
860 CLOSE_GROUP_STORAGE_PENALTY_SUSPENDED.load(Ordering::Relaxed)
861}
862
863/// Penalise `peer` at `weight` for not holding a chunk it was supposed to be holding,
864/// unless this release withholds that particular penalty.
865///
866/// Covers the responsible-chunk audit, the fresh-replication possession check, the prune
867/// audit, and the fetch paths where a peer that answered `Present` could not then serve
868/// the bytes. A node short of the disk to hold its chunks produces every one of those, so
869/// leaving any of them out would stop some of its accusers and not others.
870///
871/// Only the penalty is withheld. The caller has already logged the failure with its type,
872/// class and key, and that record is what tells us when it is safe to switch the penalty
873/// back on.
874pub async fn penalise_unheld_close_group_chunk(
875 p2p_node: &Arc<P2PNode>,
876 peer: &PeerId,
877 audit_type: &str,
878 weight: f64,
879) {
880 if close_group_storage_penalty_suspended() {
881 debug!(
882 audit_type,
883 peer = %peer,
884 "Recorded but not penalised: this release withholds the penalty for not \
885 holding a close-group chunk. Commitment-bound audits still penalise."
886 );
887 return;
888 }
889 p2p_node
890 .report_trust_event(peer, TrustEvent::ApplicationFailure(weight))
891 .await;
892}
893
894/// Probability of launching a subtree audit when a peer's *changed* commitment
895/// is ingested via gossip (ADR-0002). Keeps audits occasional surprise exams.
896pub const AUDIT_ON_GOSSIP_PROBABILITY: f64 = 0.2;
897
898/// Per-peer cooldown between gossip-triggered subtree audits (ADR-0002), in
899/// seconds. Bounds how often any one peer is audited regardless of gossip rate.
900pub const AUDIT_ON_GOSSIP_COOLDOWN_SECS: u64 = 30 * 60;
901
902/// ADR-0004: first-audit drainer retry cadence for cooldown-pending pins.
903///
904/// How often the drainer retries pins it kept pending because their peer was on
905/// cooldown. Finer than the cooldown itself so a monetized commitment is
906/// first-audited promptly after its peer's window reopens; the retry just
907/// re-checks a small per-peer map, so the tick is cheap.
908pub const FIRST_AUDIT_RETRY_INTERVAL: Duration = Duration::from_mins(1);
909
910/// Interval for the cumulative first-audit scheduler observability summary.
911///
912/// Deliberately low frequency: this is intended for fleet-level Elasticsearch
913/// aggregation without recreating the high-volume logging load it measures.
914pub const FIRST_AUDIT_SUMMARY_INTERVAL: Duration = Duration::from_mins(5);
915
916/// ADR-0004: max monetized-pin events the first-audit drainer drains from its
917/// channel per wake before it must run the audit-launch phase.
918///
919/// Bounds the synchronous `try_recv` batch so a sustained producer flood cannot
920/// starve audit launching by spinning in the drain loop forever. After this many
921/// events the drainer processes audits, then loops back to drain more.
922pub const FIRST_AUDIT_DRAIN_BATCH: usize = 64;
923
924/// ADR-0004 Amendment 2: token-bucket refill interval for monetized first-audit
925/// launches — one launch token per interval, per node.
926///
927/// This is the load-bearing bound: fleet-wide first-audit pressure becomes
928/// `nodes x (1 / interval)` regardless of upload volume, where the pre-amendment
929/// scheduler scaled with `uploads x pinned-quotes-per-proof x verifying-storers`
930/// (measured at ~110 storage-commitment audit events/hour/service in the
931/// DEV-01 staging run, with 77.7% of launches timing out in the DEV-03
932/// per-service-concurrency attempt). At 5 minutes the sustained rate is
933/// 12 launches/hour/node (a drained burst bucket adds at most
934/// [`FIRST_AUDIT_BUDGET_BURST`] more in the first hour); steady-state demand
935/// sits far below it because nomination is paid-pin-only and re-nominations
936/// are suppressed by [`FIRST_AUDIT_PEER_REAUDIT_INTERVAL`].
937pub const FIRST_AUDIT_LAUNCH_INTERVAL: Duration = Duration::from_mins(5);
938
939/// ADR-0004 Amendment 2: token-bucket capacity for monetized first-audit
940/// launches.
941///
942/// Lets a node absorb a small burst of NEW earning peers (several distinct
943/// paid pins verified back-to-back) without waiting a full refill interval per
944/// launch, while keeping the sustained rate pinned to
945/// [`FIRST_AUDIT_LAUNCH_INTERVAL`].
946pub const FIRST_AUDIT_BUDGET_BURST: u32 = 2;
947
948/// ADR-0004 Amendment 2: max concurrently in-flight monetized first audits per
949/// node.
950///
951/// A first audit can hold a slot for the full size-scaled two-round deadline,
952/// so without this cap a burst of slow/timing-out targets would pile up
953/// concurrent subtree audits even under the launch-rate budget. Deferral is
954/// penalty-free: the pin stays pending and is retried when a slot frees.
955pub const FIRST_AUDIT_MAX_INFLIGHT: u64 = 2;
956
957/// ADR-0004 Amendment 2: max uniform random delay applied before sending a
958/// monetized first-audit challenge.
959///
960/// Every storer of a chunk verifies the same payment at the same instant, so
961/// unjittered first audits from the whole close group would hit the paid peer
962/// simultaneously and trip its per-peer responder admission cap (drops that
963/// auditors then record as Timeout). The jitter decorrelates the observers.
964pub const FIRST_AUDIT_LAUNCH_JITTER_MAX: Duration = Duration::from_secs(30);
965
966/// ADR-0004 Amendment 2: per-peer suppression window between monetized first
967/// audits, across commitment rotations.
968///
969/// Pin-level dedup alone is defeated by the hourly commitment rotation (every
970/// rotation mints a fresh pin, re-arming every observer). After a first audit
971/// LAUNCHES at a peer, further monetized nominations for that peer are dropped
972/// for this window — unless the new pin's committed key count exceeds the
973/// audited one by more than [`FIRST_AUDIT_COUNT_JUMP_NUM`]/
974/// [`FIRST_AUDIT_COUNT_JUMP_DEN`] (a peer that passes an audit on an honest
975/// count and then mints a much larger commitment must be re-nominated
976/// immediately: inflated SIDECAR-ONLY pins are visible to payment verifiers
977/// only, so no gossip-lottery audit can ever cover them). Kept comfortably
978/// inside the 3h answerability TTL so a re-nomination after the window still
979/// lands in-window. Gossip-lottery re-audits are unaffected.
980pub const FIRST_AUDIT_PEER_REAUDIT_INTERVAL: Duration = Duration::from_hours(2);
981
982/// ADR-0004 Amendment 2: committed-count jump that overrides the per-peer
983/// re-audit window, as a ratio (`new > old * NUM / DEN`, integer math).
984///
985/// 3/2: a >1.5x growth in claimed committed keys within the suppression window
986/// re-nominates the peer despite a recent first audit.
987pub const FIRST_AUDIT_COUNT_JUMP_NUM: u64 = 3;
988/// Denominator of the count-jump override ratio. See
989/// [`FIRST_AUDIT_COUNT_JUMP_NUM`].
990pub const FIRST_AUDIT_COUNT_JUMP_DEN: u64 = 2;
991
992/// ADR-0004 Amendment 2: capacity of the bounded verifier-to-drainer
993/// monetized-pin channel.
994///
995/// Nominations are gated behind SETTLED on-chain payments, so legitimate
996/// ingress is tiny; the drainer drains every wake (batched at
997/// [`FIRST_AUDIT_DRAIN_BATCH`]) and coalesces newest-per-peer, so a backlog
998/// this deep implies the drainer is starved, not that work is arriving fast.
999/// Producers `try_send` and drop on full: a dropped nomination is
1000/// penalty-free; the peer's gossiped commitments stay lottery-covered and
1001/// its next settled payment re-nominates the paid pin.
1002pub const FIRST_AUDIT_INGRESS_CAPACITY: usize = 1024;
1003
1004/// Number of subtree leaves spot-checked against real chunk bytes per audit
1005/// (ADR-0002 real-bytes layer).
1006///
1007/// The auditor clamps this to its 3..=5 band (`BYTE_SPOTCHECK_MIN..=MAX` in
1008/// `storage_commitment_audit`), so this is the effective MAXIMUM — set it
1009/// within the band rather than advertising a sample size the auditor never
1010/// requests.
1011pub const AUDIT_SPOTCHECK_COUNT: u32 = 5;
1012
1013/// Conservative leaf-count hint for sizing the subtree-audit response deadline.
1014///
1015/// The deadline is set before the proof arrives, so we size for the largest
1016/// legal store: `sqrt(MAX_COMMITMENT_KEY_COUNT) = 1000`. Honest small stores
1017/// finish well within it.
1018pub const SUBTREE_AUDIT_TIMEOUT_LEAF_HINT: usize = 1000;
1019
1020/// Maximum mature records selected for prune-confirmation auditing per pass.
1021///
1022/// This bounds local digest/proof bookkeeping independently from the number
1023/// of network requests. Keys for the same peer are batched below.
1024pub const MAX_PRUNE_AUDIT_CANDIDATES_PER_PASS: usize = 1024;
1025
1026/// Maximum initial prune-confirmation audit requests sent per pass.
1027///
1028/// A request may contain multiple keys. Keeping this separate from the
1029/// candidate cap prevents the old candidate-to-peer-edge accounting from
1030/// limiting a production pass to roughly nine records.
1031pub const MAX_PRUNE_AUDIT_REQUESTS_PER_PASS: usize = 256;
1032
1033/// Maximum mature records deleted through the complete width-20 fast path per
1034/// pass.
1035pub const MAX_FAST_PRUNE_DELETIONS_PER_PASS: usize = 2048;
1036
1037/// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before proceeding
1038/// with bootstrap sync. Covers bootstrap nodes with no peers to connect to.
1039const BOOTSTRAP_COMPLETE_TIMEOUT_SECS: u64 = 60;
1040
1041// ---------------------------------------------------------------------------
1042// Runtime-configurable wrapper
1043// ---------------------------------------------------------------------------
1044
1045/// Runtime-configurable replication parameters.
1046///
1047/// Validated on construction — node rejects invalid configs.
1048#[derive(Debug, Clone)]
1049pub struct ReplicationConfig {
1050 /// Close-group width and target holder count per key.
1051 pub close_group_size: usize,
1052 /// Required positive presence votes for quorum.
1053 pub quorum_threshold: usize,
1054 /// Maximum closest nodes tracking paid status for a key.
1055 pub paid_list_close_group_size: usize,
1056 /// Number of closest peers to self eligible for neighbor sync.
1057 pub neighbor_sync_scope: usize,
1058 /// Peers synced concurrently per round-robin repair round.
1059 pub neighbor_sync_peer_count: usize,
1060 /// Neighbor sync cadence range (min).
1061 pub neighbor_sync_interval_min: Duration,
1062 /// Neighbor sync cadence range (max).
1063 pub neighbor_sync_interval_max: Duration,
1064 /// Minimum spacing between successive syncs with the same peer.
1065 pub neighbor_sync_cooldown: Duration,
1066 /// Self-lookup cadence range (min).
1067 pub self_lookup_interval_min: Duration,
1068 /// Self-lookup cadence range (max).
1069 pub self_lookup_interval_max: Duration,
1070 /// Audit scheduler cadence range (min).
1071 pub audit_tick_interval_min: Duration,
1072 /// Audit scheduler cadence range (max).
1073 pub audit_tick_interval_max: Duration,
1074 /// Floor on the audit response deadline. Covers global RTT for
1075 /// the small request/response envelope plus scheduling jitter.
1076 /// See `AUDIT_RESPONSE_FLOOR_SECS` for sizing.
1077 pub audit_response_floor: Duration,
1078 /// Conservative honest-responder read throughput (bytes/sec).
1079 /// Used to scale the audit response deadline against the size of
1080 /// the challenge. Slow enough that even an HDD-backed honest peer
1081 /// fits inside the budget; fast enough that a relay attacker who
1082 /// must fetch bytes over the network falls outside.
1083 pub audit_honest_read_bps: u64,
1084 /// Slack multiplier on the honest-read estimate before
1085 /// declaring an audit timed out.
1086 pub audit_response_honest_multiplier: u64,
1087 /// Maximum duration a peer may claim bootstrap status.
1088 pub bootstrap_claim_grace_period: Duration,
1089 /// Minimum continuous out-of-range duration before pruning a key.
1090 pub prune_hysteresis_duration: Duration,
1091 /// Verification request timeout (per-batch).
1092 pub verification_request_timeout: Duration,
1093 /// Fetch request timeout.
1094 pub fetch_request_timeout: Duration,
1095 /// Seconds to wait for `DhtNetworkEvent::BootstrapComplete` before
1096 /// proceeding with bootstrap sync (covers bootstrap nodes with no peers).
1097 pub bootstrap_complete_timeout_secs: u64,
1098 /// Lower bound of the delay before a fresh-replication possession check
1099 /// runs (ADR-0003). Defaults to [`POSSESSION_CHECK_DELAY_MIN`]; tests
1100 /// shorten it so the scheduled check fires quickly.
1101 pub possession_check_delay_min: Duration,
1102 /// Upper bound of the possession-check delay window (ADR-0003). Defaults
1103 /// to [`POSSESSION_CHECK_DELAY_MAX`].
1104 pub possession_check_delay_max: Duration,
1105 /// Per-peer responder-side cooldown between heavy subtree round-1 proofs.
1106 /// Defaults to [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`]; tests set
1107 /// it low so rapid back-to-back audits of one holder are not rate-dropped.
1108 pub subtree_round1_responder_cooldown: Duration,
1109 /// Global ceiling on concurrent heavy subtree round-1 proofs this node will
1110 /// serve. Defaults to [`MAX_CONCURRENT_SUBTREE_ROUND1`].
1111 ///
1112 /// Exposed here rather than read straight from the constant because it is the
1113 /// tightest bound the responder applies and the one with the least fleet
1114 /// evidence behind its value: too low and honest auditors are capacity-dropped
1115 /// (their audits land in the graced timeout lane, so coverage silently falls
1116 /// without any peer being penalised), too high and concurrent full-subtree
1117 /// hashing competes with serving real traffic. Making it configurable means a
1118 /// fleet that lands on the wrong number can be retuned without cutting a
1119 /// release. A value of 0 is clamped to 1 by
1120 /// [`SubtreeRound1Limiter::new`](crate::replication) rather than disabling
1121 /// round 1 outright.
1122 pub subtree_round1_max_concurrent: usize,
1123}
1124
1125impl Default for ReplicationConfig {
1126 fn default() -> Self {
1127 Self {
1128 close_group_size: CLOSE_GROUP_SIZE,
1129 quorum_threshold: QUORUM_THRESHOLD,
1130 paid_list_close_group_size: PAID_LIST_CLOSE_GROUP_SIZE,
1131 neighbor_sync_scope: NEIGHBOR_SYNC_SCOPE,
1132 neighbor_sync_peer_count: NEIGHBOR_SYNC_PEER_COUNT,
1133 neighbor_sync_interval_min: NEIGHBOR_SYNC_INTERVAL_MIN,
1134 neighbor_sync_interval_max: NEIGHBOR_SYNC_INTERVAL_MAX,
1135 neighbor_sync_cooldown: NEIGHBOR_SYNC_COOLDOWN,
1136 self_lookup_interval_min: SELF_LOOKUP_INTERVAL_MIN,
1137 self_lookup_interval_max: SELF_LOOKUP_INTERVAL_MAX,
1138 audit_tick_interval_min: AUDIT_TICK_INTERVAL_MIN,
1139 audit_tick_interval_max: AUDIT_TICK_INTERVAL_MAX,
1140 audit_response_floor: Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
1141 audit_honest_read_bps: AUDIT_HONEST_READ_BPS,
1142 audit_response_honest_multiplier: AUDIT_RESPONSE_HONEST_MULTIPLIER,
1143 bootstrap_claim_grace_period: BOOTSTRAP_CLAIM_GRACE_PERIOD,
1144 prune_hysteresis_duration: PRUNE_HYSTERESIS_DURATION,
1145 verification_request_timeout: VERIFICATION_REQUEST_TIMEOUT,
1146 fetch_request_timeout: FETCH_REQUEST_TIMEOUT,
1147 bootstrap_complete_timeout_secs: BOOTSTRAP_COMPLETE_TIMEOUT_SECS,
1148 possession_check_delay_min: POSSESSION_CHECK_DELAY_MIN,
1149 possession_check_delay_max: POSSESSION_CHECK_DELAY_MAX,
1150 subtree_round1_responder_cooldown: SUBTREE_ROUND1_RESPONDER_COOLDOWN,
1151 subtree_round1_max_concurrent: MAX_CONCURRENT_SUBTREE_ROUND1,
1152 }
1153 }
1154}
1155
1156impl ReplicationConfig {
1157 /// Validate safety constraints. Returns `Err` with a description if any
1158 /// constraint is violated.
1159 ///
1160 /// # Errors
1161 ///
1162 /// Returns a human-readable message describing the first violated
1163 /// constraint.
1164 pub fn validate(&self) -> Result<(), String> {
1165 if self.close_group_size == 0 {
1166 return Err("close_group_size must be >= 1".to_string());
1167 }
1168 if self.quorum_threshold == 0 || self.quorum_threshold > self.close_group_size {
1169 return Err(format!(
1170 "quorum_threshold ({}) must satisfy 1 <= quorum_threshold <= close_group_size ({})",
1171 self.quorum_threshold, self.close_group_size,
1172 ));
1173 }
1174 if self.close_group_size > MAX_PRUNE_AUDIT_REQUESTS_PER_PASS {
1175 return Err(format!(
1176 "close_group_size ({}) must be <= MAX_PRUNE_AUDIT_REQUESTS_PER_PASS ({})",
1177 self.close_group_size, MAX_PRUNE_AUDIT_REQUESTS_PER_PASS,
1178 ));
1179 }
1180 if self.paid_list_close_group_size == 0 {
1181 return Err("paid_list_close_group_size must be >= 1".to_string());
1182 }
1183 if self.neighbor_sync_interval_min > self.neighbor_sync_interval_max {
1184 return Err(format!(
1185 "neighbor_sync_interval_min ({:?}) must be <= neighbor_sync_interval_max ({:?})",
1186 self.neighbor_sync_interval_min, self.neighbor_sync_interval_max,
1187 ));
1188 }
1189 if self.audit_tick_interval_min > self.audit_tick_interval_max {
1190 return Err(format!(
1191 "audit_tick_interval_min ({:?}) must be <= audit_tick_interval_max ({:?})",
1192 self.audit_tick_interval_min, self.audit_tick_interval_max,
1193 ));
1194 }
1195 if self.self_lookup_interval_min > self.self_lookup_interval_max {
1196 return Err(format!(
1197 "self_lookup_interval_min ({:?}) must be <= self_lookup_interval_max ({:?})",
1198 self.self_lookup_interval_min, self.self_lookup_interval_max,
1199 ));
1200 }
1201 if self.neighbor_sync_peer_count == 0 {
1202 return Err("neighbor_sync_peer_count must be >= 1".to_string());
1203 }
1204 if self.neighbor_sync_scope == 0 {
1205 return Err("neighbor_sync_scope must be >= 1".to_string());
1206 }
1207 if self.neighbor_sync_scope > K_BUCKET_SIZE {
1208 return Err(format!(
1209 "neighbor_sync_scope ({}) must be <= K_BUCKET_SIZE ({})",
1210 self.neighbor_sync_scope, K_BUCKET_SIZE,
1211 ));
1212 }
1213 Ok(())
1214 }
1215
1216 /// Effective quorum votes required for a key given the number of
1217 /// reachable quorum targets.
1218 ///
1219 /// `min(self.quorum_threshold, floor(quorum_targets_count / 2) + 1)`
1220 #[must_use]
1221 pub fn quorum_needed(&self, quorum_targets_count: usize) -> usize {
1222 if quorum_targets_count == 0 {
1223 return 0;
1224 }
1225 let majority = quorum_targets_count / 2 + 1;
1226 self.quorum_threshold.min(majority)
1227 }
1228
1229 /// Confirmations required for paid-list consensus given the number of
1230 /// peers in the paid-list close group for a key.
1231 ///
1232 /// `floor(paid_group_size / 2) + 1`
1233 #[must_use]
1234 pub fn confirm_needed(paid_group_size: usize) -> usize {
1235 paid_group_size / 2 + 1
1236 }
1237
1238 /// Confirmations required to authorize a key, given the edge-discounted
1239 /// denominator and the true (undiscounted) group size.
1240 ///
1241 /// The strict majority of the discounted group, raised to
1242 /// [`PAID_LIST_ABSOLUTE_CONFIRM_FLOOR`] so a shrunken denominator cannot
1243 /// make a single voter decisive — but never above `full_group_size`, which
1244 /// would demand more confirmations than there are peers to give them.
1245 #[must_use]
1246 pub fn paid_confirm_needed(effective_group_size: usize, full_group_size: usize) -> usize {
1247 Self::confirm_needed(effective_group_size)
1248 .max(PAID_LIST_ABSOLUTE_CONFIRM_FLOOR.min(full_group_size))
1249 }
1250
1251 /// Number of furthest peers treated as churny edge voters for a paid close
1252 /// group of `paid_group_size`, when the group is at full configured width.
1253 ///
1254 /// Scaled to the group so the discount stays proportionate at every
1255 /// configured width, and capped at [`PAID_LIST_FLEX_EDGE_COUNT`]. Returns
1256 /// `0` for an undersized group, which keeps its ordinary strict majority.
1257 #[must_use]
1258 pub fn paid_list_flex_edge_count(
1259 paid_group_size: usize,
1260 configured_group_size: usize,
1261 ) -> usize {
1262 if paid_group_size < configured_group_size {
1263 return 0;
1264 }
1265 PAID_LIST_FLEX_EDGE_COUNT.min(configured_group_size / PAID_LIST_FLEX_EDGE_DIVISOR)
1266 }
1267
1268 /// Returns a random duration in `[neighbor_sync_interval_min,
1269 /// neighbor_sync_interval_max]`.
1270 #[must_use]
1271 pub fn random_neighbor_sync_interval(&self) -> Duration {
1272 random_duration_in_range(
1273 self.neighbor_sync_interval_min,
1274 self.neighbor_sync_interval_max,
1275 )
1276 }
1277
1278 /// Maximum age of an outstanding bootstrap capacity-rejection record.
1279 ///
1280 /// A source is revisited only after the round-robin loop has advanced
1281 /// through every neighbor batch. Size the window from that full configured
1282 /// cycle (including one request deadline per peer), the peer cooldown, and
1283 /// one slow-cadence interval of slack. This prevents a live source near the
1284 /// end of a 20-peer cycle from being expired before it can legitimately
1285 /// re-deliver its rejected hints.
1286 #[must_use]
1287 pub fn capacity_rejected_max_age(&self) -> Duration {
1288 let batch_size = self.neighbor_sync_peer_count.max(1);
1289 let batch_count = self.neighbor_sync_scope.saturating_add(batch_size - 1) / batch_size;
1290 let batch_count = u32::try_from(batch_count).unwrap_or(u32::MAX);
1291 let peer_count = u32::try_from(self.neighbor_sync_scope).unwrap_or(u32::MAX);
1292 let full_cycle = self
1293 .neighbor_sync_interval_max
1294 .saturating_mul(batch_count)
1295 .saturating_add(self.verification_request_timeout.saturating_mul(peer_count));
1296
1297 full_cycle
1298 .max(self.neighbor_sync_cooldown)
1299 .saturating_add(self.neighbor_sync_interval_max)
1300 }
1301
1302 /// Compute the number of keys to sample for an audit round, scaled
1303 /// dynamically by the total number of locally stored keys.
1304 ///
1305 /// Formula: `max(floor(sqrt(total_keys)), 1)`, capped at `total_keys`.
1306 #[must_use]
1307 pub fn audit_sample_count(total_keys: usize) -> usize {
1308 #[allow(
1309 clippy::cast_possible_truncation,
1310 clippy::cast_sign_loss,
1311 clippy::cast_precision_loss
1312 )]
1313 let sqrt = (total_keys as f64).sqrt() as usize;
1314 sqrt.max(1).min(total_keys)
1315 }
1316
1317 /// Maximum number of keys this node should send in one responsible-chunk
1318 /// [`AuditChallenge`].
1319 ///
1320 /// This is the sender-side limit used by the normal responsible audit path:
1321 /// one challenge samples at most `sqrt(local_stored_keys)` keys. Other paths
1322 /// that reuse the same `AuditChallenge` wire message, such as
1323 /// prune-confirmation audits, should chunk to this same limit instead of
1324 /// inventing a larger batch size.
1325 ///
1326 /// [`AuditChallenge`]: crate::replication::protocol::AuditChallenge
1327 #[must_use]
1328 pub fn responsible_audit_key_limit(local_stored_keys: usize) -> usize {
1329 Self::audit_sample_count(local_stored_keys)
1330 }
1331
1332 /// Maximum number of keys to accept in an incoming audit challenge.
1333 ///
1334 /// Scales dynamically from the same responsible-audit sender limit, with a
1335 /// 2x margin to account for the challenger having a larger local store than
1336 /// us and therefore sampling more keys.
1337 #[must_use]
1338 pub fn max_incoming_audit_keys(stored_chunks: usize) -> usize {
1339 // Allow at least 1 key so a newly-joined node can still be audited.
1340 (2 * Self::responsible_audit_key_limit(stored_chunks)).max(1)
1341 }
1342
1343 /// Compute the audit response timeout for a challenge with
1344 /// `challenged_key_count` keys, **sized to be tight enough that a
1345 /// relay attacker that must fetch the chunk bytes from elsewhere
1346 /// falls outside the budget**.
1347 ///
1348 /// Formula:
1349 /// `floor + (challenged_bytes / honest_read_bps) × multiplier`
1350 ///
1351 /// Where `challenged_bytes = k × MAX_CHUNK_SIZE`. An honest peer
1352 /// reads `k × 4 MiB` from local disk at `honest_read_bps` (set
1353 /// conservatively at 50 MB/s — well below modern SSDs); the
1354 /// multiplier of 5 absorbs jitter, BLAKE3, ML-DSA, and slow disks.
1355 ///
1356 /// A relay attacker on a residential link (~5-12 MB/s) who must
1357 /// fetch the same `k × 4 MiB` over the network sees ~10-100× higher
1358 /// latency than disk for the data alone, plus per-chunk round-trips,
1359 /// and misses the budget. In the periodic responsible-chunk
1360 /// `AuditChallenge`, prune-confirmation, and ADR-0003 possession-check paths
1361 /// that timeout is an immediate audit failure. The heavier subtree audit
1362 /// still graces timeouts separately.
1363 ///
1364 /// This is an economic deterrent for the §7 relay limit calibrated
1365 /// for residential bandwidth, NOT a hard bound: a relay on a
1366 /// datacenter cross-connect (≥1 Gbps) can fetch `k × 4 MiB` fast
1367 /// enough to answer in time. It raises the relay's cost (bandwidth
1368 /// per audit) without claiming to make relaying impossible. The
1369 /// cryptographic guarantee remains commitment-binding (the relay
1370 /// must still hold or fetch the exact committed bytes); the timeout
1371 /// only attacks the economics.
1372 #[must_use]
1373 pub fn audit_response_timeout(&self, challenged_key_count: usize) -> Duration {
1374 let bytes_per_key = u64::try_from(crate::ant_protocol::MAX_CHUNK_SIZE).unwrap_or(u64::MAX);
1375 let keys = u64::try_from(challenged_key_count).unwrap_or(u64::MAX);
1376 let total_bytes = bytes_per_key.saturating_mul(keys);
1377 let bps = self.audit_honest_read_bps.max(1);
1378 // Apply the multiplier BEFORE integer-dividing by bps so each
1379 // chunk contributes a fractional second rather than rounding
1380 // down to zero. Otherwise k in 1..=12 would all collapse to the
1381 // floor (~40 MiB / 50 MB/s = 0 secs in integer arithmetic), and
1382 // an honest HDD-backed peer at sqrt(N)=10 stored chunks could
1383 // miss the budget under load.
1384 let multiplied = total_bytes.saturating_mul(self.audit_response_honest_multiplier);
1385 // Resolve the scaled term in MILLISECONDS, not seconds: at small
1386 // sample sizes (e.g. a 2-key challenge → 8 MiB) the per-second quotient
1387 // `multiplied / bps` integer-truncates to 0, leaving only the floor.
1388 // Small challenges still need the sub-second honest-read estimate
1389 // (e.g. 8 MiB × 5 / 50 MB/s ≈ 840 ms) instead of dropping it.
1390 let scaled_ms = multiplied.saturating_mul(1000) / bps;
1391 // saturating_add avoids a panic if the floor plus the scaled term would
1392 // overflow `Duration::MAX`.
1393 self.audit_response_floor
1394 .saturating_add(Duration::from_millis(scaled_ms))
1395 }
1396
1397 /// Deadline for the round-2 SLICE challenge opening `openings` blocks.
1398 ///
1399 /// The reply itself is only a few KB per opening (a 1 KiB block plus two
1400 /// short hash chains), but an honest responder still reads each opened
1401 /// chunk's full bytes from disk to build its Bao slice and nonced opening. So
1402 /// the deadline is sized to that honest full-chunk disk read (the same
1403 /// per-byte scaling as [`Self::audit_response_timeout`], one full chunk per
1404 /// opening), on the `BYTE_AUDIT_RESPONSE_FLOOR_SECS` floor to absorb the
1405 /// handshake and a busy disk.
1406 ///
1407 /// The deadline is not a security parameter, and this is worth stating
1408 /// precisely because an earlier version of this comment claimed more than
1409 /// it should. The round-1 `nonced_root` is uncomputable without all the
1410 /// bytes under a fresh nonce, but that binds only that SOMEONE holding them
1411 /// computed it, not that the audited peer did: nonce, peer id and key are
1412 /// all public, so a backend holding one copy can compute roots and openings
1413 /// for any number of front-end identities, and only the compact proof
1414 /// crosses the link. The old full-byte round 2 did not prevent that either
1415 /// — it priced it, by forcing megabytes through the relay per audit, and a
1416 /// tight deadline was part of that price. Both are gone here. So the
1417 /// deadline exists only to bound how long the auditor waits for an honest
1418 /// reply, and non-delegability is not a property either design provides;
1419 /// see ADR-0009 for where that is left.
1420 #[must_use]
1421 pub fn slice_audit_response_timeout(&self, openings: usize) -> Duration {
1422 let scaled = self
1423 .audit_response_timeout(openings)
1424 .saturating_sub(self.audit_response_floor);
1425 Duration::from_secs(BYTE_AUDIT_RESPONSE_FLOOR_SECS).saturating_add(scaled)
1426 }
1427
1428 /// Number of subtree leaves to spot-check against real chunk bytes per
1429 /// audit (ADR-0002 real-bytes layer). Faking a fraction `x` of nonced
1430 /// leaves survives only `(1 - x)^k`.
1431 #[must_use]
1432 pub fn audit_spotcheck_count(&self) -> u32 {
1433 AUDIT_SPOTCHECK_COUNT
1434 }
1435
1436 /// Conservative leaf-count hint for sizing the subtree-audit response
1437 /// deadline before the proof arrives.
1438 ///
1439 /// The selected subtree holds about `sqrt(key_count)` real leaves; sizing
1440 /// for a large store keeps an honest peer with a big store from timing out.
1441 #[must_use]
1442 pub fn subtree_audit_timeout_leaf_hint(&self) -> usize {
1443 SUBTREE_AUDIT_TIMEOUT_LEAF_HINT
1444 }
1445
1446 /// Returns a random duration in `[audit_tick_interval_min,
1447 /// audit_tick_interval_max]`.
1448 #[must_use]
1449 pub fn random_audit_tick_interval(&self) -> Duration {
1450 random_duration_in_range(self.audit_tick_interval_min, self.audit_tick_interval_max)
1451 }
1452
1453 /// Returns a random duration in `[self_lookup_interval_min,
1454 /// self_lookup_interval_max]`.
1455 #[must_use]
1456 pub fn random_self_lookup_interval(&self) -> Duration {
1457 random_duration_in_range(self.self_lookup_interval_min, self.self_lookup_interval_max)
1458 }
1459}
1460
1461/// Pick a random `Duration` uniformly in `[min, max]` at millisecond
1462/// granularity.
1463///
1464/// When `min == max` the result is deterministic.
1465fn random_duration_in_range(min: Duration, max: Duration) -> Duration {
1466 if min == max {
1467 return min;
1468 }
1469 // Our intervals are minutes/hours, well within u64 range. Saturate to
1470 // u64::MAX on the impossible overflow path to avoid a lossy cast.
1471 let to_u64_millis = |d: Duration| -> u64 { u64::try_from(d.as_millis()).unwrap_or(u64::MAX) };
1472 let chosen = rand::thread_rng().gen_range(to_u64_millis(min)..=to_u64_millis(max));
1473 Duration::from_millis(chosen)
1474}
1475
1476// ---------------------------------------------------------------------------
1477// Tests
1478// ---------------------------------------------------------------------------
1479
1480#[cfg(test)]
1481#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1482mod tests {
1483 use super::*;
1484 use serial_test::serial;
1485
1486 #[test]
1487 fn defaults_pass_validation() {
1488 let config = ReplicationConfig::default();
1489 assert!(config.validate().is_ok(), "default config must be valid");
1490 }
1491
1492 #[test]
1493 fn default_prune_hysteresis_is_three_days() {
1494 let config = ReplicationConfig::default();
1495 assert_eq!(config.prune_hysteresis_duration, Duration::from_hours(72));
1496 }
1497
1498 #[test]
1499 fn storage_admission_width_adds_margin() {
1500 const TEST_CLOSE_GROUP_SIZE: usize = 7;
1501
1502 assert_eq!(
1503 storage_admission_width(TEST_CLOSE_GROUP_SIZE),
1504 TEST_CLOSE_GROUP_SIZE + STORAGE_ADMISSION_MARGIN
1505 );
1506 assert_eq!(storage_admission_width(usize::MAX), usize::MAX);
1507 }
1508
1509 #[test]
1510 fn audit_failure_weight_is_five() {
1511 assert!((AUDIT_FAILURE_TRUST_WEIGHT - 5.0).abs() <= f64::EPSILON);
1512 }
1513
1514 /// One test rather than several, because the switch is process-wide: separate tests
1515 /// would race each other under the default parallel runner.
1516 #[test]
1517 #[serial]
1518 fn the_unheld_chunk_penalty_switch_follows_the_release_it_is_compiled_into() {
1519 // A build that never applies the policy still behaves like THIS release, not the
1520 // previous one. `ReplicationEngine::new` is public and is constructed directly by
1521 // test harnesses, so defaulting the other way would leave those engines penalising
1522 // exactly what the release exists to stop penalising.
1523 assert_eq!(
1524 close_group_storage_penalty_suspended(),
1525 RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY
1526 );
1527
1528 set_close_group_storage_penalty_suspended(true);
1529 assert!(close_group_storage_penalty_suspended());
1530 set_close_group_storage_penalty_suspended(false);
1531 assert!(!close_group_storage_penalty_suspended());
1532
1533 // And applying the release policy lands on whatever this build ships, without
1534 // asserting the constant itself, which the follow-up release flips on purpose.
1535 apply_and_announce(RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY);
1536 assert_eq!(
1537 close_group_storage_penalty_suspended(),
1538 RELEASE_SUSPEND_CLOSE_GROUP_STORAGE_PENALTY
1539 );
1540 }
1541
1542 #[test]
1543 fn core_replication_id_stays_v2_and_subtree_rides_its_own_id() {
1544 // Core replication, including all digest audit lanes, stays on v2.
1545 // Only the subtree family changed and therefore receives a separate id.
1546 assert_eq!(REPLICATION_PROTOCOL_ID, "autonomi.ant.replication.v2");
1547 assert_eq!(
1548 SUBTREE_AUDIT_PROTOCOL_ID,
1549 "autonomi.ant.replication.subtree-audit.v2"
1550 );
1551 assert_ne!(REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID);
1552 }
1553
1554 #[test]
1555 fn audit_response_timeout_floor_at_zero_keys() {
1556 let config = ReplicationConfig::default();
1557 assert_eq!(
1558 config.audit_response_timeout(0),
1559 Duration::from_secs(AUDIT_RESPONSE_FLOOR_SECS),
1560 "zero-key challenge should yield the floor exactly"
1561 );
1562 }
1563
1564 #[test]
1565 fn audit_response_timeout_scales_with_key_count() {
1566 let config = ReplicationConfig::default();
1567 let t1 = config.audit_response_timeout(1);
1568 let t10 = config.audit_response_timeout(10);
1569 let t100 = config.audit_response_timeout(100);
1570 assert!(t1 <= t10 && t10 < t100, "timeout must not decrease with k");
1571
1572 // Scaling now resolves in MILLISECONDS so a sub-second honest read no
1573 // longer truncates to zero (§4). For k=1:
1574 // (4_194_304 × 5 × 1000) / 52_428_800 = 400 ms, + 4 s round-1 floor =
1575 // 4.4 s.
1576 assert_eq!(t1, Duration::from_millis(4400));
1577
1578 // For k=10: (10 × 4_194_304 × 5 × 1000) / 52_428_800 = 4000 ms scaled,
1579 // + 4 s floor = 8 s. An HDD-backed honest peer at 20 MB/s reads 40 MiB
1580 // in ~2 s, comfortably inside; a relay fetching 40 MiB at 5 MB/s
1581 // residential bandwidth needs ~8 s for the data alone, outside.
1582 assert_eq!(t10, Duration::from_secs(8));
1583
1584 // For k=100: (100 × 4_194_304 × 5 × 1000) / 52_428_800 = 40_000 ms
1585 // scaled, + 4 s floor = 44 s.
1586 assert_eq!(t100, Duration::from_secs(44));
1587 }
1588
1589 #[test]
1590 fn audit_response_timeout_fits_honest_hdd_at_typical_sample_size() {
1591 // The canonical audit sample is sqrt(N) at N stored chunks.
1592 // At N=100 stored chunks, sample is 10. An HDD-backed honest
1593 // peer at the slowest realistic random-read throughput (20 MB/s,
1594 // well below modern HDDs which sustain 80-150 MB/s sequential)
1595 // reads 10 × 4 MiB = 40 MiB in ~2 s. Add 300 ms cross-continent
1596 // RTT, ~10 ms scheduling, ~3 ms ML-DSA sign, and the honest
1597 // envelope is ~2.3 s. The 8 s budget at k=10 leaves >5 s of
1598 // slack.
1599 let config = ReplicationConfig::default();
1600 let budget = config.audit_response_timeout(10);
1601 let realistic_hdd_bps: u64 = 20 * 1024 * 1024;
1602 let bytes: u64 = 10 * 4 * 1024 * 1024;
1603 let honest_envelope_secs = bytes / realistic_hdd_bps + 1; // +1 s for network/scheduling/sign
1604 assert!(
1605 Duration::from_secs(honest_envelope_secs) < budget,
1606 "honest HDD envelope ({honest_envelope_secs}s) must fit inside k=10 budget ({}s)",
1607 budget.as_secs(),
1608 );
1609 }
1610
1611 #[test]
1612 fn audit_response_timeout_relay_is_outside_envelope() {
1613 // The intended invariant: an honest peer with the SSD-class
1614 // read budget fits inside `audit_response_timeout(k)`, while a
1615 // relay attacker fetching k*4MiB over residential bandwidth
1616 // (≈ 5 MB/s realistic for sustained download) does NOT. Spot-
1617 // check this at k=100: honest budget is 44s, relay needs at
1618 // least 100 * 4 MiB / 5 MB/s = 80s for the data alone, which
1619 // exceeds the budget.
1620 let config = ReplicationConfig::default();
1621 let budget = config.audit_response_timeout(100);
1622 let relay_data_only = Duration::from_secs(100 * 4 * 1024 * 1024 / (5 * 1024 * 1024));
1623 assert!(
1624 relay_data_only > budget,
1625 "relay fetch ({}s) must exceed honest audit budget ({}s)",
1626 relay_data_only.as_secs(),
1627 budget.as_secs(),
1628 );
1629 }
1630
1631 #[test]
1632 fn audit_response_timeout_saturates_on_huge_k() {
1633 let config = ReplicationConfig::default();
1634 // Should not panic or overflow at extreme k values.
1635 let _ = config.audit_response_timeout(usize::MAX);
1636 }
1637
1638 #[test]
1639 fn quorum_threshold_zero_rejected() {
1640 let config = ReplicationConfig {
1641 quorum_threshold: 0,
1642 ..ReplicationConfig::default()
1643 };
1644 assert!(config.validate().is_err());
1645 }
1646
1647 #[test]
1648 fn quorum_threshold_exceeds_close_group_rejected() {
1649 let defaults = ReplicationConfig::default();
1650 let config = ReplicationConfig {
1651 quorum_threshold: defaults.close_group_size + 1,
1652 ..defaults
1653 };
1654 assert!(config.validate().is_err());
1655 }
1656
1657 #[test]
1658 fn close_group_size_zero_rejected() {
1659 let config = ReplicationConfig {
1660 close_group_size: 0,
1661 ..ReplicationConfig::default()
1662 };
1663 assert!(config.validate().is_err());
1664 }
1665
1666 #[test]
1667 fn close_group_size_exceeding_prune_audit_request_budget_rejected() {
1668 let config = ReplicationConfig {
1669 close_group_size: MAX_PRUNE_AUDIT_REQUESTS_PER_PASS + 1,
1670 quorum_threshold: QUORUM_THRESHOLD,
1671 ..ReplicationConfig::default()
1672 };
1673
1674 let err = config.validate().unwrap_err();
1675
1676 assert!(
1677 err.contains("MAX_PRUNE_AUDIT_REQUESTS_PER_PASS"),
1678 "error should mention prune audit budget: {err}"
1679 );
1680 }
1681
1682 #[test]
1683 fn paid_list_close_group_size_zero_rejected() {
1684 let config = ReplicationConfig {
1685 paid_list_close_group_size: 0,
1686 ..ReplicationConfig::default()
1687 };
1688 assert!(config.validate().is_err());
1689 }
1690
1691 #[test]
1692 fn neighbor_sync_interval_inverted_rejected() {
1693 let config = ReplicationConfig {
1694 neighbor_sync_interval_min: Duration::from_secs(100),
1695 neighbor_sync_interval_max: Duration::from_secs(50),
1696 ..ReplicationConfig::default()
1697 };
1698 assert!(config.validate().is_err());
1699 }
1700
1701 #[test]
1702 fn capacity_rejection_expiry_covers_full_configured_sync_cycle() {
1703 let config = ReplicationConfig {
1704 // Keep the scope deliberately indivisible by the batch size so the
1705 // expectation verifies that the final partial batch is included.
1706 neighbor_sync_scope: 21,
1707 neighbor_sync_peer_count: 4,
1708 ..ReplicationConfig::default()
1709 };
1710 let batches = config
1711 .neighbor_sync_scope
1712 .div_ceil(config.neighbor_sync_peer_count);
1713 let cycle_cadence = config.neighbor_sync_interval_max * u32::try_from(batches).unwrap();
1714 let request_budget = config.verification_request_timeout
1715 * u32::try_from(config.neighbor_sync_scope).unwrap();
1716 let full_cycle = cycle_cadence + request_budget;
1717
1718 assert_eq!(
1719 config.capacity_rejected_max_age(),
1720 full_cycle + config.neighbor_sync_interval_max,
1721 );
1722 assert!(config.capacity_rejected_max_age() > Duration::from_mins(70));
1723 }
1724
1725 #[test]
1726 fn capacity_rejection_expiry_tracks_runtime_sync_configuration() {
1727 let config = ReplicationConfig {
1728 neighbor_sync_scope: 9,
1729 neighbor_sync_peer_count: 2,
1730 neighbor_sync_interval_max: Duration::from_secs(10),
1731 neighbor_sync_cooldown: Duration::from_secs(100),
1732 verification_request_timeout: Duration::from_secs(1),
1733 ..ReplicationConfig::default()
1734 };
1735
1736 // Five batches take 50s and their nine request budgets take 9s, so
1737 // the 100s cooldown dominates; one 10s cadence interval is slack.
1738 assert_eq!(config.capacity_rejected_max_age(), Duration::from_secs(110));
1739 }
1740
1741 #[test]
1742 fn audit_tick_interval_inverted_rejected() {
1743 let config = ReplicationConfig {
1744 audit_tick_interval_min: Duration::from_secs(100),
1745 audit_tick_interval_max: Duration::from_secs(50),
1746 ..ReplicationConfig::default()
1747 };
1748 assert!(config.validate().is_err());
1749 }
1750
1751 #[test]
1752 fn self_lookup_interval_inverted_rejected() {
1753 let config = ReplicationConfig {
1754 self_lookup_interval_min: Duration::from_secs(100),
1755 self_lookup_interval_max: Duration::from_secs(50),
1756 ..ReplicationConfig::default()
1757 };
1758 assert!(config.validate().is_err());
1759 }
1760
1761 #[test]
1762 fn neighbor_sync_peer_count_zero_rejected() {
1763 let config = ReplicationConfig {
1764 neighbor_sync_peer_count: 0,
1765 ..ReplicationConfig::default()
1766 };
1767 assert!(config.validate().is_err());
1768 }
1769
1770 #[test]
1771 fn neighbor_sync_scope_exceeding_k_bucket_size_rejected() {
1772 let config = ReplicationConfig {
1773 neighbor_sync_scope: K_BUCKET_SIZE + 1,
1774 ..ReplicationConfig::default()
1775 };
1776 assert!(config.validate().is_err());
1777 }
1778
1779 #[test]
1780 fn audit_sample_count_scales_with_sqrt() {
1781 // Empty store
1782 assert_eq!(ReplicationConfig::audit_sample_count(0), 0);
1783
1784 // Single key
1785 assert_eq!(ReplicationConfig::audit_sample_count(1), 1);
1786
1787 // Small stores: sqrt(3)=1
1788 assert_eq!(ReplicationConfig::audit_sample_count(3), 1);
1789
1790 // sqrt scaling
1791 assert_eq!(ReplicationConfig::audit_sample_count(4), 2);
1792 assert_eq!(ReplicationConfig::audit_sample_count(25), 5);
1793 assert_eq!(ReplicationConfig::audit_sample_count(100), 10);
1794 assert_eq!(ReplicationConfig::audit_sample_count(1_000), 31);
1795 assert_eq!(ReplicationConfig::audit_sample_count(7_000), 83);
1796 assert_eq!(ReplicationConfig::audit_sample_count(10_000), 100);
1797 assert_eq!(ReplicationConfig::audit_sample_count(1_000_000), 1_000);
1798 }
1799
1800 #[test]
1801 fn responsible_audit_key_limit_matches_audit_sample_count() {
1802 for stored_keys in [0, 1, 3, 4, 25, 100, 1_000, 7_000, 10_000, 1_000_000] {
1803 assert_eq!(
1804 ReplicationConfig::responsible_audit_key_limit(stored_keys),
1805 ReplicationConfig::audit_sample_count(stored_keys),
1806 "responsible audit sender limit must stay identical to audit sample count"
1807 );
1808 }
1809 }
1810
1811 #[test]
1812 fn max_incoming_audit_keys_scales_dynamically() {
1813 // Empty store: at least 1 key accepted.
1814 assert_eq!(ReplicationConfig::max_incoming_audit_keys(0), 1);
1815
1816 // 1 chunk: 2 * responsible_audit_key_limit(1) = 2.
1817 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1), 2);
1818
1819 // 100 chunks: 2 * responsible_audit_key_limit(100) = 20.
1820 assert_eq!(ReplicationConfig::max_incoming_audit_keys(100), 20);
1821
1822 // 1M chunks: 2 * responsible_audit_key_limit(1_000_000) = 2_000.
1823 assert_eq!(ReplicationConfig::max_incoming_audit_keys(1_000_000), 2_000);
1824
1825 // 5M chunks: 2 * responsible_audit_key_limit(5_000_000) = 4_472.
1826 assert_eq!(ReplicationConfig::max_incoming_audit_keys(5_000_000), 4_472);
1827 }
1828
1829 #[test]
1830 fn quorum_needed_uses_smaller_of_threshold_and_majority() {
1831 let config = ReplicationConfig::default();
1832
1833 // With 7 targets: majority = 7/2+1 = 4, threshold = 4 → min = 4
1834 assert_eq!(config.quorum_needed(7), 4);
1835
1836 // With 3 targets: majority = 3/2+1 = 2, threshold = 4 → min = 2
1837 assert_eq!(config.quorum_needed(3), 2);
1838
1839 // With 0 targets: quorum is impossible — returns 0
1840 assert_eq!(config.quorum_needed(0), 0);
1841
1842 // With 100 targets: majority = 51, threshold = 4 → min = 4
1843 assert_eq!(config.quorum_needed(100), 4);
1844 }
1845
1846 #[test]
1847 fn confirm_needed_is_strict_majority() {
1848 assert_eq!(ReplicationConfig::confirm_needed(1), 1);
1849 assert_eq!(ReplicationConfig::confirm_needed(2), 2);
1850 assert_eq!(ReplicationConfig::confirm_needed(3), 2);
1851 assert_eq!(ReplicationConfig::confirm_needed(4), 3);
1852 assert_eq!(ReplicationConfig::confirm_needed(20), 11);
1853 }
1854
1855 /// The edge is a proportion of the group, not a fixed four peers.
1856 ///
1857 /// A fixed four is a fifth of the production width but four fifths of a
1858 /// configured width of five, which collapsed the voting core to one peer.
1859 #[test]
1860 fn flex_edge_scales_with_the_configured_group() {
1861 // Production width is unchanged: 20 / 5 == PAID_LIST_FLEX_EDGE_COUNT.
1862 assert_eq!(
1863 ReplicationConfig::paid_list_flex_edge_count(
1864 PAID_LIST_CLOSE_GROUP_SIZE,
1865 PAID_LIST_CLOSE_GROUP_SIZE
1866 ),
1867 PAID_LIST_FLEX_EDGE_COUNT,
1868 );
1869
1870 // Small widths keep a majority-sized core rather than a single peer.
1871 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(5, 5), 1);
1872 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(10, 10), 2);
1873 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(15, 15), 3);
1874
1875 // Never more than the ceiling, however wide the group is configured.
1876 assert_eq!(
1877 ReplicationConfig::paid_list_flex_edge_count(100, 100),
1878 PAID_LIST_FLEX_EDGE_COUNT,
1879 );
1880
1881 // An undersized group keeps its ordinary strict majority.
1882 assert_eq!(ReplicationConfig::paid_list_flex_edge_count(19, 20), 0);
1883 }
1884
1885 /// A shrunken denominator must never make one voter decisive.
1886 #[test]
1887 fn paid_confirm_needed_applies_an_absolute_floor() {
1888 // The floor binds where the discounted majority would be trivial.
1889 assert_eq!(
1890 ReplicationConfig::paid_confirm_needed(1, 5),
1891 PAID_LIST_ABSOLUTE_CONFIRM_FLOOR
1892 );
1893 assert_eq!(
1894 ReplicationConfig::paid_confirm_needed(2, 5),
1895 PAID_LIST_ABSOLUTE_CONFIRM_FLOOR
1896 );
1897
1898 // Above the floor the strict majority governs, unchanged.
1899 assert_eq!(ReplicationConfig::paid_confirm_needed(16, 20), 9);
1900 assert_eq!(ReplicationConfig::paid_confirm_needed(20, 20), 11);
1901
1902 // The floor never demands more confirmations than there are peers.
1903 assert_eq!(ReplicationConfig::paid_confirm_needed(1, 1), 1);
1904 assert_eq!(ReplicationConfig::paid_confirm_needed(2, 2), 2);
1905 }
1906
1907 /// The reviewed collapse: at a configured width of five, four fixed edge
1908 /// voters left a core of one, so a single `Confirmed` authorized the key.
1909 #[test]
1910 fn small_configured_group_cannot_authorize_on_one_vote() {
1911 const SMALL_GROUP: usize = 5;
1912
1913 let edge = ReplicationConfig::paid_list_flex_edge_count(SMALL_GROUP, SMALL_GROUP);
1914 let core = SMALL_GROUP - edge;
1915 assert!(
1916 core > 1,
1917 "the voting core must not collapse to a single peer"
1918 );
1919 assert!(
1920 ReplicationConfig::paid_confirm_needed(core, SMALL_GROUP) > 1,
1921 "a lone confirmation must not authorize a key"
1922 );
1923 }
1924
1925 #[test]
1926 fn random_intervals_within_bounds() {
1927 let config = ReplicationConfig::default();
1928
1929 // Run several iterations to exercise randomness.
1930 let iterations = 50;
1931 for _ in 0..iterations {
1932 let ns = config.random_neighbor_sync_interval();
1933 assert!(ns >= config.neighbor_sync_interval_min);
1934 assert!(ns <= config.neighbor_sync_interval_max);
1935
1936 let at = config.random_audit_tick_interval();
1937 assert!(at >= config.audit_tick_interval_min);
1938 assert!(at <= config.audit_tick_interval_max);
1939
1940 let sl = config.random_self_lookup_interval();
1941 assert!(sl >= config.self_lookup_interval_min);
1942 assert!(sl <= config.self_lookup_interval_max);
1943 }
1944 }
1945
1946 #[test]
1947 fn random_interval_equal_bounds_is_deterministic() {
1948 let fixed = Duration::from_secs(42);
1949 let config = ReplicationConfig {
1950 neighbor_sync_interval_min: fixed,
1951 neighbor_sync_interval_max: fixed,
1952 ..ReplicationConfig::default()
1953 };
1954 assert_eq!(config.random_neighbor_sync_interval(), fixed);
1955 }
1956
1957 // -----------------------------------------------------------------------
1958 // Section 18 scenarios
1959 // -----------------------------------------------------------------------
1960
1961 /// Scenario 18: Invalid runtime config is rejected by `validate()`.
1962 #[test]
1963 fn scenario_18_invalid_config_rejected() {
1964 // quorum_threshold > close_group_size -> validation fails.
1965 let config = ReplicationConfig {
1966 quorum_threshold: 10,
1967 close_group_size: 7,
1968 ..ReplicationConfig::default()
1969 };
1970 let err = config.validate().unwrap_err();
1971 assert!(
1972 err.contains("quorum_threshold"),
1973 "error should mention quorum_threshold: {err}"
1974 );
1975
1976 // close_group_size = 0 -> validation fails.
1977 let config = ReplicationConfig {
1978 close_group_size: 0,
1979 ..ReplicationConfig::default()
1980 };
1981 let err = config.validate().unwrap_err();
1982 assert!(
1983 err.contains("close_group_size"),
1984 "error should mention close_group_size: {err}"
1985 );
1986
1987 // neighbor_sync interval min > max -> validation fails.
1988 let config = ReplicationConfig {
1989 neighbor_sync_interval_min: Duration::from_secs(200),
1990 neighbor_sync_interval_max: Duration::from_secs(100),
1991 ..ReplicationConfig::default()
1992 };
1993 let err = config.validate().unwrap_err();
1994 assert!(
1995 err.contains("neighbor_sync_interval"),
1996 "error should mention neighbor_sync_interval: {err}"
1997 );
1998
1999 // self_lookup interval min > max -> validation fails.
2000 let config = ReplicationConfig {
2001 self_lookup_interval_min: Duration::from_secs(999),
2002 self_lookup_interval_max: Duration::from_secs(1),
2003 ..ReplicationConfig::default()
2004 };
2005 let err = config.validate().unwrap_err();
2006 assert!(
2007 err.contains("self_lookup_interval"),
2008 "error should mention self_lookup_interval: {err}"
2009 );
2010
2011 // audit_tick interval min > max -> validation fails.
2012 let config = ReplicationConfig {
2013 audit_tick_interval_min: Duration::from_secs(500),
2014 audit_tick_interval_max: Duration::from_secs(10),
2015 ..ReplicationConfig::default()
2016 };
2017 let err = config.validate().unwrap_err();
2018 assert!(
2019 err.contains("audit_tick_interval"),
2020 "error should mention audit_tick_interval: {err}"
2021 );
2022 }
2023
2024 /// Scenario 26: Dynamic paid-list threshold for undersized set.
2025 /// With PaidGroupSize=8, `ConfirmNeeded` = floor(8/2)+1 = 5.
2026 #[test]
2027 fn scenario_26_dynamic_paid_threshold_undersized() {
2028 assert_eq!(ReplicationConfig::confirm_needed(8), 5, "floor(8/2)+1 = 5");
2029
2030 // Additional boundary checks for small paid groups.
2031 assert_eq!(
2032 ReplicationConfig::confirm_needed(1),
2033 1,
2034 "single peer requires 1 confirmation"
2035 );
2036 assert_eq!(
2037 ReplicationConfig::confirm_needed(2),
2038 2,
2039 "2 peers require 2 confirmations"
2040 );
2041 assert_eq!(
2042 ReplicationConfig::confirm_needed(3),
2043 2,
2044 "3 peers require 2 confirmations"
2045 );
2046 assert_eq!(
2047 ReplicationConfig::confirm_needed(0),
2048 1,
2049 "0 peers yields floor(0/2)+1 = 1 (degenerate case)"
2050 );
2051 }
2052
2053 /// Scenario 31: Consecutive audit ticks occur on randomized intervals
2054 /// bounded by the configured `[audit_tick_interval_min, audit_tick_interval_max]`
2055 /// window.
2056 #[test]
2057 fn scenario_31_audit_cadence_within_jitter_bounds() {
2058 let config = ReplicationConfig {
2059 audit_tick_interval_min: Duration::from_mins(10),
2060 audit_tick_interval_max: Duration::from_mins(20),
2061 ..ReplicationConfig::default()
2062 };
2063
2064 // Sample many intervals and verify each is within bounds.
2065 let iterations = 100;
2066 let mut saw_different = false;
2067 let mut prev = Duration::ZERO;
2068
2069 for _ in 0..iterations {
2070 let interval = config.random_audit_tick_interval();
2071 assert!(
2072 interval >= config.audit_tick_interval_min,
2073 "interval {interval:?} below min {:?}",
2074 config.audit_tick_interval_min,
2075 );
2076 assert!(
2077 interval <= config.audit_tick_interval_max,
2078 "interval {interval:?} above max {:?}",
2079 config.audit_tick_interval_max,
2080 );
2081 if interval != prev && prev != Duration::ZERO {
2082 saw_different = true;
2083 }
2084 prev = interval;
2085 }
2086
2087 // With 100 samples from a 10-minute range, at least two should differ
2088 // (probabilistically near-certain).
2089 assert!(
2090 saw_different,
2091 "audit intervals should exhibit randomized jitter across samples"
2092 );
2093 }
2094
2095 /// The capacity stand-down has to be an order of magnitude above the retry
2096 /// it replaces and still below the life of the entry it defers.
2097 ///
2098 /// A stand-down only a little above the request timeout would leave the
2099 /// repeat cost the same order as before, which is the cost this change
2100 /// exists to remove. At or past `PENDING_VERIFY_MAX_AGE` every deferral
2101 /// would instead become an eviction, which is a different design with
2102 /// different failure modes: the key would only return on a fresh
2103 /// neighbour-sync hint rather than on its own schedule.
2104 ///
2105 /// What this does not show: that either gate uses the constant. It pins the
2106 /// policy the constant encodes; the e2e proves the gates.
2107 #[test]
2108 fn capacity_blocked_retry_is_an_order_above_the_request_timeout_and_below_the_entry_lifetime() {
2109 assert!(
2110 CAPACITY_BLOCKED_RETRY >= VERIFICATION_REQUEST_TIMEOUT * 10,
2111 "a stand-down near the request timeout leaves the repeat cost unchanged in order"
2112 );
2113 assert!(
2114 CAPACITY_BLOCKED_RETRY < PENDING_VERIFY_MAX_AGE,
2115 "a deferral at or past the entry lifetime is an eviction, not a deferral"
2116 );
2117 }
2118
2119 /// The backoff ceiling sits in the same band, and for the same reasons: far
2120 /// enough above the request timeout to actually cut the repeat cost, far
2121 /// enough below the entry lifetime that a capped retry still gets several
2122 /// looks before stale eviction ends the episode.
2123 #[test]
2124 fn verification_retry_backoff_max_is_between_the_request_timeout_and_the_entry_lifetime() {
2125 assert!(
2126 VERIFICATION_RETRY_BACKOFF_MAX > VERIFICATION_REQUEST_TIMEOUT,
2127 "a ceiling at or below the base delay is not a backoff"
2128 );
2129 assert!(
2130 VERIFICATION_RETRY_BACKOFF_MAX * 4 <= PENDING_VERIFY_MAX_AGE,
2131 "a capped retry must still get several looks inside one entry lifetime"
2132 );
2133 }
2134
2135 #[test]
2136 fn fresh_read_retries_back_off_over_about_a_minute() {
2137 let delays: Vec<Duration> = (1..MAX_FRESH_READ_ATTEMPTS)
2138 .map(fresh_read_retry_delay)
2139 .collect();
2140 let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32]
2141 .into_iter()
2142 .map(Duration::from_secs)
2143 .collect();
2144 assert_eq!(delays, expected);
2145 assert_eq!(
2146 delays.iter().sum::<Duration>(),
2147 Duration::from_secs(63),
2148 "a store-wide read fault shorter than this costs no fresh offers"
2149 );
2150 // Out-of-range inputs saturate rather than panic.
2151 assert_eq!(fresh_read_retry_delay(0), FRESH_READ_RETRY_DELAY);
2152 assert!(
2153 fresh_read_retry_delay(u32::MAX) >= fresh_read_retry_delay(MAX_FRESH_READ_ATTEMPTS)
2154 );
2155 }
2156}