Skip to main content

itzma_core/
gc.rs

1//! Garbage collection: dead segments, and optionally old WAL objects.
2//!
3//! GC is an explicit call, [`Namespace::gc`](crate::Namespace::gc). It loads the
4//! manifest, lists `segments/` once, works out which segment directories are
5//! dead, and deletes them. It never writes the manifest, so it needs only
6//! load, list, put and delete, and any number of collectors can run at once.
7//!
8//! A segment `lo-hi` is dead when it is not live, `hi` is at or below
9//! `wal_folded_through`, and it is not `1-<wal_folded_through>`. The last
10//! exclusion protects an orphan that a merge over an empty tail would produce
11//! and reuse. Every id a compactor makes starts at `folded + 1` (a fold) or at 1
12//! (a merge), and the fold point only moves forward, so a dead id never becomes
13//! live again.
14//!
15//! It also deletes the index objects inside live segments' directories
16//! that the manifest does not name: an older generation that a rebuild replaced,
17//! or an orphan of a build that never published. Like a segment, such an object
18//! goes only once it and the index that replaced it are at least `min_age` old.
19//! The whole directory of a dead segment goes with the segment. The sparse index
20//! objects (`sparse-idx-<generation>.bin`) follow the same rule against
21//! the manifest's `sparse_indexes`. `sparse.bin` needs none of it: it has one
22//! generation and lives and dies with its segment.
23//!
24//! With [`GcOptions::fence_wal`] it also lists `wal/` and replaces WAL objects
25//! that a segment has absorbed with an 8-byte fence at the same key, so that
26//! put-if-absent still refuses a writer with a stale hint. An object is fenced
27//! only when its seq is at or below the fold point and both it and the live
28//! segment that holds its seq are at least `min_age` old.
29//!
30//! A fencing run does not list the whole WAL. It reads a small hint object,
31//! `<namespace>/gc/fenced-through`, which says how far an unbroken run of fences
32//! reaches from seq 1, lists only past that, and writes the hint again once its
33//! fences are in place. The hint is not a source of truth (see
34//! [`fenced_through_path`]): a low or missing one costs a longer listing, and
35//! nothing reads it but `gc`.
36
37use std::collections::{BTreeMap, HashSet};
38use std::time::{Duration, SystemTime, UNIX_EPOCH};
39
40use futures::stream::{self, TryStreamExt};
41use object_store::path::Path;
42use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt};
43
44use crate::error::{ItzmaError, Result};
45use crate::index;
46use crate::manifest::Manifest;
47use crate::sparse_index;
48use crate::{segment, wal, wal_codec};
49
50/// The default for [`GcOptions::min_age`]: 24 hours.
51pub const DEFAULT_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);
52
53/// How many deletes, or fences, run at once.
54const CONCURRENCY: usize = 16;
55
56/// The longest an object can be and still count as a hint. A seq is at most 20
57/// digits, so a longer one is not a hint and is read as 0 without being read.
58const HINT_READ_BYTES: u64 = 32;
59
60/// Object key of the fence hint: `<namespace>/gc/fenced-through`. It holds one
61/// seq as decimal text: every WAL object at or below it was a fence when a
62/// fencing run wrote it. Only [`Namespace::gc`](crate::Namespace::gc) reads or
63/// writes it, and only with `fence_wal`.
64///
65/// It is a hint and not a fact. A fence never turns back into an object, so the
66/// value cannot go stale by itself. A missing, unreadable or too low value makes
67/// the next run list more than it needs to, and two collectors may write a lower
68/// value over a higher one, which costs the same. A value that is too high (only
69/// a hand-written one can be) leaves objects below it unfenced, which wastes
70/// space and loses nothing. Nothing else uses it: `recover` works out
71/// the same fact from the WAL listing.
72///
73/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
74pub fn fenced_through_path(namespace: &str) -> Path {
75    Path::from(format!("{namespace}/gc/fenced-through"))
76}
77
78/// Settings for [`Namespace::gc`](crate::Namespace::gc).
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct GcOptions {
81    /// How old a segment must be before it is deleted, and how old the live
82    /// segment that replaced it must be. It gives a slow reader time to finish
83    /// and an operator time to notice a mistake. Readers do not depend on it:
84    /// one that finds a segment gone reloads the manifest and reads again.
85    pub min_age: Duration,
86    /// Work out what would be deleted or fenced, report it, and change nothing.
87    pub dry_run: bool,
88    /// Also replace old WAL objects with fences (phase B). Off by
89    /// default, because a fenced range can no longer be rebuilt from the WAL:
90    /// the segments become the only copy of what it held.
91    ///
92    /// The namespace must be at WAL format level 4
93    /// ([`FENCE_FORMAT_VERSION`](crate::wal::FENCE_FORMAT_VERSION)), or the call
94    /// fails with [`ItzmaError::WalFormatTooOld`] and changes nothing.
95    pub fence_wal: bool,
96}
97
98impl Default for GcOptions {
99    fn default() -> Self {
100        Self {
101            min_age: DEFAULT_MIN_AGE,
102            dry_run: false,
103            fence_wal: false,
104        }
105    }
106}
107
108/// What a call to [`Namespace::gc`](crate::Namespace::gc) did.
109///
110/// The counts are what the run set out to delete and did not fail on. Deleting
111/// an object that is already gone is not an error and is still counted, so two
112/// collectors running at once can both count the same segment. With
113/// [`GcOptions::dry_run`] they are what a real run would have counted.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub struct GcReport {
116    /// Dead segments removed, each with every object under its directory.
117    pub segments_deleted: usize,
118    /// Total size of the objects removed.
119    pub bytes_freed: u64,
120    /// Dead segments left for a later run because they, or the live segment
121    /// that replaced them, are younger than `min_age`.
122    pub segments_too_young: usize,
123    /// WAL objects replaced by a fence. Zero unless [`GcOptions::fence_wal`] is
124    /// set. An object that is already a fence is not counted.
125    pub wal_objects_fenced: usize,
126    /// What the fenced WAL objects held, less the 8 bytes each fence keeps.
127    pub wal_bytes_freed: u64,
128    /// WAL objects left for a later run because they, or the live segment that
129    /// holds their seq, are younger than `min_age`.
130    pub wal_too_young: usize,
131    /// Index objects removed from segments that are still live: the ones the
132    /// manifest does not name, an older generation that a rebuild replaced or
133    /// an orphan of a build that never published. The index objects
134    /// inside a dead segment's directory go with the segment and are counted
135    /// there. Their size is part of `bytes_freed`.
136    pub indexes_deleted: usize,
137    /// Index objects left for a later run because they, or the index that
138    /// replaced them, are younger than `min_age`.
139    pub indexes_too_young: usize,
140    /// Sparse index objects removed from segments that are still live: an older
141    /// generation a rebuild replaced, or an orphan of a build that never
142    /// published. One inside a dead segment's directory goes with the
143    /// segment and is counted there. Their size is part of `bytes_freed`.
144    pub sparse_indexes_deleted: usize,
145    /// Sparse index objects left for a later run because they, or the index that
146    /// replaced them, are younger than `min_age`.
147    pub sparse_indexes_too_young: usize,
148}
149
150/// One `segments/<id>/` directory, as the listing shows it.
151pub(crate) struct Found {
152    pub(crate) lo: u64,
153    pub(crate) hi: u64,
154    /// Write time of the newest object in the directory, in unix milliseconds.
155    pub(crate) modified_ms: i64,
156    /// Every object in the directory with its size.
157    pub(crate) objects: Vec<(Path, u64)>,
158    /// The index objects among them (`index-<generation>.bin`).
159    pub(crate) indexes: Vec<FoundIndex>,
160    /// The sparse index objects among them (`sparse-idx-<generation>.bin`).
161    pub(crate) sparse_indexes: Vec<FoundIndex>,
162}
163
164/// One index object in a segment directory.
165pub(crate) struct FoundIndex {
166    pub(crate) generation: u32,
167    pub(crate) path: Path,
168    pub(crate) size: u64,
169    pub(crate) modified_ms: i64,
170}
171
172/// What to do about the segments found.
173struct Plan {
174    delete: Vec<Found>,
175    too_young: usize,
176}
177
178/// The age rule: how old something must be, against a clock passed in so the
179/// rule can be tested.
180#[derive(Clone, Copy)]
181struct Age {
182    now_ms: i64,
183    min_age_ms: i64,
184}
185
186impl Age {
187    fn new(now_ms: i64, min_age: Duration) -> Self {
188        Self {
189            now_ms,
190            min_age_ms: i64::try_from(min_age.as_millis()).unwrap_or(i64::MAX),
191        }
192    }
193
194    /// A write time in the future (clock skew) counts as age zero.
195    fn enough(self, modified_ms: i64) -> bool {
196        self.now_ms.saturating_sub(modified_ms).max(0) >= self.min_age_ms
197    }
198}
199
200/// The live segments, oldest first, with each one's last seq and write time.
201/// The write time is `None` when the listing does not show the segment, which
202/// counts as too young. Whatever holds a seq is the live segment that replaced
203/// it, so its write time stands in for the moment the seq stopped being needed.
204struct Covering(Vec<(u64, Option<i64>)>);
205
206impl Covering {
207    fn new(manifest: &Manifest, found: &BTreeMap<String, Found>) -> Self {
208        Self(
209            manifest
210                .live_segments
211                .iter()
212                .filter_map(|id| {
213                    let (_, hi) = segment::parse_segment_id(id)?;
214                    Some((hi, found.get(id).map(|f| f.modified_ms)))
215                })
216                .collect(),
217        )
218    }
219
220    /// When the live segment that holds `seq` was written.
221    fn modified_ms(&self, seq: u64) -> Option<i64> {
222        let at = self.0.partition_point(|(hi, _)| *hi < seq);
223        self.0.get(at).and_then(|(_, modified_ms)| *modified_ms)
224    }
225}
226
227/// Group a listing of `segments/` by directory. Objects that sit directly
228/// under the prefix, and directories whose name is not a segment id, are not
229/// ours and are skipped.
230pub(crate) fn group(prefix: &Path, listing: Vec<ObjectMeta>) -> BTreeMap<String, Found> {
231    let mut found: BTreeMap<String, Found> = BTreeMap::new();
232    for meta in listing {
233        let id = {
234            let Some(mut parts) = meta.location.prefix_match(prefix) else {
235                continue;
236            };
237            let Some(dir) = parts.next() else { continue };
238            if parts.next().is_none() {
239                continue;
240            }
241            dir.as_ref().to_string()
242        };
243        let Some((lo, hi)) = segment::parse_segment_id(&id) else {
244            continue;
245        };
246        let entry = found.entry(id).or_insert_with(|| Found {
247            lo,
248            hi,
249            modified_ms: i64::MIN,
250            objects: Vec::new(),
251            indexes: Vec::new(),
252            sparse_indexes: Vec::new(),
253        });
254        let modified_ms = meta.last_modified.timestamp_millis();
255        entry.modified_ms = entry.modified_ms.max(modified_ms);
256        if let Some(generation) = meta.location.filename().and_then(index::generation_of) {
257            entry.indexes.push(FoundIndex {
258                generation,
259                path: meta.location.clone(),
260                size: meta.size,
261                modified_ms,
262            });
263        }
264        if let Some(generation) = meta
265            .location
266            .filename()
267            .and_then(sparse_index::generation_of)
268        {
269            entry.sparse_indexes.push(FoundIndex {
270                generation,
271                path: meta.location.clone(),
272                size: meta.size,
273                modified_ms,
274            });
275        }
276        entry.objects.push((meta.location, meta.size));
277    }
278    found
279}
280
281/// A segment is dead when it is not live, its range ends at or below the fold
282/// point, and it is not `1-<folded>`, which an orphan of a merge over an empty
283/// tail would be and a later run would reuse. One rule for `gc` and for
284/// [`inspect`](crate::inspect), so what a report calls dead is what a run takes.
285pub(crate) fn is_dead(folded: u64, live: &HashSet<&str>, id: &str, segment: &Found) -> bool {
286    !live.contains(id) && segment.hi <= folded && !(segment.lo == 1 && segment.hi == folded)
287}
288
289/// Decide which segments to delete. Pure: no storage.
290fn plan(
291    manifest: &Manifest,
292    found: BTreeMap<String, Found>,
293    covering: &Covering,
294    age: Age,
295) -> Plan {
296    let folded = manifest.wal_folded_through;
297    let live_ids: HashSet<&str> = manifest.live_segments.iter().map(String::as_str).collect();
298
299    let mut delete = Vec::new();
300    let mut too_young = 0;
301    for (id, segment) in found {
302        if !is_dead(folded, &live_ids, &id, &segment) {
303            continue;
304        }
305        if age.enough(segment.modified_ms)
306            && covering
307                .modified_ms(segment.hi)
308                .is_some_and(|m| age.enough(m))
309        {
310            delete.push(segment);
311        } else {
312            too_young += 1;
313        }
314    }
315    Plan { delete, too_young }
316}
317
318/// What to do about the index objects of live segments.
319#[derive(Default)]
320struct IndexPlan {
321    delete: Vec<(Path, u64)>,
322    too_young: usize,
323}
324
325/// Decide which index objects of live segments to delete. Pure: no storage.
326///
327/// An index object is dead when the manifest does not name it: an older
328/// generation, a newer one that was never published, or one for a segment the
329/// manifest lists no index for. Like a segment (see [`plan`]) it is deleted only
330/// when it and the index that replaced it are both `min_age` old. An object with
331/// no replacement, an orphan, needs only its own age, and one whose replacement
332/// the listing does not show counts as too young. The directory of a segment
333/// that is not live is not looked at here: it is [`plan`]'s, whole.
334fn plan_indexes(manifest: &Manifest, found: &BTreeMap<String, Found>, age: Age) -> IndexPlan {
335    plan_generations(
336        manifest,
337        found,
338        age,
339        |id| manifest.indexes.get(id).map(|entry| entry.generation),
340        |dir| &dir.indexes,
341    )
342}
343
344/// [`plan_indexes`] for the sparse index objects, against the manifest's
345/// `sparse_indexes`.
346fn plan_sparse_indexes(
347    manifest: &Manifest,
348    found: &BTreeMap<String, Found>,
349    age: Age,
350) -> IndexPlan {
351    plan_generations(
352        manifest,
353        found,
354        age,
355        |id| {
356            manifest
357                .sparse_indexes
358                .get(id)
359                .map(|entry| entry.generation)
360        },
361        |dir| &dir.sparse_indexes,
362    )
363}
364
365/// The rule of [`plan_indexes`], for whichever kind of generational object
366/// `named` and `objects` pick out.
367fn plan_generations(
368    manifest: &Manifest,
369    found: &BTreeMap<String, Found>,
370    age: Age,
371    named: impl Fn(&str) -> Option<u32>,
372    objects: impl Fn(&Found) -> &[FoundIndex],
373) -> IndexPlan {
374    let mut plan = IndexPlan::default();
375    for id in &manifest.live_segments {
376        let Some(dir) = found.get(id) else { continue };
377        let named = named(id);
378        let present = objects(dir);
379        let replacement_ready = match named {
380            None => true,
381            Some(generation) => present
382                .iter()
383                .find(|index| index.generation == generation)
384                .is_some_and(|index| age.enough(index.modified_ms)),
385        };
386        for index in present {
387            if Some(index.generation) == named {
388                continue;
389            }
390            if replacement_ready && age.enough(index.modified_ms) {
391                plan.delete.push((index.path.clone(), index.size));
392            } else {
393                plan.too_young += 1;
394            }
395        }
396    }
397    plan
398}
399
400/// One `wal/<seq>.json` object, as the listing shows it.
401pub(crate) struct WalObject {
402    pub(crate) seq: u64,
403    pub(crate) path: Path,
404    pub(crate) size: u64,
405    pub(crate) modified_ms: i64,
406}
407
408/// What to do about the WAL objects found.
409#[derive(Default)]
410struct WalPlan {
411    fence: Vec<WalObject>,
412    too_young: usize,
413}
414
415/// Decide which WAL objects to fence. Pure: no storage. Objects past the fold
416/// point are not ours to touch, and an object the size of a fence already is
417/// one (every real object is longer), so neither is counted.
418fn plan_wal(
419    manifest: &Manifest,
420    covering: &Covering,
421    objects: Vec<WalObject>,
422    age: Age,
423) -> WalPlan {
424    let mut plan = WalPlan::default();
425    for object in objects {
426        if object.seq > manifest.wal_folded_through || object.size == wal_codec::FENCE_LEN as u64 {
427            continue;
428        }
429        if age.enough(object.modified_ms)
430            && covering
431                .modified_ms(object.seq)
432                .is_some_and(|m| age.enough(m))
433        {
434            plan.fence.push(object);
435        } else {
436            plan.too_young += 1;
437        }
438    }
439    plan
440}
441
442pub(crate) fn now_millis() -> i64 {
443    SystemTime::now()
444        .duration_since(UNIX_EPOCH)
445        .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
446}
447
448/// One collection run against a manifest the caller has already loaded and
449/// validated. See the module docs and
450/// [`Namespace::gc`](crate::Namespace::gc).
451pub(crate) async fn run(
452    store: &dyn ObjectStore,
453    namespace: &str,
454    manifest: &Manifest,
455    options: &GcOptions,
456) -> Result<GcReport> {
457    if options.fence_wal && manifest.wal_format < wal::FENCE_FORMAT_VERSION {
458        return Err(ItzmaError::WalFormatTooOld {
459            have: manifest.wal_format,
460            need: wal::FENCE_FORMAT_VERSION,
461        });
462    }
463    // The listings come after the manifest on purpose: a segment written in
464    // between has `hi` past the manifest's fold point, so it is not dead, and
465    // a WAL object written in between has a seq past it too.
466    let prefix = Path::from(format!("{namespace}/segments"));
467    let listing: Vec<ObjectMeta> = store.list(Some(&prefix)).try_collect().await?;
468    let found = group(&prefix, listing);
469    let covering = Covering::new(manifest, &found);
470    let age = Age::new(now_millis(), options.min_age);
471    let indexes = plan_indexes(manifest, &found, age);
472    let sparse_indexes = plan_sparse_indexes(manifest, &found, age);
473    let Plan { delete, too_young } = plan(manifest, found, &covering, age);
474    let hint = if options.fence_wal {
475        read_hint(store, namespace).await?
476    } else {
477        0
478    };
479    let (wal_plan, reach) = if options.fence_wal {
480        let objects = list_wal_after(store, namespace, hint).await?;
481        let listed: Vec<(u64, u64)> = objects.iter().map(|o| (o.seq, o.size)).collect();
482        let plan = plan_wal(manifest, &covering, objects, age);
483        let reach = fenced_reach(hint, &listed, &plan.fence);
484        (plan, reach)
485    } else {
486        (WalPlan::default(), hint)
487    };
488
489    let report = GcReport {
490        segments_deleted: delete.len(),
491        bytes_freed: delete
492            .iter()
493            .flat_map(|found| &found.objects)
494            .map(|(_, size)| size)
495            .chain(indexes.delete.iter().map(|(_, size)| size))
496            .chain(sparse_indexes.delete.iter().map(|(_, size)| size))
497            .sum(),
498        segments_too_young: too_young,
499        wal_objects_fenced: wal_plan.fence.len(),
500        wal_bytes_freed: wal_plan
501            .fence
502            .iter()
503            .map(|object| object.size.saturating_sub(wal_codec::FENCE_LEN as u64))
504            .sum(),
505        wal_too_young: wal_plan.too_young,
506        indexes_deleted: indexes.delete.len(),
507        indexes_too_young: indexes.too_young,
508        sparse_indexes_deleted: sparse_indexes.delete.len(),
509        sparse_indexes_too_young: sparse_indexes.too_young,
510    };
511    if !options.dry_run {
512        let paths: Vec<Path> = delete
513            .into_iter()
514            .flat_map(|found| found.objects)
515            .chain(indexes.delete)
516            .chain(sparse_indexes.delete)
517            .map(|(path, _)| path)
518            .collect();
519        delete_all(store, paths).await?;
520        fence_all(store, wal_plan.fence).await?;
521        if reach > hint {
522            write_hint(store, namespace, reach).await?;
523        }
524    }
525    Ok(report)
526}
527
528/// List `wal/` with sizes and write times. Keys that are not a seq are not
529/// ours and are skipped.
530pub(crate) async fn list_wal(store: &dyn ObjectStore, namespace: &str) -> Result<Vec<WalObject>> {
531    list_wal_after(store, namespace, 0).await
532}
533
534/// [`list_wal`] for the objects with a seq above `after`. Zero lists them all.
535pub(crate) async fn list_wal_after(
536    store: &dyn ObjectStore,
537    namespace: &str,
538    after: u64,
539) -> Result<Vec<WalObject>> {
540    let prefix = wal::wal_prefix(namespace);
541    let listing: Vec<ObjectMeta> = if after == 0 {
542        store.list(Some(&prefix)).try_collect().await?
543    } else {
544        store
545            .list_with_offset(Some(&prefix), &wal::wal_path(namespace, after))
546            .try_collect()
547            .await?
548    };
549    Ok(listing
550        .into_iter()
551        .filter_map(|meta| {
552            Some(WalObject {
553                seq: wal::parse_seq(&meta.location)?,
554                modified_ms: meta.last_modified.timestamp_millis(),
555                size: meta.size,
556                path: meta.location,
557            })
558        })
559        .collect())
560}
561
562/// The seq in the fence hint, or 0 if there is no hint or it does not parse. A
563/// bad hint is never an error, because starting from the top is always right.
564async fn read_hint(store: &dyn ObjectStore, namespace: &str) -> Result<u64> {
565    match store.get(&fenced_through_path(namespace)).await {
566        // The size comes with the response, so an object that cannot be a hint
567        // is not downloaded.
568        Ok(got) if got.meta.size > HINT_READ_BYTES => Ok(0),
569        Ok(got) => Ok(parse_hint(&got.bytes().await?)),
570        Err(object_store::Error::NotFound { .. }) => Ok(0),
571        Err(e) => Err(e.into()),
572    }
573}
574
575fn parse_hint(bytes: &[u8]) -> u64 {
576    std::str::from_utf8(bytes)
577        .ok()
578        .and_then(|text| text.trim().parse().ok())
579        .unwrap_or(0)
580}
581
582/// A plain overwrite. Two collectors racing may leave the lower value, which
583/// only makes the next listing longer.
584async fn write_hint(store: &dyn ObjectStore, namespace: &str, seq: u64) -> Result<()> {
585    store
586        .put(&fenced_through_path(namespace), seq.to_string().into())
587        .await?;
588    Ok(())
589}
590
591/// How far the unbroken run of fences reaches from `from` once the objects in
592/// `fenced` have been written. `listed` is every object the run saw, with its
593/// size, and nothing past a gap, a young object or an unfolded one counts.
594fn fenced_reach(from: u64, listed: &[(u64, u64)], fenced: &[WalObject]) -> u64 {
595    let planned: HashSet<u64> = fenced.iter().map(|object| object.seq).collect();
596    let mut sorted = listed.to_vec();
597    sorted.sort_unstable();
598    let mut reach = from;
599    for (seq, size) in sorted {
600        let fence = size == wal_codec::FENCE_LEN as u64 || planned.contains(&seq);
601        if seq != reach + 1 || !fence {
602            break;
603        }
604        reach = seq;
605    }
606    reach
607}
608
609/// Overwrite each object with a fence, 16 at a time. The first failure ends the
610/// run, and a rerun finishes the job: an object already fenced is skipped, and
611/// two collectors that fence the same object write the same bytes.
612async fn fence_all(store: &dyn ObjectStore, objects: Vec<WalObject>) -> Result<()> {
613    stream::iter(objects.into_iter().map(Ok::<_, ItzmaError>))
614        .try_for_each_concurrent(CONCURRENCY, |object| async move {
615            store.put(&object.path, wal_codec::fence().into()).await?;
616            Ok(())
617        })
618        .await
619}
620
621/// Delete every path, 16 at a time. The first failure ends the run, and a rerun
622/// finishes the job, since deleting is idempotent.
623async fn delete_all(store: &dyn ObjectStore, paths: Vec<Path>) -> Result<()> {
624    stream::iter(paths.into_iter().map(Ok::<_, ItzmaError>))
625        .try_for_each_concurrent(
626            CONCURRENCY,
627            |path| async move { delete_one(store, &path).await },
628        )
629        .await
630}
631
632/// Delete one object. One already gone, say from another collector, is fine.
633async fn delete_one(store: &dyn ObjectStore, path: &Path) -> Result<()> {
634    match store.delete(path).await {
635        Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
636        Err(e) => Err(e.into()),
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643    use crate::document::{Metric, Schema};
644
645    fn to_fence(seq: u64) -> WalObject {
646        WalObject {
647            seq,
648            path: wal::wal_path("docs", seq),
649            size: 100,
650            modified_ms: 0,
651        }
652    }
653
654    const FENCE_SIZE: u64 = wal_codec::FENCE_LEN as u64;
655
656    #[test]
657    fn a_hint_is_decimal_text_and_anything_else_is_zero() {
658        assert_eq!(parse_hint(b"1205"), 1205);
659        assert_eq!(parse_hint(b" 7\n"), 7);
660        for bad in [
661            &b""[..],
662            b"x",
663            b"-1",
664            b"1.5",
665            b"\xff",
666            b"99999999999999999999999",
667        ] {
668            assert_eq!(parse_hint(bad), 0, "{bad:?}");
669        }
670    }
671
672    #[test]
673    fn the_reach_follows_an_unbroken_run_of_fences() {
674        let listed = [(1, FENCE_SIZE), (2, FENCE_SIZE), (3, 100), (4, 100)];
675        // 3 is being fenced now, 4 is not.
676        assert_eq!(fenced_reach(0, &listed, &[to_fence(3)]), 3);
677        // Nothing is being fenced, so the run stops at the first real object.
678        assert_eq!(fenced_reach(0, &listed, &[]), 2);
679    }
680
681    #[test]
682    fn the_reach_stops_at_a_gap_and_starts_from_the_hint() {
683        let listed = [(6, FENCE_SIZE), (7, FENCE_SIZE), (9, FENCE_SIZE)];
684        assert_eq!(fenced_reach(5, &listed, &[]), 7);
685        // The listing is in any order.
686        let shuffled = [(9, FENCE_SIZE), (7, FENCE_SIZE), (6, FENCE_SIZE)];
687        assert_eq!(fenced_reach(5, &shuffled, &[]), 7);
688        // Objects the listing did not show are not assumed to be fences.
689        assert_eq!(fenced_reach(5, &[], &[]), 5);
690        assert_eq!(fenced_reach(5, &[(8, FENCE_SIZE)], &[]), 5);
691    }
692
693    #[test]
694    fn the_reach_never_falls_below_the_hint() {
695        assert_eq!(fenced_reach(10, &[(11, 100)], &[]), 10);
696    }
697
698    const HOUR_MS: i64 = 60 * 60 * 1000;
699    const NOW: i64 = 1_000 * HOUR_MS;
700
701    fn found(lo: u64, hi: u64, age_hours: i64) -> (String, Found) {
702        let id = segment::segment_id(lo, hi);
703        let path = segment::segment_path("docs", &id);
704        (
705            id,
706            Found {
707                lo,
708                hi,
709                modified_ms: NOW - age_hours * HOUR_MS,
710                objects: vec![(path, 100)],
711                indexes: Vec::new(),
712                sparse_indexes: Vec::new(),
713            },
714        )
715    }
716
717    fn manifest(live: &[(u64, u64)], folded: u64) -> Manifest {
718        let mut m = Manifest::new(Schema::new(1, Metric::L2));
719        m.live_segments = live
720            .iter()
721            .map(|(lo, hi)| segment::segment_id(*lo, *hi))
722            .collect();
723        m.wal_folded_through = folded;
724        m
725    }
726
727    /// Ids the plan would delete, sorted.
728    fn deleted(plan: &Plan) -> Vec<String> {
729        let mut ids: Vec<String> = plan
730            .delete
731            .iter()
732            .map(|f| segment::segment_id(f.lo, f.hi))
733            .collect();
734        ids.sort();
735        ids
736    }
737
738    fn ids(pairs: &[(u64, u64)]) -> Vec<String> {
739        pairs
740            .iter()
741            .map(|(lo, hi)| segment::segment_id(*lo, *hi))
742            .collect()
743    }
744
745    fn plan_for(m: &Manifest, segments: &[(u64, u64, i64)], min_age_hours: u64) -> Plan {
746        let listing: BTreeMap<String, Found> = segments
747            .iter()
748            .map(|(lo, hi, age)| found(*lo, *hi, *age))
749            .collect();
750        let covering = Covering::new(m, &listing);
751        plan(
752            m,
753            listing,
754            &covering,
755            Age::new(NOW, Duration::from_secs(min_age_hours * 3600)),
756        )
757    }
758
759    fn wal_object(seq: u64, size: u64, age_hours: i64) -> WalObject {
760        WalObject {
761            seq,
762            path: wal::wal_path("docs", seq),
763            size,
764            modified_ms: NOW - age_hours * HOUR_MS,
765        }
766    }
767
768    /// The seqs the plan would fence.
769    fn fenced(plan: &WalPlan) -> Vec<u64> {
770        plan.fence.iter().map(|o| o.seq).collect()
771    }
772
773    fn wal_plan_for(
774        m: &Manifest,
775        segments: &[(u64, u64, i64)],
776        objects: Vec<WalObject>,
777        min_age_hours: u64,
778    ) -> WalPlan {
779        let listing: BTreeMap<String, Found> = segments
780            .iter()
781            .map(|(lo, hi, age)| found(*lo, *hi, *age))
782            .collect();
783        let covering = Covering::new(m, &listing);
784        plan_wal(
785            m,
786            &covering,
787            objects,
788            Age::new(NOW, Duration::from_secs(min_age_hours * 3600)),
789        )
790    }
791
792    #[test]
793    fn a_live_segment_is_never_dead() {
794        let m = manifest(&[(1, 3)], 3);
795        let plan = plan_for(&m, &[(1, 3, 500)], 0);
796        assert!(plan.delete.is_empty());
797        assert_eq!(plan.too_young, 0);
798    }
799
800    #[test]
801    fn a_superseded_segment_is_dead() {
802        let m = manifest(&[(1, 3)], 3);
803        let plan = plan_for(
804            &m,
805            &[(1, 1, 500), (2, 2, 500), (3, 3, 500), (1, 3, 500)],
806            24,
807        );
808        assert_eq!(deleted(&plan), ids(&[(1, 1), (2, 2), (3, 3)]));
809    }
810
811    #[test]
812    fn a_fold_that_a_merge_replaced_is_dead() {
813        // Live: a base 1-4 and a delta 5-6. The delta 5-5 that 5-6 replaced is dead.
814        let m = manifest(&[(1, 4), (5, 6)], 6);
815        let plan = plan_for(&m, &[(1, 4, 500), (5, 5, 500), (5, 6, 500)], 24);
816        assert_eq!(deleted(&plan), ids(&[(5, 5)]));
817    }
818
819    #[test]
820    fn an_orphan_past_the_fold_point_is_kept() {
821        let m = manifest(&[(1, 3)], 3);
822        let plan = plan_for(&m, &[(1, 3, 500), (4, 5, 500), (1, 5, 500)], 0);
823        assert!(plan.delete.is_empty());
824        assert_eq!(plan.too_young, 0, "kept is not the same as too young");
825    }
826
827    #[test]
828    fn an_orphan_that_a_merge_over_an_empty_tail_would_reuse_is_kept() {
829        // Live 1-1 and 2-2, folded through 2. A merge would make 1-2.
830        let m = manifest(&[(1, 1), (2, 2)], 2);
831        let plan = plan_for(&m, &[(1, 1, 500), (2, 2, 500), (1, 2, 500)], 0);
832        assert!(plan.delete.is_empty());
833    }
834
835    #[test]
836    fn an_orphan_at_or_below_the_fold_point_is_dead() {
837        let m = manifest(&[(1, 3)], 3);
838        let plan = plan_for(&m, &[(1, 3, 500), (2, 3, 500), (2, 2, 500)], 24);
839        assert_eq!(deleted(&plan), ids(&[(2, 2), (2, 3)]));
840    }
841
842    #[test]
843    fn a_dead_segment_needs_its_own_age_and_its_coverers() {
844        let m = manifest(&[(1, 3)], 3);
845        // 1-1 is old but the merge that replaced it is an hour old.
846        let plan = plan_for(&m, &[(1, 1, 500), (1, 3, 1)], 24);
847        assert!(plan.delete.is_empty());
848        assert_eq!(plan.too_young, 1);
849
850        // The merge is old but the dead segment was written an hour ago.
851        let plan = plan_for(&m, &[(2, 2, 1), (1, 3, 500)], 24);
852        assert!(plan.delete.is_empty());
853        assert_eq!(plan.too_young, 1);
854
855        // Both old enough.
856        let plan = plan_for(&m, &[(2, 2, 30), (1, 3, 25)], 24);
857        assert_eq!(deleted(&plan), ids(&[(2, 2)]));
858    }
859
860    #[test]
861    fn the_covering_segment_is_the_one_that_holds_the_dead_segments_end() {
862        // Live 1-4 (old) and 5-6 (young). 3-4 is covered by 1-4, not by 5-6.
863        let m = manifest(&[(1, 4), (5, 6)], 6);
864        let plan = plan_for(&m, &[(1, 4, 500), (5, 6, 1), (3, 4, 500), (5, 5, 500)], 24);
865        assert_eq!(deleted(&plan), ids(&[(3, 4)]));
866        assert_eq!(plan.too_young, 1, "5-5 waits for 5-6");
867    }
868
869    #[test]
870    fn a_zero_min_age_deletes_regardless_of_age() {
871        let m = manifest(&[(1, 3)], 3);
872        let plan = plan_for(&m, &[(2, 2, 0), (1, 3, 0)], 0);
873        assert_eq!(deleted(&plan), ids(&[(2, 2)]));
874    }
875
876    #[test]
877    fn a_write_time_in_the_future_counts_as_brand_new() {
878        // The store's clock runs ahead of ours.
879        let m = manifest(&[(1, 3)], 3);
880        let plan = plan_for(&m, &[(2, 2, -5), (1, 3, 500)], 24);
881        assert!(plan.delete.is_empty());
882        assert_eq!(plan.too_young, 1);
883        let plan = plan_for(&m, &[(2, 2, -5), (1, 3, -5)], 0);
884        assert_eq!(deleted(&plan), ids(&[(2, 2)]));
885    }
886
887    #[test]
888    fn a_live_segment_the_listing_does_not_show_counts_as_too_young() {
889        let m = manifest(&[(1, 3)], 3);
890        let plan = plan_for(&m, &[(2, 2, 500)], 24);
891        assert!(plan.delete.is_empty());
892        assert_eq!(plan.too_young, 1);
893    }
894
895    #[test]
896    fn nothing_is_dead_before_the_first_fold() {
897        let m = manifest(&[], 0);
898        let plan = plan_for(&m, &[(1, 2, 500), (3, 3, 500)], 0);
899        assert!(plan.delete.is_empty());
900    }
901
902    #[test]
903    fn folded_and_old_wal_objects_are_fenced() {
904        let m = manifest(&[(1, 3)], 3);
905        let objects = (1..=3).map(|seq| wal_object(seq, 500, 500)).collect();
906        let plan = wal_plan_for(&m, &[(1, 3, 500)], objects, 24);
907        assert_eq!(fenced(&plan), [1, 2, 3]);
908        assert_eq!(plan.too_young, 0);
909    }
910
911    #[test]
912    fn a_wal_object_past_the_fold_point_is_never_fenced() {
913        let m = manifest(&[(1, 3)], 3);
914        let objects = (1..=5).map(|seq| wal_object(seq, 500, 500)).collect();
915        let plan = wal_plan_for(&m, &[(1, 3, 500)], objects, 0);
916        assert_eq!(fenced(&plan), [1, 2, 3]);
917        assert_eq!(plan.too_young, 0, "left alone is not the same as too young");
918    }
919
920    #[test]
921    fn a_fence_is_skipped_and_not_counted() {
922        let m = manifest(&[(1, 3)], 3);
923        let objects = vec![
924            wal_object(1, wal_codec::FENCE_LEN as u64, 500),
925            wal_object(2, wal_codec::FENCE_LEN as u64, 0),
926            wal_object(3, 500, 500),
927        ];
928        let plan = wal_plan_for(&m, &[(1, 3, 500)], objects, 24);
929        assert_eq!(fenced(&plan), [3]);
930        assert_eq!(plan.too_young, 0);
931    }
932
933    #[test]
934    fn a_wal_object_needs_its_own_age_and_its_covering_segments() {
935        let m = manifest(&[(1, 3)], 3);
936        // The object is an hour old, the segment that holds it is old.
937        let plan = wal_plan_for(&m, &[(1, 3, 500)], vec![wal_object(2, 500, 1)], 24);
938        assert!(plan.fence.is_empty());
939        assert_eq!(plan.too_young, 1);
940
941        // The object is old, the segment that holds it is an hour old.
942        let plan = wal_plan_for(&m, &[(1, 3, 1)], vec![wal_object(2, 500, 500)], 24);
943        assert!(plan.fence.is_empty());
944        assert_eq!(plan.too_young, 1);
945
946        let plan = wal_plan_for(&m, &[(1, 3, 25)], vec![wal_object(2, 500, 30)], 24);
947        assert_eq!(fenced(&plan), [2]);
948    }
949
950    #[test]
951    fn the_segment_that_holds_the_seq_is_the_one_that_counts_for_a_wal_object() {
952        // Live 1-4 (old) and 5-6 (young). Seq 3 is held by 1-4, seq 5 by 5-6.
953        let m = manifest(&[(1, 4), (5, 6)], 6);
954        let objects = vec![wal_object(3, 500, 500), wal_object(5, 500, 500)];
955        let plan = wal_plan_for(&m, &[(1, 4, 500), (5, 6, 1)], objects, 24);
956        assert_eq!(fenced(&plan), [3]);
957        assert_eq!(plan.too_young, 1);
958    }
959
960    #[test]
961    fn a_covering_segment_the_listing_does_not_show_counts_as_too_young_for_wal() {
962        let m = manifest(&[(1, 3)], 3);
963        let plan = wal_plan_for(&m, &[], vec![wal_object(2, 500, 500)], 24);
964        assert!(plan.fence.is_empty());
965        assert_eq!(plan.too_young, 1);
966    }
967
968    #[test]
969    fn a_zero_min_age_fences_regardless_of_age() {
970        let m = manifest(&[(1, 3)], 3);
971        let plan = wal_plan_for(&m, &[(1, 3, 0)], vec![wal_object(2, 500, 0)], 0);
972        assert_eq!(fenced(&plan), [2]);
973    }
974
975    #[test]
976    fn a_wal_write_time_in_the_future_counts_as_brand_new() {
977        let m = manifest(&[(1, 3)], 3);
978        let plan = wal_plan_for(&m, &[(1, 3, 500)], vec![wal_object(2, 500, -5)], 24);
979        assert!(plan.fence.is_empty());
980        assert_eq!(plan.too_young, 1);
981    }
982
983    #[test]
984    fn nothing_is_fenced_before_the_first_fold() {
985        let m = manifest(&[], 0);
986        let objects = (1..=3).map(|seq| wal_object(seq, 500, 500)).collect();
987        let plan = wal_plan_for(&m, &[], objects, 0);
988        assert!(plan.fence.is_empty());
989        assert_eq!(plan.too_young, 0);
990    }
991
992    /// A live segment `1-1` with the given index objects `(generation, age in
993    /// hours)`, and a manifest that names `named` for it, if any.
994    fn plan_indexes_for(
995        objects: &[(u32, i64)],
996        named: Option<u32>,
997        min_age_hours: u64,
998    ) -> IndexPlan {
999        let mut m = manifest(&[(1, 1)], 1);
1000        let (id, mut dir) = found(1, 1, 100);
1001        dir.indexes = objects
1002            .iter()
1003            .map(|(generation, age)| FoundIndex {
1004                generation: *generation,
1005                path: index::index_path("docs", &id, *generation),
1006                size: 10,
1007                modified_ms: NOW - age * HOUR_MS,
1008            })
1009            .collect();
1010        if let Some(generation) = named {
1011            m.indexes.insert(
1012                id.clone(),
1013                crate::manifest::IndexEntry {
1014                    generation,
1015                    kind: "sq8".into(),
1016                },
1017            );
1018        }
1019        let listing = BTreeMap::from([(id, dir)]);
1020        plan_indexes(
1021            &m,
1022            &listing,
1023            Age::new(NOW, Duration::from_secs(min_age_hours * 3600)),
1024        )
1025    }
1026
1027    fn deleted_generations(plan: &IndexPlan) -> Vec<String> {
1028        plan.delete
1029            .iter()
1030            .map(|(path, _)| path.filename().unwrap_or_default().to_string())
1031            .collect()
1032    }
1033
1034    #[test]
1035    fn an_index_the_manifest_names_is_never_deleted() {
1036        let plan = plan_indexes_for(&[(1, 1_000)], Some(1), 0);
1037        assert!(plan.delete.is_empty());
1038        assert_eq!(plan.too_young, 0);
1039    }
1040
1041    #[test]
1042    fn a_replaced_generation_needs_its_own_age_and_its_replacements() {
1043        // 1 is old, 2 replaced it. Both old enough: 1 goes.
1044        let plan = plan_indexes_for(&[(1, 30), (2, 25)], Some(2), 24);
1045        assert_eq!(deleted_generations(&plan), ["index-1.bin"]);
1046        assert_eq!(plan.too_young, 0);
1047        // The replacement is young: the old one waits.
1048        let plan = plan_indexes_for(&[(1, 30), (2, 1)], Some(2), 24);
1049        assert!(plan.delete.is_empty());
1050        assert_eq!(plan.too_young, 1);
1051        // The old one is young itself.
1052        let plan = plan_indexes_for(&[(1, 1), (2, 30)], Some(2), 24);
1053        assert!(plan.delete.is_empty());
1054        assert_eq!(plan.too_young, 1);
1055    }
1056
1057    #[test]
1058    fn an_orphan_waits_only_for_its_own_age() {
1059        // Nothing named: the segment has no index, whatever is there is stray.
1060        let plan = plan_indexes_for(&[(1, 30)], None, 24);
1061        assert_eq!(deleted_generations(&plan), ["index-1.bin"]);
1062        let plan = plan_indexes_for(&[(1, 1)], None, 24);
1063        assert!(plan.delete.is_empty());
1064        assert_eq!(plan.too_young, 1);
1065    }
1066
1067    #[test]
1068    fn a_newer_generation_that_was_never_published_is_an_orphan() {
1069        // Generation 2 is named. 3 is a rebuild that stopped before it published.
1070        let plan = plan_indexes_for(&[(2, 30), (3, 30)], Some(2), 24);
1071        assert_eq!(deleted_generations(&plan), ["index-3.bin"]);
1072        let plan = plan_indexes_for(&[(2, 30), (3, 1)], Some(2), 24);
1073        assert!(plan.delete.is_empty());
1074        assert_eq!(plan.too_young, 1);
1075    }
1076
1077    #[test]
1078    fn a_replacement_the_listing_does_not_show_counts_as_too_young() {
1079        let plan = plan_indexes_for(&[(1, 1_000)], Some(2), 24);
1080        assert!(plan.delete.is_empty());
1081        assert_eq!(plan.too_young, 1);
1082    }
1083
1084    #[test]
1085    fn a_zero_min_age_deletes_every_unnamed_index() {
1086        let plan = plan_indexes_for(&[(1, 0), (2, 0), (3, 0)], Some(2), 0);
1087        assert_eq!(deleted_generations(&plan), ["index-1.bin", "index-3.bin"]);
1088    }
1089
1090    #[test]
1091    fn a_segment_that_is_not_live_is_not_this_plans() {
1092        // Its directory is the segment plan's, deleted whole.
1093        let m = manifest(&[(1, 2)], 2);
1094        let (id, mut dir) = found(1, 1, 100);
1095        dir.indexes = vec![FoundIndex {
1096            generation: 1,
1097            path: index::index_path("docs", &id, 1),
1098            size: 10,
1099            modified_ms: NOW - 1_000 * HOUR_MS,
1100        }];
1101        let listing = BTreeMap::from([(id, dir)]);
1102        let plan = plan_indexes(&m, &listing, Age::new(NOW, Duration::ZERO));
1103        assert!(plan.delete.is_empty());
1104        assert_eq!(plan.too_young, 0);
1105    }
1106
1107    #[tokio::test]
1108    async fn the_listing_finds_index_objects_by_name_only() {
1109        use object_store::memory::InMemory;
1110        let store = InMemory::new();
1111        let id = segment::segment_id(1, 1);
1112        for name in [
1113            "data.bin",
1114            "index-2.bin",
1115            "index-01.bin",
1116            "index-1.bin.tmp",
1117            "notes.txt",
1118        ] {
1119            let path = Path::from(format!("docs/segments/{id}/{name}"));
1120            store
1121                .put(&path, bytes::Bytes::from_static(b"seven!!").into())
1122                .await
1123                .expect("put");
1124        }
1125        let prefix = Path::from("docs/segments");
1126        let listing: Vec<ObjectMeta> = store.list(Some(&prefix)).try_collect().await.expect("list");
1127
1128        let found = group(&prefix, listing);
1129        let dir = &found[&id];
1130        assert_eq!(dir.objects.len(), 5, "everything is still in the directory");
1131        let mut generations: Vec<u32> = dir.indexes.iter().map(|i| i.generation).collect();
1132        generations.sort_unstable();
1133        assert_eq!(
1134            generations,
1135            [2],
1136            "one valid generation, malformed names ignored"
1137        );
1138    }
1139}