Skip to main content

ant_node/replication/
retention.rs

1//! Pressure-gated retention (ADR-0028).
2//!
3//! A node keeps every record it holds while its disk has room, including the
4//! records it is no longer responsible for, and goes on serving them. Leaving
5//! a record's range only makes the record *eligible* to be erased. The prune
6//! passes erase eligible records only while the partition holding the record
7//! store is under pressure: farthest from this node first, each after its
8//! current close group proves possession, and only until the pressure ends.
9//!
10//! This module holds the policy both prune passes share: when the partition
11//! is under pressure, with hysteresis so a node erases in spells rather than
12//! one record at a time, and in what order eligible records go.
13
14use std::cmp::Reverse;
15use std::collections::{HashMap, HashSet};
16use std::time::{Duration, Instant};
17
18use parking_lot::Mutex;
19use saorsa_core::identity::PeerId;
20
21use crate::ant_protocol::XorName;
22use crate::client::xor_distance;
23use crate::storage::{ChunkStore, DiskSpace};
24
25/// Denominator of the free-space shares below.
26const PERCENT: u128 = 100;
27
28/// Free share of the partition, in percent, below which pressure starts.
29const PRESSURE_ENTER_FREE_PERCENT: u128 = 10;
30
31/// Free share, in percent, at or above which pressure ends.
32///
33/// Above the entry share, so a node that starts erasing frees a margin before
34/// it stops, instead of erasing one record each time a write takes it back
35/// under the line.
36const PRESSURE_EXIT_FREE_PERCENT: u128 = 15;
37
38/// Multiple of the store's reserve below which pressure starts, whatever the
39/// free share.
40///
41/// On a small partition the free share can stay above
42/// [`PRESSURE_ENTER_FREE_PERCENT`] until the store refuses writes at its
43/// reserve. This starts erasing while there is still room above the reserve.
44const PRESSURE_ENTER_RESERVE_MULTIPLE: u64 = 2;
45
46/// Multiple of the store's reserve that must be free, as well as
47/// [`PRESSURE_EXIT_FREE_PERCENT`], for pressure to end.
48const PRESSURE_EXIT_RESERVE_MULTIPLE: u64 = 3;
49
50/// Which store a record lives in.
51///
52/// Demotions are kept per kind: a chunk and a pointer may share an address.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub enum RecordKind {
55    /// A content-addressed chunk.
56    Chunk,
57    /// A pointer record.
58    Pointer,
59}
60
61/// Disk-pressure state shared by a node's chunk and pointer prune passes.
62#[derive(Debug, Default)]
63pub struct DiskPressure {
64    state: Mutex<PressureState>,
65}
66
67#[derive(Debug, Default)]
68struct PressureState {
69    /// Whether the partition is under pressure.
70    active: bool,
71    /// Per kind, the records whose possession check failed in this spell of
72    /// pressure, each with when it last failed, as a count of demotions. They
73    /// are tried after every other eligible record, oldest failure first, so
74    /// records nobody can prove yet never keep the rest from their turn.
75    demoted: HashMap<RecordKind, HashMap<XorName, u64>>,
76    /// How many demotions this node has recorded.
77    demotions: u64,
78    /// When the last prune pass finished.
79    last_pass: Option<Instant>,
80}
81
82impl DiskPressure {
83    /// Update the state from a fresh measurement, and say whether the node may
84    /// erase eligible records now.
85    ///
86    /// A failed measurement (`None`) says nothing about free space: nothing is
87    /// erased on it, and the state is left for the next measurement to decide.
88    /// A spell of pressure that ends forgets its demotions.
89    pub fn observe(&self, space: Option<DiskSpace>, reserve: u64) -> bool {
90        let Some(space) = space else {
91            return false;
92        };
93        let mut state = self.state.lock();
94        let active = under_pressure(state.active, space, reserve);
95        if state.active && !active {
96            state.demoted.clear();
97        }
98        state.active = active;
99        active
100    }
101
102    /// Measure `store`'s partition afresh and [`Self::observe`] it.
103    ///
104    /// Some filesystems show freed space only after a later commit, so a pass
105    /// may erase a little past the exit line. That is bounded by one pass's
106    /// budget, and costs only out-of-range records the group has proven.
107    pub fn observe_store(&self, store: &ChunkStore) -> bool {
108        self.observe(store.disk_space(), store.disk_reserve())
109    }
110
111    /// Whether a prune pass should run now.
112    ///
113    /// A pass runs after every completed neighbour-sync cycle. Under pressure
114    /// it also runs on other rounds, `spacing` after the last pass finished:
115    /// rounds run back to back while newly close peers are synced, and each
116    /// pass scans every stored record.
117    pub fn prune_pass_due(
118        &self,
119        cycle_complete: bool,
120        store: &ChunkStore,
121        spacing: Duration,
122    ) -> bool {
123        let under_pressure = !cycle_complete && self.observe_store(store);
124        self.pass_due_at(cycle_complete, under_pressure, spacing, Instant::now())
125    }
126
127    fn pass_due_at(
128        &self,
129        cycle_complete: bool,
130        under_pressure: bool,
131        spacing: Duration,
132        now: Instant,
133    ) -> bool {
134        let spaced = self
135            .state
136            .lock()
137            .last_pass
138            .is_none_or(|last| now.saturating_duration_since(last) >= spacing);
139        cycle_complete || (under_pressure && spaced)
140    }
141
142    /// Record that a prune pass has finished, so the next one is spaced from it.
143    pub fn prune_pass_finished(&self) {
144        self.finish_pass_at(Instant::now());
145    }
146
147    fn finish_pass_at(&self, now: Instant) {
148        self.state.lock().last_pass = Some(now);
149    }
150
151    /// Record that `key`'s possession check failed in this spell of pressure,
152    /// so it is tried after the other eligible records, and after the records
153    /// that failed before it.
154    ///
155    /// Ignored outside a spell, which has no order to change.
156    pub fn demote(&self, kind: RecordKind, key: XorName) {
157        let mut state = self.state.lock();
158        if state.active {
159            let failure = state.demotions;
160            state.demotions = failure.saturating_add(1);
161            state.demoted.entry(kind).or_default().insert(key, failure);
162        }
163    }
164
165    /// The first `limit` of `records` in the order to try erasing them:
166    /// records not demoted, farthest from `self_id` first, then demoted ones,
167    /// oldest failure first.
168    ///
169    /// Farthest first, so the records closest to this node go last. Demoted
170    /// records wait while records not yet tried fill the limit: they stay on
171    /// disk meanwhile, and the limit still goes to records that may free space.
172    /// Once a pass has room for them, oldest failure first gives each its turn
173    /// again. Demotions of records that are no longer candidates are forgotten.
174    pub fn erasure_order<T>(
175        &self,
176        kind: RecordKind,
177        self_id: &PeerId,
178        mut records: Vec<T>,
179        limit: usize,
180        key_of: impl Fn(&T) -> XorName,
181    ) -> Vec<T> {
182        let candidates: HashSet<XorName> = records.iter().map(&key_of).collect();
183        let demoted = self.current_demotions(kind, &candidates);
184        let self_xor: XorName = *self_id.as_bytes();
185        let order_key = |record: &T| {
186            let key = key_of(record);
187            (
188                // `None` sorts first, so records not demoted go first.
189                demoted.get(&key).copied(),
190                Reverse(xor_distance(&self_xor, &key)),
191            )
192        };
193        if limit == 0 {
194            return Vec::new();
195        }
196        if limit < records.len() {
197            records.select_nth_unstable_by_key(limit - 1, &order_key);
198            records.truncate(limit);
199        }
200        records.sort_by_key(order_key);
201        records
202    }
203
204    /// The demotions of `kind` that still apply to `candidates`.
205    fn current_demotions(
206        &self,
207        kind: RecordKind,
208        candidates: &HashSet<XorName>,
209    ) -> HashMap<XorName, u64> {
210        let mut state = self.state.lock();
211        let demoted = state.demoted.entry(kind).or_default();
212        demoted.retain(|key, _| candidates.contains(key));
213        demoted.clone()
214    }
215}
216
217/// Whether the partition is under pressure, given whether it already was.
218fn under_pressure(was_active: bool, space: DiskSpace, reserve: u64) -> bool {
219    let free_share_below =
220        |percent: u128| u128::from(space.available) * PERCENT < u128::from(space.total) * percent;
221    if was_active {
222        free_share_below(PRESSURE_EXIT_FREE_PERCENT)
223            || space.available < reserve.saturating_mul(PRESSURE_EXIT_RESERVE_MULTIPLE)
224    } else {
225        free_share_below(PRESSURE_ENTER_FREE_PERCENT)
226            || space.available < reserve.saturating_mul(PRESSURE_ENTER_RESERVE_MULTIPLE)
227    }
228}
229
230#[cfg(test)]
231#[allow(clippy::unwrap_used, clippy::expect_used)]
232mod tests {
233    use super::*;
234
235    const TOTAL: u64 = 1_000_000;
236    const NO_RESERVE: u64 = 0;
237    const NO_LIMIT: usize = usize::MAX;
238
239    fn space(available: u64) -> DiskSpace {
240        DiskSpace {
241            available,
242            total: TOTAL,
243        }
244    }
245
246    fn key(first: u8) -> XorName {
247        let mut key = [0u8; 32];
248        key[0] = first;
249        key
250    }
251
252    fn self_id() -> PeerId {
253        PeerId::from_bytes([0u8; 32])
254    }
255
256    fn under_pressure_now() -> DiskPressure {
257        let pressure = DiskPressure::default();
258        assert!(pressure.observe(Some(space(0)), NO_RESERVE));
259        pressure
260    }
261
262    #[test]
263    fn pressure_starts_below_ten_percent_free_and_ends_at_fifteen() {
264        let pressure = DiskPressure::default();
265        assert!(
266            !pressure.observe(Some(space(100_000)), NO_RESERVE),
267            "10% free is not pressure"
268        );
269        assert!(
270            pressure.observe(Some(space(99_999)), NO_RESERVE),
271            "below 10% free is"
272        );
273        assert!(
274            pressure.observe(Some(space(149_999)), NO_RESERVE),
275            "pressure holds until 15% is free"
276        );
277        assert!(
278            !pressure.observe(Some(space(150_000)), NO_RESERVE),
279            "15% free ends it"
280        );
281        assert!(
282            !pressure.observe(Some(space(120_000)), NO_RESERVE),
283            "between the lines, a node not under pressure stays out of it"
284        );
285    }
286
287    #[test]
288    fn a_small_partition_comes_under_pressure_before_its_reserve() {
289        const RESERVE: u64 = 300_000;
290        let pressure = DiskPressure::default();
291        // 50% free is far above the free-share line, but under twice the reserve.
292        assert!(pressure.observe(Some(space(500_000)), RESERVE));
293        // Pressure lasts until three times the reserve is free.
294        assert!(pressure.observe(Some(space(899_999)), RESERVE));
295        assert!(!pressure.observe(Some(space(900_000)), RESERVE));
296    }
297
298    #[test]
299    fn a_failed_measurement_erases_nothing_and_keeps_the_state() {
300        let pressure = under_pressure_now();
301        assert!(
302            !pressure.observe(None, NO_RESERVE),
303            "nothing is erased on no measurement"
304        );
305        assert!(
306            pressure.observe(Some(space(149_999)), NO_RESERVE),
307            "the spell continues once a measurement says so"
308        );
309    }
310
311    #[test]
312    fn passes_under_pressure_are_spaced_and_cycles_always_run_one() {
313        const SPACING: Duration = Duration::from_mins(10);
314        const SOON: Duration = Duration::from_secs(1);
315        let pressure = DiskPressure::default();
316        let start = Instant::now();
317
318        assert!(pressure.pass_due_at(false, true, SPACING, start));
319        pressure.finish_pass_at(start + SOON);
320        assert!(
321            !pressure.pass_due_at(false, true, SPACING, start + SOON),
322            "a round straight after a pass finished waits"
323        );
324        assert!(
325            pressure.pass_due_at(true, false, SPACING, start + SOON),
326            "a completed cycle always runs one"
327        );
328        assert!(
329            !pressure.pass_due_at(false, true, SPACING, start + SPACING),
330            "spaced from when the last pass finished, not when it started"
331        );
332        assert!(pressure.pass_due_at(false, true, SPACING, start + SOON + SPACING));
333        assert!(
334            !pressure.pass_due_at(false, false, SPACING, start + SPACING * 3),
335            "nothing runs without pressure between cycles"
336        );
337    }
338
339    #[test]
340    fn records_go_farthest_first_and_demoted_ones_last() {
341        let pressure = under_pressure_now();
342        let (near, middle, far) = (key(0x01), key(0x40), key(0xF0));
343        pressure.demote(RecordKind::Chunk, far);
344
345        let order = pressure.erasure_order(
346            RecordKind::Chunk,
347            &self_id(),
348            vec![near, far, middle],
349            NO_LIMIT,
350            |k| *k,
351        );
352        assert_eq!(order, vec![middle, near, far]);
353
354        // A pointer at the same address is not demoted by the chunk's failure.
355        let order = pressure.erasure_order(
356            RecordKind::Pointer,
357            &self_id(),
358            vec![near, far],
359            NO_LIMIT,
360            |k| *k,
361        );
362        assert_eq!(order, vec![far, near]);
363    }
364
365    #[test]
366    fn a_limit_takes_the_first_records_of_the_whole_order() {
367        let pressure = under_pressure_now();
368        let candidates: Vec<XorName> = (1..=9).map(|first| key(first * 0x10)).collect();
369        pressure.demote(RecordKind::Chunk, key(0x90));
370        let order = pressure.erasure_order(RecordKind::Chunk, &self_id(), candidates, 3, |k| *k);
371        assert_eq!(order, vec![key(0x80), key(0x70), key(0x60)]);
372    }
373
374    #[test]
375    fn no_candidate_waits_more_than_a_round_for_its_next_turn() {
376        // Nothing is ever proven, so every candidate stays one for the whole
377        // spell. Passes must keep reaching all of them, not settle on
378        // retrying the farthest batch once each has failed once.
379        const CANDIDATES: u8 = 5;
380        const BATCH: usize = 2;
381        const PASSES: usize = 12;
382        let pressure = under_pressure_now();
383        let candidates: Vec<XorName> = (1..=CANDIDATES).map(|first| key(first * 0x10)).collect();
384        let passes_per_round = usize::from(CANDIDATES).div_ceil(BATCH);
385
386        let mut turns: HashMap<XorName, Vec<usize>> = HashMap::new();
387        for pass in 0..PASSES {
388            let batch = pressure.erasure_order(
389                RecordKind::Pointer,
390                &self_id(),
391                candidates.clone(),
392                BATCH,
393                |k| *k,
394            );
395            for key in batch {
396                turns.entry(key).or_default().push(pass);
397                pressure.demote(RecordKind::Pointer, key);
398            }
399        }
400
401        assert_eq!(
402            turns.len(),
403            usize::from(CANDIDATES),
404            "every candidate had a turn"
405        );
406        for (key, passes) in &turns {
407            assert!(
408                passes[0] < passes_per_round,
409                "{key:?} first tried in the first round"
410            );
411            let longest_wait = passes
412                .windows(2)
413                .map(|pair| pair[1] - pair[0])
414                .chain(std::iter::once(PASSES - passes[passes.len() - 1]))
415                .max()
416                .unwrap_or(PASSES);
417            assert!(
418                longest_wait <= passes_per_round,
419                "{key:?} waited {longest_wait} passes for a turn"
420            );
421        }
422    }
423
424    #[test]
425    fn a_few_new_candidates_each_pass_do_not_stop_failed_ones_being_retried() {
426        // A new candidate arrives every pass and nothing is ever proven. A
427        // new one is always untried, so waiting for every candidate to have
428        // failed would leave the farthest failed ones holding all other slots.
429        const INITIAL: u8 = 8;
430        const BATCH: usize = 3;
431        const PASSES: u8 = 40;
432        const MIN_TURNS: usize = 2;
433        let pressure = under_pressure_now();
434        let initial: Vec<XorName> = (1..=INITIAL).map(|first| key(first * 0x10)).collect();
435        let mut candidates = initial.clone();
436
437        let mut turns: HashMap<XorName, usize> = HashMap::new();
438        for pass in 0..PASSES {
439            let mut arrival = key(0x01);
440            arrival[1] = pass;
441            candidates.push(arrival);
442            let batch = pressure.erasure_order(
443                RecordKind::Chunk,
444                &self_id(),
445                candidates.clone(),
446                BATCH,
447                |k| *k,
448            );
449            for key in batch {
450                *turns.entry(key).or_default() += 1;
451                pressure.demote(RecordKind::Chunk, key);
452            }
453        }
454
455        for key in &initial {
456            let taken = turns.get(key).copied().unwrap_or_default();
457            assert!(
458                taken >= MIN_TURNS,
459                "{key:?} had {taken} turns in {PASSES} passes"
460            );
461        }
462    }
463
464    #[test]
465    fn demotions_end_with_the_spell_and_need_one_to_start() {
466        let pressure = DiskPressure::default();
467        let (near, far) = (key(0x01), key(0xF0));
468
469        pressure.demote(RecordKind::Chunk, far);
470        assert!(pressure.observe(Some(space(0)), NO_RESERVE));
471        let order = pressure.erasure_order(
472            RecordKind::Chunk,
473            &self_id(),
474            vec![near, far],
475            NO_LIMIT,
476            |k| *k,
477        );
478        assert_eq!(
479            order,
480            vec![far, near],
481            "a demotion outside a spell is ignored"
482        );
483
484        pressure.demote(RecordKind::Chunk, far);
485        assert!(!pressure.observe(Some(space(TOTAL)), NO_RESERVE));
486        assert!(pressure.observe(Some(space(0)), NO_RESERVE));
487        let order = pressure.erasure_order(
488            RecordKind::Chunk,
489            &self_id(),
490            vec![near, far],
491            NO_LIMIT,
492            |k| *k,
493        );
494        assert_eq!(
495            order,
496            vec![far, near],
497            "a new spell starts with no demotions"
498        );
499    }
500}