Skip to main content

itzma_core/
maintain.rs

1//! Maintenance: decide whether a compaction is due, run it, then collect.
2//!
3//! [`Namespace::maintain`](crate::Namespace::maintain) is one call that a
4//! caller schedules. It looks at the WAL tail, compacts if a threshold is
5//! crossed, runs [`gc`](crate::Namespace::gc) if asked, and reports what it did.
6//! The library starts no task of its own. This module holds the options, the
7//! report and the decision, which needs no storage and is tested on its own.
8
9use std::time::Duration;
10
11use crate::compaction::{Compaction, CompactionOptions};
12use crate::gc::{GcOptions, GcReport, WalObject};
13
14/// The default for [`CompactTrigger::tail_objects`].
15pub const DEFAULT_TAIL_OBJECTS: usize = 64;
16
17/// The default for [`CompactTrigger::tail_bytes`]: 64 MiB.
18pub const DEFAULT_TAIL_BYTES: u64 = 64 * 1024 * 1024;
19
20/// When the WAL tail is long enough that it should be folded into a segment.
21///
22/// A query reads every tail object, one GET each, so the count is latency and
23/// the bytes are the read budget. Any trigger that is crossed makes a
24/// compaction due, as long as the tail is not empty. Turn one off with
25/// `usize::MAX`, `u64::MAX` or `None`. Zero means "any tail at all".
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct CompactTrigger {
28    /// Due once the tail has this many objects. Default
29    /// [`DEFAULT_TAIL_OBJECTS`].
30    pub tail_objects: usize,
31    /// Due once the tail is this many stored bytes. Default
32    /// [`DEFAULT_TAIL_BYTES`].
33    pub tail_bytes: u64,
34    /// Due once the oldest tail object is this old. Off by default, since a
35    /// namespace with a slow trickle of writes would otherwise be merged over
36    /// and over, and a merge rewrites every segment. It is what makes
37    /// a small, slow namespace fold at all, and only folded objects can be
38    /// fenced by [`gc`](crate::Namespace::gc). The age is the store's write
39    /// time against this machine's clock.
40    pub tail_age: Option<Duration>,
41}
42
43impl Default for CompactTrigger {
44    fn default() -> Self {
45        Self {
46            tail_objects: DEFAULT_TAIL_OBJECTS,
47            tail_bytes: DEFAULT_TAIL_BYTES,
48            tail_age: None,
49        }
50    }
51}
52
53/// Settings for [`Namespace::maintain`](crate::Namespace::maintain).
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct MaintenanceOptions {
56    /// When a compaction is due.
57    pub compact_when: CompactTrigger,
58    /// What the compaction does when it runs. A namespace with more live
59    /// segments than [`CompactionOptions::max_segments`] also makes one due, so
60    /// the merge is not left waiting for a tail.
61    pub compaction: CompactionOptions,
62    /// The collection to run after the compaction, or `None` to run none. It
63    /// runs even when no compaction was due. Fencing is a per-call flag in
64    /// here ([`GcOptions::fence_wal`]), not a property of the namespace.
65    pub gc: Option<GcOptions>,
66}
67
68impl Default for MaintenanceOptions {
69    /// The default trigger and compaction, and a default collection, which
70    /// deletes dead segments a day old and leaves the WAL alone.
71    fn default() -> Self {
72        Self {
73            compact_when: CompactTrigger::default(),
74            compaction: CompactionOptions::default(),
75            gc: Some(GcOptions::default()),
76        }
77    }
78}
79
80/// What a call to [`Namespace::maintain`](crate::Namespace::maintain) saw and
81/// did.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct MaintenanceReport {
84    /// WAL objects past the fold point when the call looked.
85    pub tail_objects: usize,
86    /// Their stored size in bytes.
87    pub tail_bytes: u64,
88    /// What the compaction did, or `None` if none was due. `Some(Superseded)`
89    /// means another process compacted first, which is fine.
90    pub compaction: Option<Compaction>,
91    /// What the collection did, or `None` if none was asked for.
92    pub gc: Option<GcReport>,
93}
94
95/// What the listing of the tail shows.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub(crate) struct Tail {
98    pub(crate) objects: usize,
99    pub(crate) bytes: u64,
100    /// Write time of the oldest object in unix milliseconds, if there is one.
101    pub(crate) oldest_ms: Option<i64>,
102}
103
104impl Tail {
105    pub(crate) fn of(objects: &[WalObject]) -> Self {
106        Self {
107            objects: objects.len(),
108            bytes: objects.iter().map(|o| o.size).sum(),
109            oldest_ms: objects.iter().map(|o| o.modified_ms).min(),
110        }
111    }
112}
113
114/// Whether a compaction is due. Pure: no storage and no clock, `now_ms` is
115/// passed in.
116///
117/// An empty tail is never due by itself, whatever the thresholds say. Too many
118/// live segments is due even then, since a merge is what brings them down.
119pub(crate) fn due(
120    trigger: &CompactTrigger,
121    tail: Tail,
122    live_segments: usize,
123    max_segments: usize,
124    now_ms: i64,
125) -> bool {
126    if live_segments > max_segments.max(1) {
127        return true;
128    }
129    if tail.objects == 0 {
130        return false;
131    }
132    let old_enough = match (trigger.tail_age, tail.oldest_ms) {
133        (Some(age), Some(oldest)) => {
134            let age_ms = i64::try_from(age.as_millis()).unwrap_or(i64::MAX);
135            now_ms.saturating_sub(oldest).max(0) >= age_ms
136        }
137        _ => false,
138    };
139    tail.objects >= trigger.tail_objects || tail.bytes >= trigger.tail_bytes || old_enough
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    const NOW: i64 = 1_000_000;
147
148    fn tail(objects: usize, bytes: u64, oldest_ms: i64) -> Tail {
149        Tail {
150            objects,
151            bytes,
152            oldest_ms: (objects > 0).then_some(oldest_ms),
153        }
154    }
155
156    fn only(f: impl FnOnce(&mut CompactTrigger)) -> CompactTrigger {
157        let mut t = CompactTrigger {
158            tail_objects: usize::MAX,
159            tail_bytes: u64::MAX,
160            tail_age: None,
161        };
162        f(&mut t);
163        t
164    }
165
166    #[test]
167    fn the_defaults_are_the_documented_ones() {
168        let t = CompactTrigger::default();
169        assert_eq!(t.tail_objects, 64);
170        assert_eq!(t.tail_bytes, 64 * 1024 * 1024);
171        assert_eq!(t.tail_age, None);
172        let o = MaintenanceOptions::default();
173        assert_eq!(o.compaction, CompactionOptions::default());
174        assert_eq!(o.gc, Some(GcOptions::default()));
175    }
176
177    #[test]
178    fn an_empty_tail_is_never_due_even_at_zero() {
179        let zero = CompactTrigger {
180            tail_objects: 0,
181            tail_bytes: 0,
182            tail_age: Some(Duration::ZERO),
183        };
184        assert!(!due(&zero, tail(0, 0, 0), 1, 8, NOW));
185    }
186
187    #[test]
188    fn each_count_fires_at_its_edge_and_not_below() {
189        let objects = only(|t| t.tail_objects = 3);
190        assert!(!due(&objects, tail(2, 0, NOW), 1, 8, NOW));
191        assert!(due(&objects, tail(3, 0, NOW), 1, 8, NOW));
192        let bytes = only(|t| t.tail_bytes = 500);
193        assert!(!due(&bytes, tail(1, 499, NOW), 1, 8, NOW));
194        assert!(due(&bytes, tail(1, 500, NOW), 1, 8, NOW));
195    }
196
197    #[test]
198    fn the_age_is_measured_from_the_oldest_object() {
199        let age = only(|t| t.tail_age = Some(Duration::from_secs(60)));
200        assert!(!due(&age, tail(2, 0, NOW - 59_999), 1, 8, NOW));
201        assert!(due(&age, tail(2, 0, NOW - 60_000), 1, 8, NOW));
202        // A write time in the future counts as age zero.
203        assert!(!due(&age, tail(2, 0, NOW + 10_000), 1, 8, NOW));
204    }
205
206    #[test]
207    fn a_trigger_that_is_off_never_fires() {
208        let off = only(|_| {});
209        assert!(!due(&off, tail(1_000_000, u64::MAX - 1, 0), 1, 8, NOW));
210    }
211
212    #[test]
213    fn too_many_segments_is_due_with_no_tail_at_all() {
214        let off = only(|_| {});
215        assert!(due(&off, tail(0, 0, 0), 9, 8, NOW));
216        assert!(!due(&off, tail(0, 0, 0), 8, 8, NOW));
217        // Zero is treated as one, as in compaction.
218        assert!(due(&off, tail(0, 0, 0), 2, 0, NOW));
219        assert!(!due(&off, tail(0, 0, 0), 1, 0, NOW));
220    }
221}