Diffinery

homeflare/celldpublic

celld/crates/ltx/src/store.rs
263 lines · 9.6 KBRaw History
1//! store.rs — snapshot/TXID bookkeeping + retention selection.
2//!
3//! Ported from the `Enforce*Retention*` algorithms in [email protected]
4//! `compactor.go` (`EnforceRetentionByTXID`) and `db.go`
5//! (`EnforceSnapshotRetention`, `EnforceL0RetentionByTime`).
6//!
7//! # Scope (KEEP set, PLAN.md §2)
8//! The upstream `Store` is mostly multi-DB orchestration, **compaction** level
9//! monitors, heartbeats, and validation — all OUT of the one-shot scope
10//! (L0-only, single replica, no compaction). What remains and matters here is
11//! the **retention selection** logic: which LTX files to delete, with the exact
12//! boundary semantics that are easy to get subtly wrong (strict `<`, keep the
13//! newest file, stop early to preserve a contiguous tail). These are extracted
14//! as pure, testable functions operating on a sorted `&[FileInfo]`.
15
16use crate::ltx::FileInfo;
17use crate::TXID;
18use std::time::SystemTime;
19
20/// Returns the maximum `max_txid` across a sorted file slice, or `TXID(0)` if
21/// empty. Ported from `FileInfoSlice.MaxTXID` (ltx.go:612-619).
22pub fn max_txid(files: &[FileInfo]) -> TXID {
23 files.last().map(|f| f.max_txid).unwrap_or(TXID(0))
24}
25
26/// The keep-newest invariant shared by every retention path: if the last
27/// file marked for deletion is the newest file overall, un-mark it so at least
28/// one file always survives. Mirrors the Go idiom
29/// `if deleted[len-1] == lastInfo { deleted = deleted[:len-1] }`.
30fn keep_newest(deleted: &mut Vec<FileInfo>, files: &[FileInfo]) {
31 if let (Some(last_del), Some(last)) = (deleted.last(), files.last()) {
32 if last_del == last {
33 deleted.pop();
34 }
35 }
36}
37
38/// Selects files at a level whose `max_txid` is **strictly below** `txid` for
39/// deletion, always keeping at least the newest file.
40///
41/// Ported from `Compactor.EnforceRetentionByTXID` (compactor.go:288-313).
42/// `files` must be sorted ascending by txid (the `LTXFiles` iterator contract).
43/// NOTE the inequality is strict `<`, not `<=` — a file whose `max_txid == txid`
44/// is retained (it is still needed to reach `txid`).
45pub fn select_retention_by_txid(files: &[FileInfo], txid: TXID) -> Vec<FileInfo> {
46 let mut deleted: Vec<FileInfo> = files
47 .iter()
48 .filter(|f| f.max_txid < txid)
49 .cloned()
50 .collect();
51 keep_newest(&mut deleted, files);
52 deleted
53}
54
55/// Selects snapshot files created strictly **before** `before` for deletion and
56/// returns `(deleted, min_retained_snapshot_txid)`. Always keeps the newest
57/// snapshot. The returned TXID is the lowest `max_txid` among *retained*
58/// snapshots (used to cascade retention into lower levels); `TXID(0)` if none.
59///
60/// Ported from `DB.EnforceSnapshotRetention` (db.go:2063-2116). A file with an
61/// unknown (`None`) timestamp is conservatively retained (least-data-loss).
62pub fn select_snapshot_retention(files: &[FileInfo], before: SystemTime) -> (Vec<FileInfo>, TXID) {
63 let mut deleted = Vec::new();
64 let mut min_snapshot_txid = TXID(0);
65 for f in files {
66 // CreatedAt.Before(timestamp)
67 if f.created_at.is_some_and(|t| t < before) {
68 deleted.push(f.clone());
69 continue;
70 }
71 // Track the lowest retained snapshot txid.
72 if min_snapshot_txid == TXID(0) || f.max_txid < min_snapshot_txid {
73 min_snapshot_txid = f.max_txid;
74 }
75 }
76 keep_newest(&mut deleted, files);
77 (deleted, min_snapshot_txid)
78}
79
80/// Selects L0 files eligible for time-based retention: files older than
81/// `threshold` that have already been compacted into L1 (`max_txid <=
82/// max_l1_txid`). Stops at the first file newer than `threshold` to preserve a
83/// contiguous retained tail, and only applies the keep-newest rule when the
84/// whole level was processed.
85///
86/// Ported from `DB.EnforceL0RetentionByTime` (db.go:2118-2205).
87///
88/// In the KEEP scope there is **no compaction**, so `max_l1_txid` is always
89/// `TXID(0)` and this returns empty — L0 files accumulate (Risk R-3, accepted:
90/// correct, just a slower restore on a long-lived DB). The full algorithm is
91/// ported anyway so the behavior is correct the moment compaction is added.
92pub fn select_l0_retention_by_time(
93 l0: &[FileInfo],
94 max_l1_txid: TXID,
95 threshold: SystemTime,
96) -> Vec<FileInfo> {
97 if max_l1_txid == TXID(0) {
98 return Vec::new();
99 }
100
101 let mut deleted = Vec::new();
102 let mut processed_all = true;
103 for f in l0 {
104 // Missing timestamps fall back to the threshold (db.go:2171-2178).
105 let created = f.created_at.unwrap_or(threshold);
106 if created > threshold {
107 // CreatedAt.After(threshold): L0 is ordered, so once we reach a
108 // newer file we stop — deleting past it would create a gap.
109 processed_all = false;
110 break;
111 }
112 if f.max_txid <= max_l1_txid {
113 deleted.push(f.clone());
114 }
115 // else: not yet compacted into L1 — retain it.
116 }
117
118 if processed_all {
119 keep_newest(&mut deleted, l0);
120 }
121 deleted
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use std::time::Duration;
128
129 fn fi(min: u64, max: u64, created: Option<SystemTime>) -> FileInfo {
130 FileInfo {
131 level: 0,
132 min_txid: TXID(min),
133 max_txid: TXID(max),
134 size: 1,
135 created_at: created,
136 ..Default::default()
137 }
138 }
139
140 fn files(n: u64) -> Vec<FileInfo> {
141 (1..=n).map(|i| fi(i, i, None)).collect()
142 }
143
144 #[test]
145 fn retention_by_txid_uses_strict_less_than() {
146 let f = files(5); // txids 1..5
147 // Below 3 => {1,2} (file 3 has max_txid==3, which is NOT < 3, so retained).
148 let del = select_retention_by_txid(&f, TXID(3));
149 assert_eq!(
150 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
151 vec![1, 2],
152 "strict <: max_txid==txid is kept"
153 );
154 }
155
156 #[test]
157 fn retention_by_txid_always_keeps_newest() {
158 let f = files(3);
159 // Everything is below 100, but the newest (3) must survive.
160 let del = select_retention_by_txid(&f, TXID(100));
161 assert_eq!(
162 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
163 vec![1, 2],
164 "keep-newest: file 3 retained"
165 );
166 }
167
168 #[test]
169 fn retention_by_txid_deletes_nothing_when_all_above() {
170 let f = files(3);
171 assert!(select_retention_by_txid(&f, TXID(1)).is_empty());
172 }
173
174 #[test]
175 fn snapshot_retention_by_time_keeps_newest_and_tracks_min() {
176 let now = SystemTime::now();
177 let old = now - Duration::from_secs(3600);
178 let recent = now - Duration::from_secs(10);
179 let before = now - Duration::from_secs(60);
180 // Two old snapshots + one recent; cutoff `before` is 60s ago.
181 let f = vec![
182 fi(1, 1, Some(old)),
183 fi(2, 2, Some(old)),
184 fi(3, 3, Some(recent)),
185 ];
186 let (del, min_txid) = select_snapshot_retention(&f, before);
187 assert_eq!(
188 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
189 vec![1, 2],
190 "old snapshots deleted, recent retained"
191 );
192 assert_eq!(min_txid, TXID(3), "lowest retained snapshot txid");
193 }
194
195 #[test]
196 fn snapshot_retention_keeps_newest_even_if_all_old() {
197 let now = SystemTime::now();
198 let old = now - Duration::from_secs(3600);
199 let before = now - Duration::from_secs(60);
200 let f = vec![fi(1, 1, Some(old)), fi(2, 2, Some(old))];
201 let (del, _) = select_snapshot_retention(&f, before);
202 assert_eq!(
203 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
204 vec![1],
205 "keep-newest applies to snapshots too"
206 );
207 }
208
209 #[test]
210 fn l0_retention_is_noop_without_compaction() {
211 // KEEP scope: no L1 => max_l1_txid 0 => never deletes.
212 let f = files(10);
213 let threshold = SystemTime::now();
214 assert!(select_l0_retention_by_time(&f, TXID(0), threshold).is_empty());
215 }
216
217 #[test]
218 fn l0_retention_stops_early_on_recent_file() {
219 let now = SystemTime::now();
220 let old = now - Duration::from_secs(3600);
221 let recent = now - Duration::from_secs(1);
222 let threshold = now - Duration::from_secs(60);
223 // Files 1,2 are old; file 3 is recent (after threshold) -> stop.
224 // All have max_txid <= max_l1_txid (5), so 1,2 are eligible; we stop at 3.
225 let f = vec![
226 fi(1, 1, Some(old)),
227 fi(2, 2, Some(old)),
228 fi(3, 3, Some(recent)),
229 fi(4, 4, Some(old)), // would be eligible, but we stopped before it
230 ];
231 let del = select_l0_retention_by_time(&f, TXID(5), threshold);
232 assert_eq!(
233 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
234 vec![1, 2],
235 "stop-early preserves the contiguous tail; never reaches file 4"
236 );
237 }
238
239 #[test]
240 fn l0_retention_only_deletes_compacted_files() {
241 let now = SystemTime::now();
242 let old = now - Duration::from_secs(3600);
243 let threshold = now - Duration::from_secs(60);
244 // max_l1_txid = 2: only files with max_txid <= 2 are eligible.
245 let f = vec![
246 fi(1, 1, Some(old)),
247 fi(2, 2, Some(old)),
248 fi(3, 3, Some(old)), // not compacted into L1 yet -> retained
249 ];
250 let del = select_l0_retention_by_time(&f, TXID(2), threshold);
251 assert_eq!(
252 del.iter().map(|x| x.max_txid.0).collect::<Vec<_>>(),
253 vec![1, 2],
254 "only L1-compacted files are eligible"
255 );
256 }
257
258 #[test]
259 fn max_txid_of_slice() {
260 assert_eq!(max_txid(&files(7)), TXID(7));
261 assert_eq!(max_txid(&[]), TXID(0));
262 }
263}