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