Skip to main content

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