Skip to main content

ant_node/replication/
pruning.rs

1//! Post-cycle responsibility pruning (Section 11).
2//!
3//! On `NeighborSyncCycleComplete`: prune stored records and `PaidForList`
4//! entries that have been continuously out of range for at least
5//! `PRUNE_HYSTERESIS_DURATION`.
6//!
7//! # Pressure-gated retention (ADR-0028)
8//!
9//! Being a candidate makes a stored record *eligible* to be erased, never due.
10//! While the partition holding the record store has room, every candidate is
11//! retained and served, and no prune-confirmation audit is sent: none could
12//! lead to a deletion. Under disk pressure (see [`crate::replication::retention`])
13//! candidates are audited and erased farthest from this node first, records
14//! whose proofs failed in the current spell of pressure last, and the pass
15//! measures free space again before each deletion and stops once the pressure
16//! has ended.
17//!
18//! `PaidForList` entries are not part of this: a retained record keeps the entry
19//! that authorises its repair. They are evicted only once the list passes
20//! `paid_list_evict_start_entries`, whatever the disk, to make room for new
21//! keys. Entries far outside this node's range go first, and neither entries
22//! near it nor those of records it still stores go at all.
23//!
24//! # Stored-record prune lifecycle
25//!
26//! Each stored record is classified per pass against the current local
27//! routing table:
28//!
29//! - `InRange`: self is within the storage-retention width
30//!   (`close_group_size + STORAGE_ADMISSION_MARGIN`, 9 at production
31//!   parameters); any out-of-range state is cleared once bootstrap has
32//!   drained. Until then the routing table may still be filling, and a node
33//!   that knows few peers looks in range for everything.
34//! - `HysteresisPending`: outside the retention width, but not yet for the
35//!   full `PRUNE_HYSTERESIS_DURATION`. The first-seen timestamp is recorded
36//!   immediately on leaving range — a retained commitment vetoes DELETION,
37//!   never the start of this clock. The timestamp is saved after each pass,
38//!   so a restart doesn't restart the clock (see
39//!   `replication::out_of_range_clocks`).
40//! - `Candidate`: continuously outside the retention width for the full
41//!   hysteresis. Candidacy is unconditional: it never depends on repair-hint
42//!   proofs, bootstrap state, audit budget, or prior neighbor-sync contact.
43//! - `HeldByCommitment` / `BootstrapDeferred` / `Unauditable`: candidate
44//!   deferrals. They defer deletion, but never remove candidacy or restart
45//!   the hysteresis clock. The request/candidate budget is a separate, later
46//!   deferral applied after classification (not a disposition variant) so
47//!   whole proof sets are either scheduled or deferred as a unit.
48//! - `AuditFailed`: an audited candidate whose current strict close group
49//!   returned fewer than the required positive possession proofs
50//!   (`prune_proofs_needed`, 6 of 7 at production parameters). The record
51//!   and its first-seen timestamp are retained and retried on later passes.
52//! - `Pruned`: deleted after immediately re-passing the applicable checks
53//!   against the then-current routing table.
54//!
55//! Distance alone never authorises deletion. However far outside the group
56//! self has moved, a candidate is deleted only once the current strict close
57//! group proves possession: a local routing-table view says which peers are
58//! closer, not that any of them holds the bytes.
59//!
60//! Prune-confirmation audits challenge the CURRENT strict closest
61//! `close_group_size` peers to the key, taken directly from the local
62//! routing table — never filtered through `RepairProofs` or prior
63//! neighbor-sync hints. The repair-proof maturity gate remains a
64//! prerequisite for the responsible-chunk storage audit (see
65//! `audit_tick_with_repair_proofs`), which is a different mechanism with a
66//! different threat model.
67
68use std::collections::{HashMap, HashSet};
69use std::sync::Arc;
70use std::time::{Duration, Instant, SystemTime};
71
72use crate::logging::{debug, info, warn};
73
74use futures::{stream, StreamExt};
75use rand::Rng;
76use saorsa_core::identity::PeerId;
77use saorsa_core::P2PNode;
78use tokio::sync::RwLock;
79
80use crate::ant_protocol::XorName;
81use crate::replication::audit_coordinator::AuditChallengeCoordinator;
82use crate::replication::audit_metrics::{self, AuditFailureClass, AuditType};
83use crate::replication::commitment_state::ResponderCommitmentState;
84use crate::replication::config::{
85    storage_admission_width, ReplicationConfig, AUDIT_FAILURE_TRUST_WEIGHT,
86    MAX_PAID_EVICTIONS_PER_PASS, MAX_PRUNE_AUDIT_CANDIDATES_PER_PASS,
87    MAX_PRUNE_AUDIT_REQUESTS_PER_PASS, REPLICATION_PROTOCOL_ID,
88};
89use crate::replication::neighbor_sync::paid_near_bits;
90use crate::replication::out_of_range_clocks::elapsed;
91use crate::replication::paid_list::PaidList;
92use crate::replication::protocol::{
93    compute_audit_digest, AuditChallenge, AuditResponse, ReplicationMessage,
94    ReplicationMessageBody, ABSENT_KEY_DIGEST,
95};
96use crate::replication::retention::{DiskPressure, RecordKind};
97use crate::replication::types::{BootstrapClaimObservation, NeighborSyncState, RepairProofs};
98use crate::storage::ChunkStore;
99
100// `RepairProofs` remains in the prune-pass context only so records deleted by
101// pruning also drop their (audit-path) repair-proof entries; it plays no part
102// in prune candidacy or prune-audit target selection.
103
104use super::REPLICATION_TRUST_WEIGHT;
105
106const MAX_CONCURRENT_PRUNE_AUDIT_CHALLENGES: usize = 32;
107
108// ---------------------------------------------------------------------------
109// Result type
110// ---------------------------------------------------------------------------
111
112/// Summary of a prune pass.
113#[derive(Debug, Default)]
114pub struct PruneResult {
115    /// Total stored records scanned.
116    pub records_total: usize,
117    /// Number of records for which self is within the storage-retention width.
118    pub records_in_range: usize,
119    /// Number of records deleted from storage.
120    pub records_pruned: usize,
121    /// Number of records with out-of-range timestamp newly set.
122    pub records_marked_out_of_range: usize,
123    /// Number of records with out-of-range timestamp cleared (back in range).
124    pub records_cleared: usize,
125    /// Out-of-range records still inside the hysteresis window.
126    pub records_hysteresis_pending: usize,
127    /// Records continuously out of range for the full hysteresis (candidates),
128    /// regardless of whether their audit could be scheduled this pass.
129    pub records_candidates: usize,
130    /// Candidates whose deletion (and audit) is vetoed by a retained
131    /// recently-gossiped commitment.
132    pub records_held_by_commitment: usize,
133    /// Candidates whose audit is deferred until bootstrap drains.
134    pub records_bootstrap_deferred: usize,
135    /// Candidates whose audit is deferred by the per-pass challenge budget.
136    pub records_budget_deferred: usize,
137    /// Candidates audited against their current strict close group this pass.
138    pub records_audits_attempted: usize,
139    /// Audited candidates confirmed below the proof threshold (retained).
140    pub records_audit_below_threshold: usize,
141    /// Whether the partition holding the record store was under pressure.
142    pub disk_pressure: bool,
143    /// Candidates kept this pass, for any reason: room on the disk, a
144    /// deferral, a failed proof, or the pressure ending before their turn.
145    pub records_retained: usize,
146    /// Number of `PaidForList` entries evicted.
147    pub paid_entries_evicted: usize,
148}
149
150/// Shared dependencies and switches for one prune pass.
151pub struct PrunePassContext<'a> {
152    /// Local peer id.
153    pub self_id: &'a PeerId,
154    /// Local record storage.
155    pub storage: &'a Arc<ChunkStore>,
156    /// Persistent paid-list state.
157    pub paid_list: &'a Arc<PaidList>,
158    /// P2P node used for routing lookups and prune-confirmation audits.
159    pub p2p_node: &'a Arc<P2PNode>,
160    /// Replication configuration.
161    pub config: &'a ReplicationConfig,
162    /// Neighbor-sync state, including bootstrap claims.
163    pub sync_state: &'a Arc<RwLock<NeighborSyncState>>,
164    /// Repair-proof table, consulted ONLY to drop a deleted record's proof
165    /// entries. Prune candidacy and prune-audit target selection never read it.
166    pub repair_proofs: &'a Arc<RwLock<RepairProofs>>,
167    /// Whether bootstrap has drained enough to permit pruning this pass.
168    /// This gates the remote confirmation audits every deletion requires.
169    pub allow_remote_prune_audits: bool,
170    /// Responder commitment state, used to veto deleting a chunk still held
171    /// under a recently-gossiped commitment (so the storage-commitment audit's
172    /// round-2 byte challenge cannot false-positive an honest node). `None` on
173    /// the legacy/test-only prune path, which keeps the pre-retention behavior.
174    pub commitment_state: Option<&'a Arc<ResponderCommitmentState>>,
175    /// Shared outbound limiter for digest `AuditChallenge`s.
176    pub audit_challenge_coordinator: &'a Arc<AuditChallengeCoordinator>,
177    /// The node's disk-pressure state, shared with the pointer prune pass.
178    /// Candidates are erased only while it reports pressure (ADR-0028).
179    pub disk_pressure: &'a DiskPressure,
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183enum PruneAuditStatus {
184    Proven,
185    Failed,
186    /// The responder refused the challenge (capacity or routing). Never a
187    /// possession signal; treated as an attributable failure under the
188    /// assumed close-group store spread (see [`peer_proves_records`]).
189    Rejected,
190    Bootstrapping,
191}
192
193enum PruneAuditChallengeResult {
194    Response(Box<ReplicationMessage>),
195    NoResponse(AuditFailureClass),
196    MalformedResponse,
197}
198
199#[derive(Debug, Default)]
200struct RecordPruneStats {
201    in_range: usize,
202    marked: usize,
203    cleared: usize,
204    hysteresis_pending: usize,
205    candidates: usize,
206    held_by_commitment: usize,
207    bootstrap_deferred: usize,
208    budget_deferred: usize,
209    audits_attempted: usize,
210    audit_requests: usize,
211    audit_below_threshold: usize,
212    disk_pressure: bool,
213    retained: usize,
214    pruned: usize,
215}
216
217/// A prune candidate scheduled for a prune-confirmation audit this pass.
218/// `target_peers` is the current strict close group for the key (self
219/// excluded), taken directly from the local routing table.
220#[derive(Debug, Clone)]
221struct RecordPruneCandidate {
222    key: XorName,
223    target_peers: Vec<PeerId>,
224}
225
226struct RecordPruneLookupGroups {
227    retention: Vec<PeerId>,
228    strict: Vec<PeerId>,
229}
230
231struct RecordPruneKeyOutcome {
232    /// Whether the out-of-range timestamp was newly set for this key.
233    marked: bool,
234    state: RecordPruneKeyState,
235}
236
237/// Per-pass lifecycle classification of one stored record (see module docs).
238enum RecordPruneKeyState {
239    /// Self is within the storage-retention width for this key. `cleared` is
240    /// true when a stale out-of-range timestamp was removed.
241    InRange { cleared: bool },
242    /// Outside the retention width, but not yet for the full hysteresis.
243    HysteresisPending,
244    /// Continuously outside the retention width for at least the hysteresis
245    /// duration. Candidacy is unconditional; the disposition only says how the
246    /// candidate is scheduled this pass.
247    Candidate(PruneCandidateDisposition),
248}
249
250/// How a prune candidate is scheduled within one pass.
251enum PruneCandidateDisposition {
252    /// Still committed under a recently-gossiped commitment: a neighbour can
253    /// pin that root and demand the bytes in a round-2 byte challenge, so
254    /// deletion is vetoed (and the audit skipped) until the key ages out of
255    /// the retention window. Bounded reprieve: the commitment rebuild only
256    /// commits to keys we are still responsible for, so the key drops out of
257    /// the next rebuilt commitment and `is_held` flips false within at most
258    /// `RETAINED_GOSSIPED_COMMITMENTS` gossip rotations.
259    HeldByCommitment,
260    /// Remote prune-confirmation audits are not allowed yet (bootstrap has
261    /// not drained).
262    BootstrapDeferred,
263    /// The current close group has no remote peers to audit; retain
264    /// conservatively.
265    Unauditable,
266    /// Audit the current strict close group this pass.
267    Auditable(RecordPruneCandidate),
268}
269
270/// Outcome of revalidating one candidate immediately before deletion.
271enum PruneRevalidationOutcome {
272    /// Every check re-passed against the current routing table: delete.
273    Delete,
274    /// Self moved back inside the retention width; state cleared, record kept.
275    ClearedBackInRange,
276    /// The hysteresis condition no longer holds (timestamp cleared or reset
277    /// concurrently); record kept.
278    HysteresisPending,
279    /// (Re-)committed under a retained commitment; deletion vetoed.
280    HeldByCommitment,
281    /// Fewer than the required positive proofs from the CURRENT strict close
282    /// group — including when the group's membership changed after the audit
283    /// round, which invalidates stale positive reports. Record kept, retried
284    /// on later passes.
285    AuditFailed,
286    /// The current close group has no remote peers; retain conservatively.
287    Unauditable,
288}
289
290#[derive(Default)]
291struct PruneAuditReportState {
292    audit_failures: RwLock<HashSet<PeerId>>,
293    bootstrap_abuse: RwLock<HashSet<PeerId>>,
294}
295
296#[derive(Clone, Copy)]
297struct PruneAuditContext<'a> {
298    storage: &'a Arc<ChunkStore>,
299    p2p_node: &'a Arc<P2PNode>,
300    config: &'a ReplicationConfig,
301    sync_state: &'a Arc<RwLock<NeighborSyncState>>,
302    audit_challenge_coordinator: &'a Arc<AuditChallengeCoordinator>,
303    report_state: &'a PruneAuditReportState,
304}
305
306// ---------------------------------------------------------------------------
307// Prune pass
308// ---------------------------------------------------------------------------
309
310/// Execute one prune pass (see the module docs for the record lifecycle).
311pub async fn run_prune_pass_with_context(ctx: PrunePassContext<'_>) -> PruneResult {
312    let (stored_count, record_stats) = prune_stored_records(&ctx).await;
313    let (paid_count, paid_evicted) = evict_excess_paid_entries(&ctx).await;
314
315    let result = PruneResult {
316        records_total: stored_count,
317        records_in_range: record_stats.in_range,
318        records_pruned: record_stats.pruned,
319        records_marked_out_of_range: record_stats.marked,
320        records_cleared: record_stats.cleared,
321        records_hysteresis_pending: record_stats.hysteresis_pending,
322        records_candidates: record_stats.candidates,
323        records_held_by_commitment: record_stats.held_by_commitment,
324        records_bootstrap_deferred: record_stats.bootstrap_deferred,
325        records_budget_deferred: record_stats.budget_deferred,
326        records_audits_attempted: record_stats.audits_attempted,
327        records_audit_below_threshold: record_stats.audit_below_threshold,
328        disk_pressure: record_stats.disk_pressure,
329        records_retained: record_stats.retained,
330        paid_entries_evicted: paid_evicted,
331    };
332
333    // One aggregate line per pass: the full lifecycle census (never per-chunk).
334    info!(
335        "Prune pass complete: records total={} in_range={} newly_marked={} cleared={} \
336         hysteresis_pending={} candidates={} held_by_commitment={} bootstrap_deferred={} \
337         disk_pressure={} retained={} budget_deferred={} audits_attempted={} audit_requests={} \
338         audit_below_threshold={} pruned={}; paid total={} evicted={}",
339        result.records_total,
340        result.records_in_range,
341        result.records_marked_out_of_range,
342        result.records_cleared,
343        result.records_hysteresis_pending,
344        result.records_candidates,
345        result.records_held_by_commitment,
346        result.records_bootstrap_deferred,
347        result.disk_pressure,
348        result.records_retained,
349        result.records_budget_deferred,
350        result.records_audits_attempted,
351        record_stats.audit_requests,
352        result.records_audit_below_threshold,
353        result.records_pruned,
354        paid_count,
355        result.paid_entries_evicted,
356    );
357
358    result
359}
360
361async fn prune_stored_records(ctx: &PrunePassContext<'_>) -> (usize, RecordPruneStats) {
362    let stored_keys = match ctx.storage.all_keys().await {
363        Ok(keys) => keys,
364        Err(e) => {
365            warn!("Failed to read stored keys for pruning: {e}");
366            return (0, RecordPruneStats::default());
367        }
368    };
369
370    let now = SystemTime::now();
371    let mut stats = RecordPruneStats::default();
372    let mut audit_candidates = Vec::new();
373    let deps = RecordPruneKeyDeps {
374        self_id: ctx.self_id,
375        paid_list: ctx.paid_list,
376        config: ctx.config,
377        allow_remote_prune_audits: ctx.allow_remote_prune_audits,
378        commitment_state: ctx.commitment_state,
379    };
380
381    for key in &stored_keys {
382        let groups = record_prune_lookup_groups(key, ctx.p2p_node, ctx.config).await;
383
384        let outcome = evaluate_record_prune_key(&deps, key, &groups.retention, &groups.strict, now);
385        if let Some(candidate) = tally_record_prune_outcome(&mut stats, outcome, key) {
386            audit_candidates.push(candidate);
387        }
388    }
389
390    // Saved clocks must not outlive their records.
391    let stored: HashSet<&XorName> = stored_keys.iter().collect();
392    ctx.paid_list
393        .retain_record_out_of_range(|key| stored.contains(key));
394    // Before any audit or deletion, so a restart during those can't bring back
395    // a clock this pass stopped.
396    ctx.paid_list.persist_record_out_of_range().await;
397
398    // A candidate is eligible, not due: with room on the disk it stays, and
399    // no audit is sent, since none could lead to a deletion.
400    if !ctx.disk_pressure.observe_store(ctx.storage) {
401        stats.retained = stats.candidates;
402        return (stored_keys.len(), stats);
403    }
404    stats.disk_pressure = true;
405
406    // The whole order, not a prefix: request budgets may pass over a
407    // candidate, and the next in line should still be considered.
408    let candidate_count = audit_candidates.len();
409    let audit_candidates = ctx.disk_pressure.erasure_order(
410        RecordKind::Chunk,
411        ctx.self_id,
412        audit_candidates,
413        candidate_count,
414        |candidate| candidate.key,
415    );
416    // Batches are sized from the records this node is in range for, not all
417    // it holds: responders size what they accept the same way from their own
418    // stores, and retained records would otherwise make a pruner's batches
419    // too large for a newer peer to accept.
420    let max_keys_per_challenge = ReplicationConfig::responsible_audit_key_limit(stats.in_range);
421    let audit_selection = select_record_prune_audits(
422        &audit_candidates,
423        max_keys_per_challenge,
424        MAX_PRUNE_AUDIT_CANDIDATES_PER_PASS,
425        MAX_PRUNE_AUDIT_REQUESTS_PER_PASS,
426    );
427    stats.budget_deferred = audit_selection.deferred;
428    stats.audits_attempted = audit_selection.candidates.len();
429    stats.audit_requests = audit_selection.request_count;
430
431    let present_by_key = collect_record_prune_proofs(
432        &audit_selection.candidates,
433        stats.in_range,
434        ctx.storage,
435        ctx.p2p_node,
436        ctx.config,
437        ctx.sync_state,
438        ctx.audit_challenge_coordinator,
439    )
440    .await;
441    let (keys_to_delete, revalidated_cleared, audit_below_threshold) =
442        revalidated_record_prune_keys(&audit_selection.candidates, &present_by_key, ctx).await;
443    stats.cleared += revalidated_cleared;
444    stats.audit_below_threshold = audit_below_threshold;
445    stats.pruned = delete_stored_records(&keys_to_delete, ctx).await;
446    stats.retained = stats.candidates.saturating_sub(stats.pruned);
447
448    (stored_keys.len(), stats)
449}
450
451/// Fold one record's per-pass classification into the pass stats. Returns the
452/// auditable candidate when the record was scheduled for a prune audit.
453fn tally_record_prune_outcome(
454    stats: &mut RecordPruneStats,
455    outcome: RecordPruneKeyOutcome,
456    key: &XorName,
457) -> Option<RecordPruneCandidate> {
458    if outcome.marked {
459        stats.marked += 1;
460    }
461    match outcome.state {
462        RecordPruneKeyState::InRange { cleared } => {
463            stats.in_range += 1;
464            if cleared {
465                stats.cleared += 1;
466            }
467            None
468        }
469        RecordPruneKeyState::HysteresisPending => {
470            stats.hysteresis_pending += 1;
471            None
472        }
473        RecordPruneKeyState::Candidate(disposition) => {
474            stats.candidates += 1;
475            match disposition {
476                PruneCandidateDisposition::HeldByCommitment => {
477                    stats.held_by_commitment += 1;
478                    None
479                }
480                PruneCandidateDisposition::BootstrapDeferred => {
481                    stats.bootstrap_deferred += 1;
482                    None
483                }
484                PruneCandidateDisposition::Unauditable => {
485                    debug!(
486                        "Cannot prune-audit {}: current close group has no remote peers",
487                        hex::encode(key)
488                    );
489                    None
490                }
491                PruneCandidateDisposition::Auditable(candidate) => Some(candidate),
492            }
493        }
494    }
495}
496
497/// Current self-inclusive storage-retention group and strict close group for
498/// `key`, from the local routing table, reduced to peer ids.
499async fn record_prune_lookup_groups(
500    key: &XorName,
501    p2p_node: &Arc<P2PNode>,
502    config: &ReplicationConfig,
503) -> RecordPruneLookupGroups {
504    // Closest first, so the strict group is the head of the retention group.
505    let retention: Vec<PeerId> = p2p_node
506        .dht_manager()
507        .find_closest_nodes_local_with_self(key, storage_admission_width(config.close_group_size))
508        .await
509        .iter()
510        .map(|node| node.peer_id)
511        .collect();
512    let strict = retention
513        .iter()
514        .take(config.close_group_size)
515        .copied()
516        .collect();
517    RecordPruneLookupGroups { retention, strict }
518}
519
520/// The subset of [`PrunePassContext`] needed to classify one stored record.
521/// Split out (with routing-table lookups precomputed by the caller) so unit
522/// tests can drive the classification without a live `P2PNode`.
523struct RecordPruneKeyDeps<'a> {
524    self_id: &'a PeerId,
525    paid_list: &'a Arc<PaidList>,
526    config: &'a ReplicationConfig,
527    allow_remote_prune_audits: bool,
528    commitment_state: Option<&'a Arc<ResponderCommitmentState>>,
529}
530
531/// Classify one stored record for this pass (see the module docs).
532///
533/// The out-of-range timestamp is recorded the moment self is outside the
534/// storage-retention width — even while the key is still held by a retained
535/// commitment. Candidacy (past-hysteresis) is unconditional; commitment
536/// retention, bootstrap state, and the audit budget only defer the audit or
537/// veto the deletion.
538fn evaluate_record_prune_key(
539    deps: &RecordPruneKeyDeps<'_>,
540    key: &XorName,
541    storage_admission_peers: &[PeerId],
542    strict_close_peers: &[PeerId],
543    now: SystemTime,
544) -> RecordPruneKeyOutcome {
545    if storage_admission_peers.contains(deps.self_id) {
546        // Until bootstrap has drained the routing table may still be filling,
547        // and a node that knows few peers looks in range for everything. The
548        // clocks restored after a restart have to survive that.
549        let cleared = deps.allow_remote_prune_audits
550            && deps.paid_list.record_out_of_range_since(key).is_some();
551        if cleared {
552            deps.paid_list.clear_record_out_of_range(key);
553        }
554        return RecordPruneKeyOutcome {
555            marked: false,
556            state: RecordPruneKeyState::InRange { cleared },
557        };
558    }
559
560    // Outside the retention width: start (or continue) the hysteresis clock
561    // immediately. A retained commitment vetoes DELETION further down, never
562    // the timer — otherwise commitment retention would postpone when a record
563    // can become a candidate instead of only protecting answerability.
564    let marked = deps.paid_list.record_out_of_range_since(key).is_none();
565    deps.paid_list.set_record_out_of_range(key);
566
567    let Some(first_seen) = deps.paid_list.record_out_of_range_since(key) else {
568        // The timestamp was just set; its absence means a concurrent clear.
569        return RecordPruneKeyOutcome {
570            marked,
571            state: RecordPruneKeyState::HysteresisPending,
572        };
573    };
574    if elapsed(first_seen, now) < deps.config.prune_hysteresis_duration {
575        return RecordPruneKeyOutcome {
576            marked,
577            state: RecordPruneKeyState::HysteresisPending,
578        };
579    }
580
581    RecordPruneKeyOutcome {
582        marked,
583        state: RecordPruneKeyState::Candidate(schedule_prune_candidate(
584            deps,
585            key,
586            strict_close_peers,
587        )),
588    }
589}
590
591/// Decide how a prune candidate is scheduled this pass. Deferrals retain the
592/// record, its first-seen timestamp, and its candidacy.
593///
594/// Audit targets are the CURRENT strict close group from the local routing
595/// table — never filtered through `RepairProofs` or prior neighbor-sync
596/// contact: prune confirmation concerns the peers now closest to the KEY,
597/// while neighbor sync contacts the peers closest to SELF, and nothing
598/// guarantees those sets overlap for an out-of-range key.
599fn schedule_prune_candidate(
600    deps: &RecordPruneKeyDeps<'_>,
601    key: &XorName,
602    strict_close_peers: &[PeerId],
603) -> PruneCandidateDisposition {
604    if let Some(cs) = deps.commitment_state {
605        if cs.is_held(key) {
606            return PruneCandidateDisposition::HeldByCommitment;
607        }
608    }
609
610    if !deps.allow_remote_prune_audits {
611        return PruneCandidateDisposition::BootstrapDeferred;
612    }
613
614    let target_peers = remote_close_group_peers(strict_close_peers, deps.self_id);
615    if target_peers.is_empty() {
616        return PruneCandidateDisposition::Unauditable;
617    }
618
619    PruneCandidateDisposition::Auditable(RecordPruneCandidate {
620        key: *key,
621        target_peers,
622    })
623}
624
625struct RecordPruneAuditSelection {
626    candidates: Vec<RecordPruneCandidate>,
627    deferred: usize,
628    request_count: usize,
629}
630
631/// Select whole candidates, in the order given, while bounding actual batched
632/// network requests.
633///
634/// Adding a candidate consumes another request for a peer only when that
635/// peer's current batch is full. This avoids the old accounting where every
636/// candidate-to-peer edge consumed one unit despite sharing a request.
637fn select_record_prune_audits(
638    candidates: &[RecordPruneCandidate],
639    max_keys_per_challenge: usize,
640    max_candidates: usize,
641    max_requests: usize,
642) -> RecordPruneAuditSelection {
643    let max_keys_per_challenge = max_keys_per_challenge.max(1);
644    let mut selected = Vec::new();
645    let mut keys_by_peer = HashMap::<PeerId, usize>::new();
646    let mut request_count = 0usize;
647    let mut deferred = 0usize;
648
649    for candidate in candidates {
650        if selected.len() >= max_candidates {
651            deferred += 1;
652            continue;
653        }
654
655        let unique_target_peers: HashSet<PeerId> = candidate.target_peers.iter().copied().collect();
656        let additional_requests = unique_target_peers
657            .iter()
658            .filter(|peer| {
659                keys_by_peer.get(peer).copied().unwrap_or_default() % max_keys_per_challenge == 0
660            })
661            .count();
662        if request_count.saturating_add(additional_requests) > max_requests {
663            deferred += 1;
664            continue;
665        }
666
667        for peer in unique_target_peers {
668            *keys_by_peer.entry(peer).or_default() += 1;
669        }
670        request_count += additional_requests;
671        selected.push(candidate.clone());
672    }
673
674    debug_assert_eq!(
675        build_peer_audit_challenges(&selected, max_keys_per_challenge).len(),
676        request_count
677    );
678    RecordPruneAuditSelection {
679        candidates: selected,
680        deferred,
681        request_count,
682    }
683}
684
685/// Evict `PaidForList` entries once the list has passed its threshold, and
686/// return how many entries it now holds and how many went.
687///
688/// Only entries far outside this node's range go, farthest first: with evenly
689/// spread IDs this node has no vote on them. An entry whose record is still stored
690/// stays, since it authorises that record's repair. So does everything while this
691/// node knows too few peers to say what is near.
692async fn evict_excess_paid_entries(ctx: &PrunePassContext<'_>) -> (usize, usize) {
693    let count = match ctx.paid_list.count() {
694        Ok(count) => usize::try_from(count).unwrap_or(usize::MAX),
695        Err(e) => {
696            warn!("Failed to count PaidForList entries: {e}");
697            return (0, 0);
698        }
699    };
700    let excess = count.saturating_sub(ctx.config.paid_list_evict_start_entries);
701    if excess == 0 {
702        return (count, 0);
703    }
704    let near_bits = paid_near_bits(ctx.p2p_node, ctx.config.paid_list_close_group_size).await;
705    let storage = Arc::clone(ctx.storage);
706    let evicted = ctx
707        .paid_list
708        .evict_far(
709            *ctx.self_id.as_bytes(),
710            near_bits,
711            excess.min(MAX_PAID_EVICTIONS_PER_PASS),
712            move |key| storage.exists(key).unwrap_or(true),
713        )
714        .await;
715    match evicted {
716        Ok(evicted) => (count.saturating_sub(evicted), evicted),
717        Err(e) => {
718            warn!("Failed to evict PaidForList entries: {e}");
719            (count, 0)
720        }
721    }
722}
723
724fn remote_close_group_peers(close_group: &[PeerId], self_id: &PeerId) -> Vec<PeerId> {
725    close_group
726        .iter()
727        .filter(|peer| *peer != self_id)
728        .copied()
729        .collect()
730}
731
732/// Erase `keys_to_delete`, in order, while the disk stays under pressure.
733///
734/// Free space is measured again before each erasure: once the pressure has
735/// ended, the rest are kept.
736async fn delete_stored_records(keys_to_delete: &[XorName], ctx: &PrunePassContext<'_>) -> usize {
737    let (storage, paid_list, repair_proofs) = (ctx.storage, ctx.paid_list, ctx.repair_proofs);
738    let mut pruned = 0;
739
740    for (index, key) in keys_to_delete.iter().enumerate() {
741        if !ctx.disk_pressure.observe_store(storage) {
742            debug!(
743                "Disk pressure ended; keeping {} further prune candidates",
744                keys_to_delete.len() - index
745            );
746            break;
747        }
748        if let Err(e) = storage.delete(key).await {
749            warn!("Failed to prune record {}: {e}", hex::encode(key));
750        } else {
751            pruned += 1;
752            paid_list.clear_record_out_of_range(key);
753            repair_proofs.write().await.remove_key(key);
754            debug!("Pruned out-of-range record {}", hex::encode(key));
755        }
756    }
757
758    pruned
759}
760
761/// Collect positive presence reports for prune candidates.
762///
763/// A key is deleted once all but one of the current close group prove
764/// possession ([`prune_proofs_needed`]). Requiring unanimous proofs left
765/// out-of-range records undeletable whenever a single close-group peer
766/// lagged, while the all-but-one threshold still demands more copies than
767/// the storage quorum used elsewhere. Keys below the proof threshold stay
768/// local, and the retained record continues to participate in normal
769/// neighbor-sync repair because replica hint construction walks all locally
770/// stored keys, including out-of-range keys retained by hysteresis.
771async fn collect_record_prune_proofs(
772    candidates: &[RecordPruneCandidate],
773    local_stored_key_count: usize,
774    storage: &Arc<ChunkStore>,
775    p2p_node: &Arc<P2PNode>,
776    config: &ReplicationConfig,
777    sync_state: &Arc<RwLock<NeighborSyncState>>,
778    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
779) -> HashMap<XorName, HashSet<PeerId>> {
780    if candidates.is_empty() {
781        return HashMap::new();
782    }
783
784    let max_keys_per_challenge =
785        ReplicationConfig::responsible_audit_key_limit(local_stored_key_count);
786    let challenges = build_peer_audit_challenges(candidates, max_keys_per_challenge);
787    let report_state = PruneAuditReportState::default();
788    let audit_context = PruneAuditContext {
789        storage,
790        p2p_node,
791        config,
792        sync_state,
793        audit_challenge_coordinator,
794        report_state: &report_state,
795    };
796    let mut requests = stream::iter(challenges)
797        .map(|(peer, keys)| peer_proves_records(peer, keys, audit_context))
798        .buffer_unordered(MAX_CONCURRENT_PRUNE_AUDIT_CHALLENGES);
799
800    let mut present_by_key = HashMap::<XorName, HashSet<PeerId>>::new();
801    while let Some(proofs) = requests.next().await {
802        for (peer, key) in proofs {
803            present_by_key.entry(key).or_default().insert(peer);
804        }
805    }
806
807    present_by_key
808}
809
810async fn stored_record_still_exists(key: &XorName, storage: &Arc<ChunkStore>) -> bool {
811    match storage.get_raw(key).await {
812        Ok(Some(_)) => true,
813        Ok(None) => false,
814        Err(error) => {
815            warn!(
816                "Cannot revalidate prune candidate {}: failed to read local record: {error}",
817                hex::encode(key)
818            );
819            false
820        }
821    }
822}
823
824/// Re-check every audited candidate against current local state immediately
825/// before deletion, returning the keys to delete, the number of out-of-range
826/// timestamps cleared (self back in range), and the number of candidates
827/// confirmed below the proof threshold.
828///
829/// The audit round takes time; the routing table may have changed underneath
830/// it, including self moving back into range or the strict close group
831/// changing membership. Positive reports only count from peers still in the
832/// CURRENT strict close group, against a threshold computed from that
833/// current group.
834async fn revalidated_record_prune_keys(
835    candidates: &[RecordPruneCandidate],
836    present_by_key: &HashMap<XorName, HashSet<PeerId>>,
837    ctx: &PrunePassContext<'_>,
838) -> (Vec<XorName>, usize, usize) {
839    let mut keys_to_delete = Vec::new();
840    let mut cleared = 0;
841    let mut audit_below_threshold = 0;
842    let now = SystemTime::now();
843
844    for candidate in candidates {
845        if !stored_record_still_exists(&candidate.key, ctx.storage).await {
846            continue;
847        }
848        let groups = record_prune_lookup_groups(&candidate.key, ctx.p2p_node, ctx.config).await;
849        let held_by_commitment = ctx
850            .commitment_state
851            .is_some_and(|cs| cs.is_held(&candidate.key));
852        let inputs = PruneRevalidationInputs {
853            self_id: ctx.self_id,
854            first_seen: ctx.paid_list.record_out_of_range_since(&candidate.key),
855            prune_hysteresis_duration: ctx.config.prune_hysteresis_duration,
856            held_by_commitment,
857            storage_admission_peers: &groups.retention,
858            strict_close_peers: &groups.strict,
859            now,
860        };
861
862        match revalidate_record_prune_candidate(candidate, present_by_key, &inputs) {
863            PruneRevalidationOutcome::Delete => keys_to_delete.push(candidate.key),
864            PruneRevalidationOutcome::ClearedBackInRange => {
865                ctx.paid_list.clear_record_out_of_range(&candidate.key);
866                cleared += 1;
867            }
868            PruneRevalidationOutcome::AuditFailed => {
869                audit_below_threshold += 1;
870                ctx.disk_pressure.demote(RecordKind::Chunk, candidate.key);
871                debug!(
872                    "Deferring prune for {} until all but one of the current close group \
873                     report it",
874                    hex::encode(candidate.key)
875                );
876            }
877            PruneRevalidationOutcome::HysteresisPending
878            | PruneRevalidationOutcome::HeldByCommitment => {}
879            PruneRevalidationOutcome::Unauditable => {
880                debug!(
881                    "Cannot prune {}: current close group has no remote peers",
882                    hex::encode(candidate.key)
883                );
884            }
885        }
886    }
887
888    (keys_to_delete, cleared, audit_below_threshold)
889}
890
891/// Inputs for revalidating one audited candidate immediately before deletion.
892struct PruneRevalidationInputs<'a> {
893    self_id: &'a PeerId,
894    /// The candidate's out-of-range first-seen timestamp as it stands NOW.
895    first_seen: Option<SystemTime>,
896    prune_hysteresis_duration: Duration,
897    /// Whether a retained commitment holds the key NOW (TOCTOU re-check: a
898    /// rotation/gossip may have re-committed it since candidate selection).
899    held_by_commitment: bool,
900    /// Current self-inclusive storage-retention group for the key.
901    storage_admission_peers: &'a [PeerId],
902    /// Current strict close group for the key.
903    strict_close_peers: &'a [PeerId],
904    now: SystemTime,
905}
906
907/// Pure deletion decision for one audited candidate (see
908/// [`revalidated_record_prune_keys`]). Deletion requires that, against the
909/// CURRENT routing table: self is still outside the storage-retention width,
910/// the hysteresis still holds, no retained commitment holds the key, and at
911/// least [`prune_proofs_needed`] of the current strict close group supplied
912/// positive possession proofs. Stale positive reports from peers no longer in
913/// the current close group never count, and no topology — however far outside
914/// the group self has moved — substitutes for the proofs.
915fn revalidate_record_prune_candidate(
916    candidate: &RecordPruneCandidate,
917    present_by_key: &HashMap<XorName, HashSet<PeerId>>,
918    inputs: &PruneRevalidationInputs<'_>,
919) -> PruneRevalidationOutcome {
920    if inputs.storage_admission_peers.contains(inputs.self_id) {
921        return PruneRevalidationOutcome::ClearedBackInRange;
922    }
923
924    if inputs.held_by_commitment {
925        return PruneRevalidationOutcome::HeldByCommitment;
926    }
927
928    let Some(first_seen) = inputs.first_seen else {
929        return PruneRevalidationOutcome::HysteresisPending;
930    };
931    if elapsed(first_seen, inputs.now) < inputs.prune_hysteresis_duration {
932        return PruneRevalidationOutcome::HysteresisPending;
933    }
934
935    let current_target_peers = remote_close_group_peers(inputs.strict_close_peers, inputs.self_id);
936    if current_target_peers.is_empty() {
937        return PruneRevalidationOutcome::Unauditable;
938    }
939
940    let proofs_needed = prune_proofs_needed(current_target_peers.len());
941    if target_peers_reported_present(
942        &candidate.key,
943        &current_target_peers,
944        present_by_key,
945        proofs_needed,
946    ) {
947        PruneRevalidationOutcome::Delete
948    } else {
949        PruneRevalidationOutcome::AuditFailed
950    }
951}
952
953fn build_peer_audit_challenges(
954    candidates: &[RecordPruneCandidate],
955    max_keys_per_challenge: usize,
956) -> Vec<(PeerId, Vec<XorName>)> {
957    let max_keys_per_challenge = max_keys_per_challenge.max(1);
958    let mut keys_by_peer: HashMap<PeerId, Vec<XorName>> = HashMap::new();
959    for candidate in candidates {
960        for peer in &candidate.target_peers {
961            keys_by_peer.entry(*peer).or_default().push(candidate.key);
962        }
963    }
964
965    let mut challenges = Vec::new();
966    for (peer, mut keys) in keys_by_peer {
967        keys.sort_unstable();
968        keys.dedup();
969        challenges.extend(
970            keys.chunks(max_keys_per_challenge)
971                .map(|chunk| (peer, chunk.to_vec())),
972        );
973    }
974    challenges
975}
976
977#[cfg(test)]
978fn confirmed_keys_from_presence(
979    candidates: &[RecordPruneCandidate],
980    present_by_key: &HashMap<XorName, HashSet<PeerId>>,
981    proofs_needed: usize,
982) -> Vec<XorName> {
983    candidates
984        .iter()
985        .filter(|candidate| {
986            target_peers_reported_present(
987                &candidate.key,
988                &candidate.target_peers,
989                present_by_key,
990                proofs_needed,
991            )
992        })
993        .map(|candidate| candidate.key)
994        .collect()
995}
996
997/// Proofs required before deleting an out-of-range record: all but one of
998/// the close group (6 of 7 at production parameters).
999///
1000/// Stricter than the storage quorum (`QuorumNeeded`) because pruning only
1001/// runs after `PRUNE_HYSTERESIS_DURATION` out of range, by which time many
1002/// sync cycles should have replicated the record across the whole close
1003/// group. Tolerating exactly one lagging peer keeps a single absent peer
1004/// from vetoing deletion forever without accepting under-replication.
1005/// Groups of one or two peers require every proof: tolerating a miss there
1006/// would allow deletion on a single attestation.
1007pub(crate) fn prune_proofs_needed(group_size: usize) -> usize {
1008    if group_size <= 2 {
1009        group_size
1010    } else {
1011        group_size - 1
1012    }
1013}
1014
1015/// Whether enough target peers supplied positive evidence to allow deletion.
1016///
1017/// `proofs_needed == 0` means confirmation is impossible (no targets), not
1018/// trivially met.
1019pub(crate) fn target_peers_reported_present(
1020    key: &XorName,
1021    target_peers: &[PeerId],
1022    present_by_key: &HashMap<XorName, HashSet<PeerId>>,
1023    proofs_needed: usize,
1024) -> bool {
1025    if proofs_needed == 0 {
1026        return false;
1027    }
1028    let Some(present_peers) = present_by_key.get(key) else {
1029        return false;
1030    };
1031    // Count distinct proven peers: iterating the present set keeps a
1032    // duplicated entry in `target_peers` from being counted twice.
1033    let proven = present_peers
1034        .iter()
1035        .filter(|peer| target_peers.contains(peer))
1036        .count();
1037    proven >= proofs_needed
1038}
1039
1040/// Challenge a peer to prove it holds the exact record bytes for one or more keys.
1041///
1042/// Batching by peer prevents a prune pass from firing many simultaneous one-key
1043/// `AuditChallenge`s at the same target. The responder already supports
1044/// multi-key challenges, so we preserve per-key proof accounting while reducing
1045/// per-peer request bursts.
1046///
1047/// A size rejection is not accommodated: the responder's
1048/// `max_incoming_audit_keys` already grants a 2x margin over its own sender
1049/// limit, so an honestly-sized peer only rejects our batch once the close-group
1050/// store spread exceeds 4x. Under the assumed spread that is attributable
1051/// misbehaviour, so a `Rejected` response flows through the normal failure path
1052/// (labelled `size_reject` for observability) rather than triggering a
1053/// wire-compatible split-and-retry.
1054async fn peer_proves_records(
1055    peer: PeerId,
1056    keys: Vec<XorName>,
1057    context: PruneAuditContext<'_>,
1058) -> Vec<(PeerId, XorName)> {
1059    let (challenge_id, nonce) = {
1060        let mut rng = rand::thread_rng();
1061        (rng.gen::<u64>(), rng.gen::<[u8; 32]>())
1062    };
1063    let mut challenge_material = Vec::new();
1064    for key in keys {
1065        if let Some(expected_digest) =
1066            local_record_digest(&peer, &key, &nonce, context.storage).await
1067        {
1068            challenge_material.push((key, expected_digest));
1069        }
1070    }
1071    if challenge_material.is_empty() {
1072        return Vec::new();
1073    }
1074
1075    let challenge_keys: Vec<XorName> = challenge_material.iter().map(|(key, _)| *key).collect();
1076    let Some((encoded, key_count)) =
1077        encode_prune_audit_challenge(&peer, &challenge_keys, challenge_id, nonce)
1078    else {
1079        return Vec::new();
1080    };
1081    let Some(decoded) = receive_prune_audit_response(
1082        &peer,
1083        &challenge_keys,
1084        encoded,
1085        key_count,
1086        challenge_id,
1087        context,
1088    )
1089    .await
1090    else {
1091        return Vec::new();
1092    };
1093
1094    let statuses = prune_audit_response_statuses(decoded, challenge_id, &peer, &challenge_material);
1095    let mut clear_bootstrap_claim = false;
1096    let mut audit_failure_reported = false;
1097    let mut proven = Vec::new();
1098
1099    for (key, status) in statuses {
1100        if prune_audit_response_clears_bootstrap_claim(status) {
1101            clear_bootstrap_claim = true;
1102        }
1103
1104        match status {
1105            PruneAuditStatus::Proven => proven.push((peer, key)),
1106            PruneAuditStatus::Bootstrapping => {
1107                report_prune_bootstrap_claim(
1108                    &peer,
1109                    &key,
1110                    context.p2p_node,
1111                    context.config,
1112                    context.sync_state,
1113                    context.report_state,
1114                )
1115                .await;
1116            }
1117            PruneAuditStatus::Failed | PruneAuditStatus::Rejected => {
1118                let failure_class = if matches!(status, PruneAuditStatus::Rejected) {
1119                    "size_reject"
1120                } else {
1121                    "failed"
1122                };
1123                if !audit_failure_reported
1124                    && report_prune_audit_failure_once(
1125                        &peer,
1126                        &key,
1127                        context.p2p_node,
1128                        context.config,
1129                        context.report_state,
1130                        failure_class,
1131                    )
1132                    .await
1133                {
1134                    audit_failure_reported = true;
1135                }
1136            }
1137        }
1138    }
1139
1140    if clear_bootstrap_claim {
1141        clear_prune_bootstrap_claim(&peer, context.sync_state).await;
1142    }
1143
1144    proven
1145}
1146
1147async fn receive_prune_audit_response(
1148    peer: &PeerId,
1149    challenge_keys: &[XorName],
1150    encoded: Vec<u8>,
1151    key_count: usize,
1152    challenge_id: u64,
1153    context: PruneAuditContext<'_>,
1154) -> Option<ReplicationMessage> {
1155    let result = send_prune_audit_challenge(
1156        peer,
1157        encoded,
1158        key_count,
1159        challenge_id,
1160        context.p2p_node,
1161        context.config,
1162        context.audit_challenge_coordinator,
1163    )
1164    .await;
1165    let failure_class = match result {
1166        PruneAuditChallengeResult::Response(decoded) => return Some(*decoded),
1167        PruneAuditChallengeResult::NoResponse(class) => {
1168            // Keep the local class split so timeout metrics are not polluted
1169            // by failures that happened before delivery.
1170            audit_metrics::record_audit_no_response(AuditType::Prune, class);
1171            class.as_str()
1172        }
1173        PruneAuditChallengeResult::MalformedResponse => "malformed",
1174    };
1175
1176    for key in challenge_keys {
1177        if report_prune_audit_failure_once(
1178            peer,
1179            key,
1180            context.p2p_node,
1181            context.config,
1182            context.report_state,
1183            failure_class,
1184        )
1185        .await
1186        {
1187            break;
1188        }
1189    }
1190    None
1191}
1192
1193fn prune_audit_response_clears_bootstrap_claim(status: PruneAuditStatus) -> bool {
1194    matches!(
1195        status,
1196        PruneAuditStatus::Proven | PruneAuditStatus::Failed | PruneAuditStatus::Rejected
1197    )
1198}
1199
1200// The responder for an incoming `AuditChallenge` (including prune-confirmation
1201// challenges, which reuse the same wire message) lives in
1202// `super::handle_audit_challenge_msg` -> `audit::handle_audit_challenge`, the
1203// responsible-chunk audit responder. No separate prune-only responder is needed.
1204fn encode_prune_audit_challenge(
1205    peer: &PeerId,
1206    keys: &[XorName],
1207    challenge_id: u64,
1208    nonce: [u8; 32],
1209) -> Option<(Vec<u8>, usize)> {
1210    if keys.is_empty() {
1211        return None;
1212    }
1213    let challenge = AuditChallenge {
1214        challenge_id,
1215        nonce,
1216        challenged_peer_id: *peer.as_bytes(),
1217        keys: keys.to_vec(),
1218    };
1219    let key_count = challenge.keys.len();
1220    let msg = ReplicationMessage {
1221        request_id: challenge_id,
1222        body: ReplicationMessageBody::AuditChallenge(challenge),
1223    };
1224    let encoded = match msg.encode() {
1225        Ok(data) => data,
1226        Err(e) => {
1227            warn!(
1228                "Failed to encode prune audit challenge with {} keys against {peer}: {e}",
1229                keys.len(),
1230            );
1231            return None;
1232        }
1233    };
1234    Some((encoded, key_count))
1235}
1236
1237pub(crate) fn prune_audit_response_timeout(
1238    config: &ReplicationConfig,
1239    key_count: usize,
1240) -> Duration {
1241    config.audit_response_timeout(key_count)
1242}
1243
1244async fn send_prune_audit_challenge(
1245    peer: &PeerId,
1246    encoded: Vec<u8>,
1247    key_count: usize,
1248    challenge_id: u64,
1249    p2p_node: &Arc<P2PNode>,
1250    config: &ReplicationConfig,
1251    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
1252) -> PruneAuditChallengeResult {
1253    let Some(_slot) = audit_challenge_coordinator.acquire(*peer).await else {
1254        warn!(
1255            "Prune audit challenge with {key_count} keys against {peer} could not acquire coordinator slot"
1256        );
1257        return PruneAuditChallengeResult::MalformedResponse;
1258    };
1259    let timeout = prune_audit_response_timeout(config, key_count);
1260    info!(
1261        target: "ant_node::replication::audit_requester",
1262        event = "started",
1263        audit_origin = AuditType::Prune.as_str(),
1264        audit_round = "digest",
1265        challenged_peer = %peer,
1266        challenge_id,
1267        work_items = key_count,
1268        timeout_ms = timeout.as_millis(),
1269        "Outbound audit request started"
1270    );
1271    let request_started = Instant::now();
1272    let response = match p2p_node
1273        .send_request(peer, REPLICATION_PROTOCOL_ID, encoded, timeout)
1274        .await
1275    {
1276        Ok(response) => {
1277            info!(
1278                target: "ant_node::replication::audit_requester",
1279                event = "completed",
1280                audit_origin = AuditType::Prune.as_str(),
1281                audit_round = "digest",
1282                challenged_peer = %peer,
1283                challenge_id,
1284                work_items = key_count,
1285                elapsed_ms = request_started.elapsed().as_millis(),
1286                outcome = "response",
1287                "Outbound audit request completed"
1288            );
1289            response
1290        }
1291        Err(e) => {
1292            let error = e.to_string();
1293            let (send_error_class, audit_failure_class) =
1294                audit_metrics::classify_audit_send_error(&error);
1295            warn!(
1296                target: "ant_node::replication::audit_requester",
1297                event = "completed",
1298                audit_origin = AuditType::Prune.as_str(),
1299                audit_round = "digest",
1300                challenged_peer = %peer,
1301                challenge_id,
1302                work_items = key_count,
1303                elapsed_ms = request_started.elapsed().as_millis(),
1304                outcome = "no_response",
1305                audit_type = AuditType::Prune.as_str(),
1306                audit_failure_class = audit_failure_class.as_str(),
1307                send_error_class,
1308                "Prune audit challenge with {key_count} keys against {peer} failed: {e}",
1309            );
1310            return PruneAuditChallengeResult::NoResponse(audit_failure_class);
1311        }
1312    };
1313
1314    let decoded = match ReplicationMessage::decode(&response.data) {
1315        Ok(msg) => msg,
1316        Err(e) => {
1317            warn!("Failed to decode prune audit response from {peer}: {e}");
1318            return PruneAuditChallengeResult::MalformedResponse;
1319        }
1320    };
1321
1322    PruneAuditChallengeResult::Response(Box::new(decoded))
1323}
1324
1325fn prune_audit_response_statuses(
1326    decoded: ReplicationMessage,
1327    challenge_id: u64,
1328    peer: &PeerId,
1329    challenge_material: &[(XorName, [u8; 32])],
1330) -> Vec<(XorName, PruneAuditStatus)> {
1331    let failed_all = |reason: &str| {
1332        warn!(
1333            "Prune audit proof batch from {peer} failed for {} keys: {reason}",
1334            challenge_material.len()
1335        );
1336        challenge_material
1337            .iter()
1338            .map(|(key, _)| (*key, PruneAuditStatus::Failed))
1339            .collect()
1340    };
1341
1342    match decoded.body {
1343        ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1344            challenge_id: resp_id,
1345            digests,
1346        }) => {
1347            if resp_id != challenge_id {
1348                return failed_all("challenge id mismatch");
1349            }
1350            if digests.len() != challenge_material.len() {
1351                return failed_all(&format!(
1352                    "returned {} digests for {} challenged keys",
1353                    digests.len(),
1354                    challenge_material.len()
1355                ));
1356            }
1357
1358            challenge_material
1359                .iter()
1360                .zip(digests.iter())
1361                .map(|((key, expected_digest), digest)| {
1362                    if *digest == ABSENT_KEY_DIGEST {
1363                        warn!(
1364                            "Prune audit proof from {peer} failed for {}: peer reports key absent",
1365                            hex::encode(key)
1366                        );
1367                        return (*key, PruneAuditStatus::Failed);
1368                    }
1369                    if digest == expected_digest {
1370                        (*key, PruneAuditStatus::Proven)
1371                    } else {
1372                        warn!(
1373                            "Prune audit proof from {peer} failed for {}: digest mismatch",
1374                            hex::encode(key)
1375                        );
1376                        (*key, PruneAuditStatus::Failed)
1377                    }
1378                })
1379                .collect()
1380        }
1381        ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1382            challenge_id: resp_id,
1383        }) => {
1384            if resp_id == challenge_id {
1385                warn!(
1386                    "Prune audit proof batch for {} keys blocked by bootstrap claim from {peer}",
1387                    challenge_material.len()
1388                );
1389                challenge_material
1390                    .iter()
1391                    .map(|(key, _)| (*key, PruneAuditStatus::Bootstrapping))
1392                    .collect()
1393            } else {
1394                failed_all("challenge id mismatch on Bootstrapping")
1395            }
1396        }
1397        ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
1398            challenge_id: resp_id,
1399            reason,
1400        }) => {
1401            if resp_id != challenge_id {
1402                return failed_all("challenge id mismatch on Rejected");
1403            }
1404            warn!(
1405                "Prune audit proof batch for {} keys rejected by {peer}: {reason}",
1406                challenge_material.len()
1407            );
1408            challenge_material
1409                .iter()
1410                .map(|(key, _)| (*key, PruneAuditStatus::Rejected))
1411                .collect()
1412        }
1413        _ => failed_all("unexpected response type"),
1414    }
1415}
1416
1417async fn local_record_digest(
1418    peer: &PeerId,
1419    key: &XorName,
1420    nonce: &[u8; 32],
1421    storage: &Arc<ChunkStore>,
1422) -> Option<[u8; 32]> {
1423    local_record_bytes(key, storage)
1424        .await
1425        .map(|bytes| compute_audit_digest(nonce, peer.as_bytes(), key, &bytes))
1426}
1427
1428/// The local copy a prune audit judges peers against. Read through the verifying
1429/// path: a local file that no longer hashes to its key would fail every honest
1430/// holder and hold the prune back indefinitely, so it is taken out of service by the
1431/// read instead, and the key is not audited.
1432async fn local_record_bytes(key: &XorName, storage: &Arc<ChunkStore>) -> Option<Vec<u8>> {
1433    match storage.get(key).await {
1434        Ok(Some(bytes)) => Some(bytes),
1435        Ok(None) => {
1436            debug!(
1437                "Cannot prune-audit {}: local record disappeared",
1438                hex::encode(key)
1439            );
1440            None
1441        }
1442        Err(e) => {
1443            warn!(
1444                "Cannot prune-audit {}: failed to read local record: {e}",
1445                hex::encode(key)
1446            );
1447            None
1448        }
1449    }
1450}
1451
1452#[cfg(test)]
1453fn audit_digest_proves_key(
1454    peer: &PeerId,
1455    key: &XorName,
1456    nonce: &[u8; 32],
1457    local_bytes: &[u8],
1458    digest: &[u8; 32],
1459) -> bool {
1460    if *digest == ABSENT_KEY_DIGEST {
1461        return false;
1462    }
1463    let expected = compute_audit_digest(nonce, peer.as_bytes(), key, local_bytes);
1464    *digest == expected
1465}
1466
1467async fn report_prune_audit_failure_once(
1468    peer: &PeerId,
1469    key: &XorName,
1470    p2p_node: &Arc<P2PNode>,
1471    config: &ReplicationConfig,
1472    report_state: &PruneAuditReportState,
1473    audit_failure_class: &'static str,
1474) -> bool {
1475    let should_report = peer_is_currently_responsible(peer, key, p2p_node, config).await
1476        && reserve_prune_audit_failure_report(report_state, peer).await;
1477    if !should_report {
1478        return false;
1479    }
1480
1481    warn!(
1482        audit_type = AuditType::Prune.as_str(),
1483        audit_failure_class,
1484        peer = %peer,
1485        key = %hex::encode(key),
1486        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
1487        "Prune audit failure: peer={peer}, audit_failure_class={audit_failure_class}, key={}",
1488        hex::encode(key)
1489    );
1490    p2p_node
1491        .report_trust_event(
1492            peer,
1493            saorsa_core::TrustEvent::ApplicationFailure(AUDIT_FAILURE_TRUST_WEIGHT),
1494        )
1495        .await;
1496    true
1497}
1498
1499async fn reserve_prune_audit_failure_report(
1500    report_state: &PruneAuditReportState,
1501    peer: &PeerId,
1502) -> bool {
1503    report_state.audit_failures.write().await.insert(*peer)
1504}
1505
1506async fn reserve_prune_bootstrap_abuse_report(
1507    report_state: &PruneAuditReportState,
1508    peer: &PeerId,
1509) -> bool {
1510    report_state.bootstrap_abuse.write().await.insert(*peer)
1511}
1512
1513async fn report_prune_bootstrap_claim(
1514    peer: &PeerId,
1515    key: &XorName,
1516    p2p_node: &Arc<P2PNode>,
1517    config: &ReplicationConfig,
1518    sync_state: &Arc<RwLock<NeighborSyncState>>,
1519    report_state: &PruneAuditReportState,
1520) {
1521    if !peer_is_currently_responsible(peer, key, p2p_node, config).await {
1522        return;
1523    }
1524
1525    let observation = {
1526        let now = Instant::now();
1527        let mut state = sync_state.write().await;
1528        (
1529            now,
1530            state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period),
1531        )
1532    };
1533
1534    let (now, observation) = observation;
1535    match observation {
1536        BootstrapClaimObservation::WithinGrace { .. } => {
1537            debug!("Prune audit: peer {peer} claims bootstrapping (within grace period)");
1538            return;
1539        }
1540        BootstrapClaimObservation::PastGrace { first_seen } => {
1541            if !reserve_prune_bootstrap_abuse_report(report_state, peer).await {
1542                debug!("Prune audit: peer {peer} bootstrap abuse already reported this pass");
1543                return;
1544            }
1545            warn!(
1546                "Prune audit: peer {peer} claiming bootstrap past grace period \
1547                 ({:?} > {:?}), reporting abuse",
1548                now.duration_since(first_seen),
1549                config.bootstrap_claim_grace_period,
1550            );
1551        }
1552        BootstrapClaimObservation::Repeated { first_seen } => {
1553            if !reserve_prune_bootstrap_abuse_report(report_state, peer).await {
1554                debug!("Prune audit: peer {peer} bootstrap abuse already reported this pass");
1555                return;
1556            }
1557            warn!(
1558                "Prune audit: peer {peer} repeated bootstrap claim after previously stopping; \
1559                 first claim was {:?} ago, reporting abuse",
1560                now.duration_since(first_seen),
1561            );
1562        }
1563    }
1564
1565    p2p_node
1566        .report_trust_event(
1567            peer,
1568            saorsa_core::TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
1569        )
1570        .await;
1571}
1572
1573async fn clear_prune_bootstrap_claim(peer: &PeerId, sync_state: &Arc<RwLock<NeighborSyncState>>) {
1574    let removed = {
1575        let mut state = sync_state.write().await;
1576        state.clear_active_bootstrap_claim(peer)
1577    };
1578    if removed {
1579        debug!("Prune audit: cleared active bootstrap claim for {peer}");
1580    }
1581}
1582
1583async fn peer_is_currently_responsible(
1584    peer: &PeerId,
1585    key: &XorName,
1586    p2p_node: &Arc<P2PNode>,
1587    config: &ReplicationConfig,
1588) -> bool {
1589    let closest = p2p_node
1590        .dht_manager()
1591        .find_closest_nodes_local_with_self(key, config.close_group_size)
1592        .await;
1593    closest.iter().any(|node| node.peer_id == *peer)
1594}
1595
1596#[cfg(test)]
1597#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1598mod tests {
1599    use super::*;
1600    use crate::storage::chunk_store::CHUNKS_DIR_NAME;
1601    use crate::storage::ChunkStoreConfig;
1602    use tempfile::TempDir;
1603
1604    fn peer_id_from_byte(b: u8) -> PeerId {
1605        let mut bytes = [0u8; 32];
1606        bytes[0] = b;
1607        PeerId::from_bytes(bytes)
1608    }
1609
1610    fn key_from_byte(b: u8) -> XorName {
1611        [b; 32]
1612    }
1613
1614    fn peer_ids(count: usize) -> Vec<PeerId> {
1615        (0..count)
1616            .map(|idx| peer_id_from_byte(u8::try_from(idx + 1).expect("peer byte")))
1617            .collect()
1618    }
1619
1620    fn candidate(key: XorName, target_peers: Vec<PeerId>) -> RecordPruneCandidate {
1621        RecordPruneCandidate { key, target_peers }
1622    }
1623
1624    /// A prune audit judges holders against this node's own copy. A copy that
1625    /// no longer hashes to its key would fail every honest holder and hold the
1626    /// prune back forever, so it is not used as a reference: the read takes it
1627    /// out of service instead, and an intact copy is used as before.
1628    #[tokio::test]
1629    async fn a_rotted_local_copy_is_not_used_to_judge_holders() {
1630        let dir = TempDir::new().expect("temp dir");
1631        let storage = Arc::new(
1632            ChunkStore::new(ChunkStoreConfig {
1633                root_dir: dir.path().to_path_buf(),
1634                ..ChunkStoreConfig::test_default()
1635            })
1636            .await
1637            .expect("chunk store"),
1638        );
1639        let good_bytes = b"intact prune candidate".to_vec();
1640        let bad_bytes = b"rotted prune candidate".to_vec();
1641        let good = ChunkStore::compute_address(&good_bytes);
1642        let bad = ChunkStore::compute_address(&bad_bytes);
1643        storage.put(&good, &good_bytes).await.expect("put good");
1644        storage.put(&bad, &bad_bytes).await.expect("put bad");
1645        let path = dir
1646            .path()
1647            .join(CHUNKS_DIR_NAME)
1648            .join(format!("{:02x}", bad.last().copied().unwrap_or(0)))
1649            .join(hex::encode(bad));
1650        std::fs::write(&path, b"rotted").expect("corrupt the file");
1651
1652        assert_eq!(local_record_bytes(&good, &storage).await, Some(good_bytes));
1653        assert_eq!(local_record_bytes(&bad, &storage).await, None);
1654        assert!(!storage.exists(&bad).expect("exists"));
1655        assert!(!path.exists(), "the rotted local copy is removed");
1656    }
1657
1658    #[test]
1659    fn prune_audit_challenges_are_batched_by_target_peer() {
1660        let peer_a = peer_id_from_byte(1);
1661        let peer_b = peer_id_from_byte(2);
1662        let key_a = key_from_byte(0xA);
1663        let key_b = key_from_byte(0xB);
1664        let candidates = vec![
1665            candidate(key_a, vec![peer_a, peer_b]),
1666            candidate(key_b, vec![peer_b]),
1667        ];
1668
1669        let mut challenges = build_peer_audit_challenges(&candidates, 2);
1670        for (_, keys) in &mut challenges {
1671            keys.sort_unstable();
1672        }
1673        challenges.sort_unstable_by_key(|(peer, keys)| (*peer.as_bytes(), keys.clone()));
1674
1675        let mut expected = vec![(peer_a, vec![key_a]), (peer_b, vec![key_a, key_b])];
1676        expected.sort_unstable_by_key(|(peer, keys)| (*peer.as_bytes(), keys.clone()));
1677        assert_eq!(challenges, expected);
1678    }
1679
1680    #[test]
1681    fn prune_audit_challenges_split_peer_batches_at_responsible_audit_limit() {
1682        let peer = peer_id_from_byte(1);
1683        let candidates = vec![
1684            candidate(key_from_byte(0xA), vec![peer]),
1685            candidate(key_from_byte(0xB), vec![peer]),
1686            candidate(key_from_byte(0xC), vec![peer]),
1687            candidate(key_from_byte(0xD), vec![peer]),
1688            candidate(key_from_byte(0xE), vec![peer]),
1689        ];
1690
1691        let mut challenges = build_peer_audit_challenges(&candidates, 2);
1692        for (_, keys) in &mut challenges {
1693            keys.sort_unstable();
1694        }
1695        challenges.sort_unstable_by_key(|(_, keys)| keys.clone());
1696
1697        assert_eq!(
1698            challenges,
1699            vec![
1700                (peer, vec![key_from_byte(0xA), key_from_byte(0xB)]),
1701                (peer, vec![key_from_byte(0xC), key_from_byte(0xD)]),
1702                (peer, vec![key_from_byte(0xE)]),
1703            ]
1704        );
1705    }
1706
1707    #[test]
1708    fn prune_audit_batched_digest_response_is_evaluated_per_key() {
1709        let peer = peer_id_from_byte(7);
1710        let key_a = key_from_byte(0xA);
1711        let key_b = key_from_byte(0xB);
1712        let nonce = [0x7A; 32];
1713        let bytes_a = b"record-a".to_vec();
1714        let expected_a = compute_audit_digest(&nonce, peer.as_bytes(), &key_a, &bytes_a);
1715        let expected_b = compute_audit_digest(&nonce, peer.as_bytes(), &key_b, b"record-b");
1716        let msg = ReplicationMessage {
1717            request_id: 42,
1718            body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1719                challenge_id: 42,
1720                digests: vec![expected_a, ABSENT_KEY_DIGEST],
1721            }),
1722        };
1723
1724        let statuses = prune_audit_response_statuses(
1725            msg,
1726            42,
1727            &peer,
1728            &[(key_a, expected_a), (key_b, expected_b)],
1729        );
1730
1731        assert_eq!(
1732            statuses,
1733            vec![
1734                (key_a, PruneAuditStatus::Proven),
1735                (key_b, PruneAuditStatus::Failed),
1736            ]
1737        );
1738    }
1739
1740    #[test]
1741    fn confirmed_keys_require_quorum_of_target_peers_present() {
1742        let peer_a = peer_id_from_byte(1);
1743        let peer_b = peer_id_from_byte(2);
1744        let peer_c = peer_id_from_byte(3);
1745        let key = key_from_byte(0xC);
1746        let candidates = vec![candidate(key, vec![peer_a, peer_b, peer_c])];
1747        let mut present_by_key = HashMap::new();
1748        present_by_key.insert(key, HashSet::from([peer_a, peer_b]));
1749
1750        // Two of three proofs meet a quorum of 2 even though one peer is
1751        // missing — unanimity is not required.
1752        let confirmed = confirmed_keys_from_presence(&candidates, &present_by_key, 2);
1753        assert_eq!(confirmed, vec![key]);
1754
1755        // The same evidence fails a quorum of 3.
1756        let confirmed = confirmed_keys_from_presence(&candidates, &present_by_key, 3);
1757        assert!(
1758            confirmed.is_empty(),
1759            "expected no confirmed keys at a quorum of 3, got {confirmed:?}"
1760        );
1761    }
1762
1763    #[test]
1764    fn confirmed_keys_defer_below_quorum_or_missing_peer_evidence() {
1765        let peer_a = peer_id_from_byte(1);
1766        let peer_b = peer_id_from_byte(2);
1767        let quorum_key = key_from_byte(0xD);
1768        let below_quorum_key = key_from_byte(0xE);
1769        let missing_key = key_from_byte(0xF);
1770        let candidates = vec![
1771            candidate(quorum_key, vec![peer_a, peer_b]),
1772            candidate(below_quorum_key, vec![peer_a, peer_b]),
1773            candidate(missing_key, vec![peer_a, peer_b]),
1774        ];
1775        let mut present_by_key = HashMap::new();
1776        present_by_key.insert(quorum_key, HashSet::from([peer_a, peer_b]));
1777        present_by_key.insert(below_quorum_key, HashSet::from([peer_a]));
1778
1779        let confirmed = confirmed_keys_from_presence(&candidates, &present_by_key, 2);
1780
1781        assert_eq!(confirmed, vec![quorum_key]);
1782    }
1783
1784    #[test]
1785    fn prune_proofs_needed_tolerates_exactly_one_lagging_peer() {
1786        assert_eq!(prune_proofs_needed(0), 0);
1787        // Tiny groups require every proof.
1788        assert_eq!(prune_proofs_needed(1), 1);
1789        assert_eq!(prune_proofs_needed(2), 2);
1790        assert_eq!(prune_proofs_needed(3), 2);
1791        assert_eq!(prune_proofs_needed(5), 4);
1792        // Production close group: 6 of 7 proofs required.
1793        assert_eq!(prune_proofs_needed(7), 6);
1794    }
1795
1796    #[test]
1797    fn zero_quorum_never_confirms() {
1798        let peer_a = peer_id_from_byte(1);
1799        let key = key_from_byte(0x10);
1800        let mut present_by_key = HashMap::new();
1801        present_by_key.insert(key, HashSet::from([peer_a]));
1802
1803        assert!(!target_peers_reported_present(
1804            &key,
1805            &[peer_a],
1806            &present_by_key,
1807            0
1808        ));
1809    }
1810
1811    #[test]
1812    fn proofs_from_non_target_peers_do_not_count_toward_quorum() {
1813        let target = peer_id_from_byte(1);
1814        let outsider = peer_id_from_byte(2);
1815        let key = key_from_byte(0x11);
1816        let mut present_by_key = HashMap::new();
1817        present_by_key.insert(key, HashSet::from([outsider]));
1818
1819        assert!(!target_peers_reported_present(
1820            &key,
1821            &[target],
1822            &present_by_key,
1823            1
1824        ));
1825    }
1826
1827    #[test]
1828    fn duplicated_target_peer_counts_once_toward_quorum() {
1829        let peer = peer_id_from_byte(1);
1830        let key = key_from_byte(0x12);
1831        let mut present_by_key = HashMap::new();
1832        present_by_key.insert(key, HashSet::from([peer]));
1833
1834        assert!(!target_peers_reported_present(
1835            &key,
1836            &[peer, peer],
1837            &present_by_key,
1838            2
1839        ));
1840    }
1841
1842    #[test]
1843    fn audit_digest_proof_requires_matching_peer_key_nonce_and_bytes() {
1844        let peer = peer_id_from_byte(1);
1845        let other_peer = peer_id_from_byte(2);
1846        let key = key_from_byte(0x11);
1847        let other_key = key_from_byte(0x12);
1848        let nonce = [0xAA; 32];
1849        let other_nonce = [0xBB; 32];
1850        let bytes = b"record bytes";
1851        let digest = compute_audit_digest(&nonce, peer.as_bytes(), &key, bytes);
1852
1853        assert!(audit_digest_proves_key(&peer, &key, &nonce, bytes, &digest));
1854        assert!(!audit_digest_proves_key(
1855            &other_peer,
1856            &key,
1857            &nonce,
1858            bytes,
1859            &digest
1860        ));
1861        assert!(!audit_digest_proves_key(
1862            &peer, &other_key, &nonce, bytes, &digest
1863        ));
1864        assert!(!audit_digest_proves_key(
1865            &peer,
1866            &key,
1867            &other_nonce,
1868            bytes,
1869            &digest
1870        ));
1871        assert!(!audit_digest_proves_key(
1872            &peer,
1873            &key,
1874            &nonce,
1875            b"different bytes",
1876            &digest
1877        ));
1878        assert!(!audit_digest_proves_key(
1879            &peer,
1880            &key,
1881            &nonce,
1882            bytes,
1883            &ABSENT_KEY_DIGEST
1884        ));
1885    }
1886
1887    #[tokio::test]
1888    async fn prune_audit_normal_response_clears_stale_bootstrap_claim() {
1889        let peer = peer_id_from_byte(1);
1890        let state = Arc::new(RwLock::new(NeighborSyncState::new_cycle(vec![peer])));
1891        let first_seen = Instant::now();
1892        state
1893            .write()
1894            .await
1895            .bootstrap_claims
1896            .insert(peer, first_seen);
1897        state
1898            .write()
1899            .await
1900            .bootstrap_claim_history
1901            .insert(peer, first_seen);
1902
1903        clear_prune_bootstrap_claim(&peer, &state).await;
1904
1905        let state = state.read().await;
1906        assert!(!state.bootstrap_claims.contains_key(&peer));
1907        assert!(state.bootstrap_claim_history.contains_key(&peer));
1908    }
1909
1910    #[test]
1911    fn prune_audit_clear_policy_requires_decoded_non_bootstrap_response() {
1912        assert!(prune_audit_response_clears_bootstrap_claim(
1913            PruneAuditStatus::Proven
1914        ));
1915        assert!(prune_audit_response_clears_bootstrap_claim(
1916            PruneAuditStatus::Failed
1917        ));
1918        assert!(!prune_audit_response_clears_bootstrap_claim(
1919            PruneAuditStatus::Bootstrapping
1920        ));
1921    }
1922
1923    #[tokio::test]
1924    async fn prune_audit_failure_penalty_is_reserved_once_per_peer_per_pass() {
1925        let peer = peer_id_from_byte(1);
1926        let other_peer = peer_id_from_byte(2);
1927        let report_state = PruneAuditReportState::default();
1928
1929        assert!(reserve_prune_audit_failure_report(&report_state, &peer).await);
1930        assert!(!reserve_prune_audit_failure_report(&report_state, &peer).await);
1931        assert!(reserve_prune_audit_failure_report(&report_state, &other_peer).await);
1932
1933        let reported = report_state.audit_failures.read().await;
1934        assert_eq!(reported.len(), 2);
1935        assert!(reported.contains(&peer));
1936        assert!(reported.contains(&other_peer));
1937    }
1938
1939    #[tokio::test]
1940    async fn prune_bootstrap_abuse_penalty_is_reserved_once_per_peer_per_pass() {
1941        let peer = peer_id_from_byte(1);
1942        let other_peer = peer_id_from_byte(2);
1943        let report_state = PruneAuditReportState::default();
1944
1945        assert!(reserve_prune_bootstrap_abuse_report(&report_state, &peer).await);
1946        assert!(!reserve_prune_bootstrap_abuse_report(&report_state, &peer).await);
1947        assert!(reserve_prune_bootstrap_abuse_report(&report_state, &other_peer).await);
1948
1949        let reported = report_state.bootstrap_abuse.read().await;
1950        assert_eq!(reported.len(), 2);
1951        assert!(reported.contains(&peer));
1952        assert!(reported.contains(&other_peer));
1953    }
1954
1955    // -- Prune lifecycle classification (see module docs) --------------------
1956
1957    /// Production strict close-group size.
1958    const PROD_CLOSE_GROUP: usize = 7;
1959    /// Production storage-retention width (`close_group_size + margin`).
1960    const PROD_RETENTION_WIDTH: usize = 9;
1961    /// A self id outside every `peer_ids(..)` helper group.
1962    const SELF_BYTE: u8 = 99;
1963
1964    async fn test_paid_list() -> (Arc<PaidList>, tempfile::TempDir) {
1965        let dir = tempfile::tempdir().expect("tempdir");
1966        let paid_list = Arc::new(PaidList::new(dir.path()).await.expect("paid list"));
1967        (paid_list, dir)
1968    }
1969
1970    fn record_deps<'a>(
1971        self_id: &'a PeerId,
1972        paid_list: &'a Arc<PaidList>,
1973        config: &'a ReplicationConfig,
1974        allow_remote_prune_audits: bool,
1975        commitment_state: Option<&'a Arc<ResponderCommitmentState>>,
1976    ) -> RecordPruneKeyDeps<'a> {
1977        RecordPruneKeyDeps {
1978            self_id,
1979            paid_list,
1980            config,
1981            allow_remote_prune_audits,
1982            commitment_state,
1983        }
1984    }
1985
1986    /// A responder commitment state whose retained (gossiped) commitment
1987    /// contains exactly `key`, so `is_held(key)` is true.
1988    fn held_commitment_state(key: XorName, content: &[u8]) -> Arc<ResponderCommitmentState> {
1989        let (pk, sk) = saorsa_pqc::api::sig::ml_dsa_65()
1990            .generate_keypair()
1991            .expect("keypair");
1992        let bytes_hash = *blake3::hash(content).as_bytes();
1993        let built = crate::replication::commitment_state::BuiltCommitment::build(
1994            vec![(key, bytes_hash)],
1995            &[0; 32],
1996            &sk,
1997            &pk.to_bytes(),
1998        )
1999        .expect("build commitment");
2000        let hash = built.hash();
2001        let state = ResponderCommitmentState::new();
2002        state.rotate(built);
2003        state.mark_gossiped(hash);
2004        Arc::new(state)
2005    }
2006
2007    fn instant_after(base: SystemTime, delta: Duration) -> SystemTime {
2008        base.checked_add(delta).expect("test instant overflow")
2009    }
2010
2011    /// #1 + #4: a record outside the retention width is marked the moment it
2012    /// is observed there — even while a retained commitment still holds the
2013    /// key. Retention vetoes deletion, never the hysteresis clock.
2014    #[tokio::test]
2015    async fn out_of_range_record_is_marked_immediately_even_when_held_by_commitment() {
2016        let (paid_list, _dir) = test_paid_list().await;
2017        let config = ReplicationConfig::default();
2018        let self_id = peer_id_from_byte(SELF_BYTE);
2019        let key = key_from_byte(0xA0);
2020        let commitment = held_commitment_state(key, b"held bytes");
2021        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2022        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2023        let deps = record_deps(&self_id, &paid_list, &config, true, Some(&commitment));
2024
2025        let outcome = evaluate_record_prune_key(
2026            &deps,
2027            &key,
2028            &admission_peers,
2029            &strict_close_peers,
2030            SystemTime::now(),
2031        );
2032
2033        assert!(
2034            outcome.marked,
2035            "first out-of-range observation must set the timestamp"
2036        );
2037        assert!(matches!(
2038            outcome.state,
2039            RecordPruneKeyState::HysteresisPending
2040        ));
2041        assert!(
2042            paid_list.record_out_of_range_since(&key).is_some(),
2043            "a retained commitment must not delay the start of hysteresis"
2044        );
2045    }
2046
2047    /// #2: a record outside the retention width for less than the hysteresis
2048    /// duration is not a prune candidate.
2049    #[tokio::test]
2050    async fn record_outside_range_within_hysteresis_is_not_a_candidate() {
2051        let (paid_list, _dir) = test_paid_list().await;
2052        let config = ReplicationConfig::default();
2053        let self_id = peer_id_from_byte(SELF_BYTE);
2054        let key = key_from_byte(0xA1);
2055        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2056        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2057        let deps = record_deps(&self_id, &paid_list, &config, true, None);
2058
2059        paid_list.set_record_out_of_range(&key);
2060        let outcome = evaluate_record_prune_key(
2061            &deps,
2062            &key,
2063            &admission_peers,
2064            &strict_close_peers,
2065            SystemTime::now(),
2066        );
2067
2068        assert!(!outcome.marked, "timestamp was already set");
2069        assert!(matches!(
2070            outcome.state,
2071            RecordPruneKeyState::HysteresisPending
2072        ));
2073    }
2074
2075    /// #3 + #8: after the full hysteresis the record becomes an auditable
2076    /// candidate whose targets are the CURRENT strict close group — with an
2077    /// empty `RepairProofs` table and no prior neighbor-sync contact.
2078    #[tokio::test]
2079    async fn record_past_hysteresis_is_candidate_targeting_current_close_group() {
2080        let (paid_list, _dir) = test_paid_list().await;
2081        let config = ReplicationConfig::default();
2082        let self_id = peer_id_from_byte(SELF_BYTE);
2083        let key = key_from_byte(0xA2);
2084        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2085        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2086        let deps = record_deps(&self_id, &paid_list, &config, true, None);
2087
2088        paid_list.set_record_out_of_range(&key);
2089        let first_seen = paid_list
2090            .record_out_of_range_since(&key)
2091            .expect("first seen");
2092        let outcome = evaluate_record_prune_key(
2093            &deps,
2094            &key,
2095            &admission_peers,
2096            &strict_close_peers,
2097            instant_after(first_seen, config.prune_hysteresis_duration),
2098        );
2099
2100        let RecordPruneKeyState::Candidate(PruneCandidateDisposition::Auditable(candidate)) =
2101            outcome.state
2102        else {
2103            panic!("record past hysteresis must be an auditable candidate");
2104        };
2105        let targets: HashSet<PeerId> = candidate.target_peers.iter().copied().collect();
2106        let expected: HashSet<PeerId> = strict_close_peers.iter().copied().collect();
2107        assert_eq!(
2108            targets, expected,
2109            "audit targets must be the current strict close group, unfiltered by repair proofs"
2110        );
2111    }
2112
2113    /// #5: a retained commitment vetoes deletion after candidacy without
2114    /// touching the first-seen timestamp or the audit budget.
2115    #[tokio::test]
2116    async fn held_commitment_defers_candidate_without_losing_state() {
2117        let (paid_list, _dir) = test_paid_list().await;
2118        let config = ReplicationConfig::default();
2119        let self_id = peer_id_from_byte(SELF_BYTE);
2120        let key = key_from_byte(0xA3);
2121        let commitment = held_commitment_state(key, b"still committed");
2122        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2123        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2124        let deps = record_deps(&self_id, &paid_list, &config, true, Some(&commitment));
2125
2126        paid_list.set_record_out_of_range(&key);
2127        let first_seen = paid_list
2128            .record_out_of_range_since(&key)
2129            .expect("first seen");
2130        let outcome = evaluate_record_prune_key(
2131            &deps,
2132            &key,
2133            &admission_peers,
2134            &strict_close_peers,
2135            instant_after(first_seen, config.prune_hysteresis_duration),
2136        );
2137
2138        assert!(matches!(
2139            outcome.state,
2140            RecordPruneKeyState::Candidate(PruneCandidateDisposition::HeldByCommitment)
2141        ));
2142        assert_eq!(
2143            paid_list.record_out_of_range_since(&key),
2144            Some(first_seen),
2145            "the retention veto must not restart hysteresis"
2146        );
2147    }
2148
2149    /// #6: bootstrap state defers the audit but preserves candidacy and the
2150    /// first-seen timestamp.
2151    #[tokio::test]
2152    async fn bootstrap_gate_defers_audit_but_preserves_candidacy() {
2153        let (paid_list, _dir) = test_paid_list().await;
2154        let config = ReplicationConfig::default();
2155        let self_id = peer_id_from_byte(SELF_BYTE);
2156        let key = key_from_byte(0xA4);
2157        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2158        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2159        let deps = record_deps(&self_id, &paid_list, &config, false, None);
2160
2161        paid_list.set_record_out_of_range(&key);
2162        let first_seen = paid_list
2163            .record_out_of_range_since(&key)
2164            .expect("first seen");
2165        let outcome = evaluate_record_prune_key(
2166            &deps,
2167            &key,
2168            &admission_peers,
2169            &strict_close_peers,
2170            instant_after(first_seen, config.prune_hysteresis_duration),
2171        );
2172
2173        assert!(matches!(
2174            outcome.state,
2175            RecordPruneKeyState::Candidate(PruneCandidateDisposition::BootstrapDeferred)
2176        ));
2177        assert_eq!(
2178            paid_list.record_out_of_range_since(&key),
2179            Some(first_seen),
2180            "bootstrap deferral must preserve the first-seen time"
2181        );
2182    }
2183
2184    /// The request budget counts multi-key peer requests, not
2185    /// candidate-to-peer edges, and never schedules a partial candidate.
2186    #[test]
2187    fn audit_selection_batches_keys_and_defers_whole_candidates() {
2188        let peers = peer_ids(2);
2189        let candidates = vec![
2190            candidate(key_from_byte(0xA5), peers.clone()),
2191            candidate(key_from_byte(0xA6), peers.clone()),
2192            candidate(key_from_byte(0xA7), peers),
2193        ];
2194
2195        let selected = select_record_prune_audits(&candidates, 2, 10, 2);
2196
2197        assert_eq!(selected.candidates.len(), 2);
2198        assert_eq!(selected.request_count, 2);
2199        assert_eq!(selected.deferred, 1);
2200        let selected_keys: Vec<XorName> = selected.candidates.iter().map(|c| c.key).collect();
2201        assert_eq!(
2202            selected_keys,
2203            vec![key_from_byte(0xA5), key_from_byte(0xA6)],
2204            "candidates are taken in the order given"
2205        );
2206    }
2207
2208    /// #12 (part): moving back inside the retention width clears the
2209    /// out-of-range state.
2210    #[tokio::test]
2211    async fn record_back_in_range_clears_out_of_range_state() {
2212        let (paid_list, _dir) = test_paid_list().await;
2213        let config = ReplicationConfig::default();
2214        let self_id = peer_id_from_byte(SELF_BYTE);
2215        let key = key_from_byte(0xA6);
2216        let mut admission_peers = peer_ids(PROD_RETENTION_WIDTH - 1);
2217        admission_peers.push(self_id);
2218        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2219        let deps = record_deps(&self_id, &paid_list, &config, true, None);
2220
2221        paid_list.set_record_out_of_range(&key);
2222        let outcome = evaluate_record_prune_key(
2223            &deps,
2224            &key,
2225            &admission_peers,
2226            &strict_close_peers,
2227            SystemTime::now(),
2228        );
2229
2230        assert!(matches!(
2231            outcome.state,
2232            RecordPruneKeyState::InRange { cleared: true }
2233        ));
2234        assert!(
2235            paid_list.record_out_of_range_since(&key).is_none(),
2236            "re-entering range must clear the out-of-range timestamp"
2237        );
2238    }
2239
2240    /// A restarted node knows few peers until bootstrap drains, so it looks in
2241    /// range for everything. That must not restart the clocks it restored.
2242    #[tokio::test]
2243    async fn record_in_range_during_bootstrap_keeps_its_clock() {
2244        let (paid_list, _dir) = test_paid_list().await;
2245        let config = ReplicationConfig::default();
2246        let self_id = peer_id_from_byte(SELF_BYTE);
2247        let key = key_from_byte(0xA7);
2248        let mut admission_peers = peer_ids(PROD_RETENTION_WIDTH - 1);
2249        admission_peers.push(self_id);
2250        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2251        let deps = record_deps(&self_id, &paid_list, &config, false, None);
2252
2253        paid_list.set_record_out_of_range(&key);
2254        let outcome = evaluate_record_prune_key(
2255            &deps,
2256            &key,
2257            &admission_peers,
2258            &strict_close_peers,
2259            SystemTime::now(),
2260        );
2261
2262        assert!(matches!(
2263            outcome.state,
2264            RecordPruneKeyState::InRange { cleared: false }
2265        ));
2266        assert!(paid_list.record_out_of_range_since(&key).is_some());
2267    }
2268
2269    // -- Pre-deletion revalidation -------------------------------------------
2270
2271    fn revalidation_inputs<'a>(
2272        self_id: &'a PeerId,
2273        first_seen: Option<SystemTime>,
2274        held_by_commitment: bool,
2275        storage_admission_peers: &'a [PeerId],
2276        strict_close_peers: &'a [PeerId],
2277        now: SystemTime,
2278    ) -> PruneRevalidationInputs<'a> {
2279        PruneRevalidationInputs {
2280            self_id,
2281            first_seen,
2282            prune_hysteresis_duration: ReplicationConfig::default().prune_hysteresis_duration,
2283            held_by_commitment,
2284            storage_admission_peers,
2285            strict_close_peers,
2286            now,
2287        }
2288    }
2289
2290    fn matured(first_seen: SystemTime) -> SystemTime {
2291        instant_after(
2292            first_seen,
2293            ReplicationConfig::default().prune_hysteresis_duration,
2294        )
2295    }
2296
2297    /// #9 + #10: six positive proofs from the current seven-strong close group
2298    /// permit deletion; five do not.
2299    #[test]
2300    fn revalidation_deletes_at_six_of_seven_and_retains_at_five() {
2301        let self_id = peer_id_from_byte(SELF_BYTE);
2302        let key = key_from_byte(0xB0);
2303        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2304        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2305        let candidate = candidate(key, strict_close_peers.clone());
2306        let first_seen = SystemTime::now();
2307        let now = matured(first_seen);
2308
2309        for (proofs, expect_delete) in [(6usize, true), (5usize, false)] {
2310            let mut present_by_key = HashMap::new();
2311            present_by_key.insert(
2312                key,
2313                strict_close_peers[..proofs]
2314                    .iter()
2315                    .copied()
2316                    .collect::<HashSet<_>>(),
2317            );
2318            let inputs = revalidation_inputs(
2319                &self_id,
2320                Some(first_seen),
2321                false,
2322                &admission_peers,
2323                &strict_close_peers,
2324                now,
2325            );
2326            let outcome = revalidate_record_prune_candidate(&candidate, &present_by_key, &inputs);
2327            if expect_delete {
2328                assert!(
2329                    matches!(outcome, PruneRevalidationOutcome::Delete),
2330                    "6 of 7 proofs must permit deletion"
2331                );
2332            } else {
2333                assert!(
2334                    matches!(outcome, PruneRevalidationOutcome::AuditFailed),
2335                    "5 of 7 proofs must retain the record"
2336                );
2337            }
2338        }
2339    }
2340
2341    /// Distance is not possession: a node outside a complete retention group
2342    /// still keeps a mature record its close group has not proven. How far
2343    /// outside it is cannot matter, since revalidation is given no distance.
2344    #[test]
2345    fn revalidation_retains_record_outside_complete_group_without_proofs() {
2346        let self_id = peer_id_from_byte(SELF_BYTE);
2347        let key = key_from_byte(0xB5);
2348        let retention_peers = peer_ids(PROD_RETENTION_WIDTH);
2349        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2350        let candidate = candidate(key, strict_close_peers.clone());
2351        let first_seen = SystemTime::now();
2352        let inputs = revalidation_inputs(
2353            &self_id,
2354            Some(first_seen),
2355            false,
2356            &retention_peers,
2357            &strict_close_peers,
2358            matured(first_seen),
2359        );
2360
2361        let outcome = revalidate_record_prune_candidate(&candidate, &HashMap::new(), &inputs);
2362
2363        assert!(
2364            matches!(outcome, PruneRevalidationOutcome::AuditFailed),
2365            "a record no close-group member proved must never be deleted"
2366        );
2367    }
2368
2369    /// #12: self moving back inside the retention width between the audit and
2370    /// deletion clears the state and prevents deletion, even with full proofs.
2371    #[test]
2372    fn revalidation_clears_and_prevents_deletion_when_back_in_range() {
2373        let self_id = peer_id_from_byte(SELF_BYTE);
2374        let key = key_from_byte(0xB1);
2375        let mut admission_peers = peer_ids(PROD_RETENTION_WIDTH - 1);
2376        admission_peers.push(self_id);
2377        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2378        let candidate = candidate(key, strict_close_peers.clone());
2379        let mut present_by_key = HashMap::new();
2380        present_by_key.insert(key, strict_close_peers.iter().copied().collect());
2381        let first_seen = SystemTime::now();
2382        let inputs = revalidation_inputs(
2383            &self_id,
2384            Some(first_seen),
2385            false,
2386            &admission_peers,
2387            &strict_close_peers,
2388            matured(first_seen),
2389        );
2390
2391        let outcome = revalidate_record_prune_candidate(&candidate, &present_by_key, &inputs);
2392
2393        assert!(matches!(
2394            outcome,
2395            PruneRevalidationOutcome::ClearedBackInRange
2396        ));
2397    }
2398
2399    /// #12: a strict-close-group membership change after the audit round
2400    /// invalidates stale positive reports — only proofs from CURRENT members
2401    /// count toward the CURRENT group's threshold.
2402    #[test]
2403    fn revalidation_rejects_proofs_from_stale_close_group() {
2404        let self_id = peer_id_from_byte(SELF_BYTE);
2405        let key = key_from_byte(0xB2);
2406        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2407        let old_close_group = peer_ids(PROD_CLOSE_GROUP);
2408        // Six positive proofs — a passing audit against the OLD group.
2409        let mut present_by_key = HashMap::new();
2410        present_by_key.insert(
2411            key,
2412            old_close_group[..6].iter().copied().collect::<HashSet<_>>(),
2413        );
2414        // The close group churned: only three audited peers remain members.
2415        let churned_close_group: Vec<PeerId> = old_close_group[4..7]
2416            .iter()
2417            .copied()
2418            .chain((20..24).map(peer_id_from_byte))
2419            .collect();
2420        let candidate = candidate(key, old_close_group);
2421        let first_seen = SystemTime::now();
2422        let inputs = revalidation_inputs(
2423            &self_id,
2424            Some(first_seen),
2425            false,
2426            &admission_peers,
2427            &churned_close_group,
2428            matured(first_seen),
2429        );
2430
2431        let outcome = revalidate_record_prune_candidate(&candidate, &present_by_key, &inputs);
2432
2433        assert!(
2434            matches!(outcome, PruneRevalidationOutcome::AuditFailed),
2435            "stale proofs must not satisfy the churned current close group"
2436        );
2437    }
2438
2439    /// A commitment re-gossiped between candidate selection and deletion
2440    /// vetoes the deletion even with a full set of proofs (TOCTOU re-check).
2441    #[test]
2442    fn revalidation_vetoes_deletion_for_recommitted_key() {
2443        let self_id = peer_id_from_byte(SELF_BYTE);
2444        let key = key_from_byte(0xB3);
2445        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2446        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2447        let candidate = candidate(key, strict_close_peers.clone());
2448        let mut present_by_key = HashMap::new();
2449        present_by_key.insert(key, strict_close_peers.iter().copied().collect());
2450        let first_seen = SystemTime::now();
2451        let inputs = revalidation_inputs(
2452            &self_id,
2453            Some(first_seen),
2454            true,
2455            &admission_peers,
2456            &strict_close_peers,
2457            matured(first_seen),
2458        );
2459
2460        let outcome = revalidate_record_prune_candidate(&candidate, &present_by_key, &inputs);
2461
2462        assert!(matches!(
2463            outcome,
2464            PruneRevalidationOutcome::HeldByCommitment
2465        ));
2466    }
2467
2468    /// A concurrently cleared or reset out-of-range timestamp downgrades the
2469    /// candidate back to hysteresis-pending instead of deleting.
2470    #[test]
2471    fn revalidation_requires_hysteresis_to_still_hold() {
2472        let self_id = peer_id_from_byte(SELF_BYTE);
2473        let key = key_from_byte(0xB4);
2474        let admission_peers = peer_ids(PROD_RETENTION_WIDTH);
2475        let strict_close_peers = peer_ids(PROD_CLOSE_GROUP);
2476        let candidate = candidate(key, strict_close_peers.clone());
2477        let mut present_by_key = HashMap::new();
2478        present_by_key.insert(
2479            key,
2480            strict_close_peers
2481                .iter()
2482                .copied()
2483                .collect::<HashSet<PeerId>>(),
2484        );
2485        let now = SystemTime::now();
2486
2487        for first_seen in [None, Some(now)] {
2488            let inputs = revalidation_inputs(
2489                &self_id,
2490                first_seen,
2491                false,
2492                &admission_peers,
2493                &strict_close_peers,
2494                now,
2495            );
2496            let outcome = revalidate_record_prune_candidate(&candidate, &present_by_key, &inputs);
2497            assert!(matches!(
2498                outcome,
2499                PruneRevalidationOutcome::HysteresisPending
2500            ));
2501        }
2502    }
2503
2504    // -- Prune-audit response grading (#11) -----------------------------------
2505
2506    const TEST_CHALLENGE_ID: u64 = 0x00C0_FFEE;
2507    const TEST_NONCE: [u8; 32] = [0xAB; 32];
2508    const TEST_RECORD_BYTES: &[u8] = b"prune audit record bytes";
2509
2510    fn digests_response(challenge_id: u64, digests: Vec<[u8; 32]>) -> ReplicationMessage {
2511        ReplicationMessage {
2512            request_id: challenge_id,
2513            body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
2514                challenge_id,
2515                digests,
2516            }),
2517        }
2518    }
2519
2520    fn graded_status(peer: &PeerId, key: &XorName, msg: ReplicationMessage) -> PruneAuditStatus {
2521        let expected = compute_audit_digest(&TEST_NONCE, peer.as_bytes(), key, TEST_RECORD_BYTES);
2522        let statuses =
2523            prune_audit_response_statuses(msg, TEST_CHALLENGE_ID, peer, &[(*key, expected)]);
2524        statuses
2525            .into_iter()
2526            .next()
2527            .map(|(_, status)| status)
2528            .expect("single-key batch returns exactly one status")
2529    }
2530
2531    #[test]
2532    fn prune_audit_status_accepts_only_a_matching_digest() {
2533        let peer = peer_id_from_byte(1);
2534        let key = key_from_byte(0xC0);
2535        let valid = compute_audit_digest(&TEST_NONCE, peer.as_bytes(), &key, TEST_RECORD_BYTES);
2536
2537        let status = graded_status(
2538            &peer,
2539            &key,
2540            digests_response(TEST_CHALLENGE_ID, vec![valid]),
2541        );
2542
2543        assert_eq!(status, PruneAuditStatus::Proven);
2544    }
2545
2546    #[test]
2547    fn prune_audit_status_rejects_absent_malformed_and_mismatching_responses() {
2548        let peer = peer_id_from_byte(1);
2549        let key = key_from_byte(0xC1);
2550        let valid = compute_audit_digest(&TEST_NONCE, peer.as_bytes(), &key, TEST_RECORD_BYTES);
2551
2552        // Absent-key sentinel is a negative answer.
2553        let absent = digests_response(TEST_CHALLENGE_ID, vec![ABSENT_KEY_DIGEST]);
2554        assert_eq!(graded_status(&peer, &key, absent), PruneAuditStatus::Failed);
2555
2556        // A digest over different bytes does not prove possession.
2557        let mismatch = digests_response(TEST_CHALLENGE_ID, vec![[0x11; 32]]);
2558        assert_eq!(
2559            graded_status(&peer, &key, mismatch),
2560            PruneAuditStatus::Failed
2561        );
2562
2563        // A malformed digest count never counts.
2564        let wrong_count = digests_response(TEST_CHALLENGE_ID, vec![valid, valid]);
2565        assert_eq!(
2566            graded_status(&peer, &key, wrong_count),
2567            PruneAuditStatus::Failed
2568        );
2569
2570        // A response bound to a different challenge never counts.
2571        let stale_challenge = digests_response(TEST_CHALLENGE_ID + 1, vec![valid]);
2572        assert_eq!(
2573            graded_status(&peer, &key, stale_challenge),
2574            PruneAuditStatus::Failed
2575        );
2576
2577        // An explicit rejection never counts as a positive proof; it grades to
2578        // the distinct `Rejected` status (a non-recovering, labelled failure).
2579        let rejected = ReplicationMessage {
2580            request_id: TEST_CHALLENGE_ID,
2581            body: ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
2582                challenge_id: TEST_CHALLENGE_ID,
2583                reason: "test".to_string(),
2584            }),
2585        };
2586        assert_eq!(
2587            graded_status(&peer, &key, rejected),
2588            PruneAuditStatus::Rejected
2589        );
2590
2591        // An unexpected message type never counts.
2592        let unexpected = ReplicationMessage {
2593            request_id: TEST_CHALLENGE_ID,
2594            body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
2595                challenge_id: TEST_CHALLENGE_ID,
2596                nonce: TEST_NONCE,
2597                challenged_peer_id: *peer.as_bytes(),
2598                keys: vec![key],
2599            }),
2600        };
2601        assert_eq!(
2602            graded_status(&peer, &key, unexpected),
2603            PruneAuditStatus::Failed
2604        );
2605    }
2606
2607    /// A rejection is never a possession signal, so it maps to the distinct
2608    /// `Rejected` status (which drives a labelled, non-recovering penalty), and
2609    /// its `reason` text is never parsed. A challenge-id mismatch stays a plain
2610    /// `Failed`.
2611    #[test]
2612    fn any_rejection_reason_maps_to_the_rejected_status_without_parsing() {
2613        let peer = peer_id_from_byte(1);
2614        let key = key_from_byte(0xC3);
2615
2616        for reason in [
2617            "challenge contains 83 keys, limit is 60",
2618            "challenged_peer_id does not match this node",
2619            "some future reason we have never seen",
2620        ] {
2621            let rejected = ReplicationMessage {
2622                request_id: TEST_CHALLENGE_ID,
2623                body: ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
2624                    challenge_id: TEST_CHALLENGE_ID,
2625                    reason: reason.to_string(),
2626                }),
2627            };
2628            assert_eq!(
2629                graded_status(&peer, &key, rejected),
2630                PruneAuditStatus::Rejected,
2631                "reason {reason:?} should map to Rejected regardless of wording"
2632            );
2633        }
2634
2635        let mismatched = ReplicationMessage {
2636            request_id: TEST_CHALLENGE_ID,
2637            body: ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
2638                challenge_id: TEST_CHALLENGE_ID + 1,
2639                reason: "challenge contains 83 keys, limit is 60".to_string(),
2640            }),
2641        };
2642        assert_eq!(
2643            graded_status(&peer, &key, mismatched),
2644            PruneAuditStatus::Failed,
2645            "a challenge-id mismatch is a plain failure, not a capacity signal"
2646        );
2647    }
2648
2649    #[test]
2650    fn prune_audit_status_bootstrap_claim_is_not_a_positive_proof() {
2651        let peer = peer_id_from_byte(1);
2652        let key = key_from_byte(0xC2);
2653
2654        let bootstrapping = ReplicationMessage {
2655            request_id: TEST_CHALLENGE_ID,
2656            body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
2657                challenge_id: TEST_CHALLENGE_ID,
2658            }),
2659        };
2660        assert_eq!(
2661            graded_status(&peer, &key, bootstrapping),
2662            PruneAuditStatus::Bootstrapping
2663        );
2664
2665        let mismatched = ReplicationMessage {
2666            request_id: TEST_CHALLENGE_ID,
2667            body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
2668                challenge_id: TEST_CHALLENGE_ID + 1,
2669            }),
2670        };
2671        assert_eq!(
2672            graded_status(&peer, &key, mismatched),
2673            PruneAuditStatus::Failed
2674        );
2675    }
2676}