1use 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
50pub const DEFAULT_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);
52
53const CONCURRENCY: usize = 16;
55
56const HINT_READ_BYTES: u64 = 32;
59
60pub fn fenced_through_path(namespace: &str) -> Path {
75 Path::from(format!("{namespace}/gc/fenced-through"))
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct GcOptions {
81 pub min_age: Duration,
86 pub dry_run: bool,
88 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub struct GcReport {
116 pub segments_deleted: usize,
118 pub bytes_freed: u64,
120 pub segments_too_young: usize,
123 pub wal_objects_fenced: usize,
126 pub wal_bytes_freed: u64,
128 pub wal_too_young: usize,
131 pub indexes_deleted: usize,
137 pub indexes_too_young: usize,
140 pub sparse_indexes_deleted: usize,
145 pub sparse_indexes_too_young: usize,
148}
149
150pub(crate) struct Found {
152 pub(crate) lo: u64,
153 pub(crate) hi: u64,
154 pub(crate) modified_ms: i64,
156 pub(crate) objects: Vec<(Path, u64)>,
158 pub(crate) indexes: Vec<FoundIndex>,
160 pub(crate) sparse_indexes: Vec<FoundIndex>,
162}
163
164pub(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
172struct Plan {
174 delete: Vec<Found>,
175 too_young: usize,
176}
177
178#[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 fn enough(self, modified_ms: i64) -> bool {
196 self.now_ms.saturating_sub(modified_ms).max(0) >= self.min_age_ms
197 }
198}
199
200struct 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 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
227pub(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
281pub(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
289fn 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#[derive(Default)]
320struct IndexPlan {
321 delete: Vec<(Path, u64)>,
322 too_young: usize,
323}
324
325fn 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
344fn 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
365fn 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
400pub(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#[derive(Default)]
410struct WalPlan {
411 fence: Vec<WalObject>,
412 too_young: usize,
413}
414
415fn 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
448pub(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 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
528pub(crate) async fn list_wal(store: &dyn ObjectStore, namespace: &str) -> Result<Vec<WalObject>> {
531 list_wal_after(store, namespace, 0).await
532}
533
534pub(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
562async fn read_hint(store: &dyn ObjectStore, namespace: &str) -> Result<u64> {
565 match store.get(&fenced_through_path(namespace)).await {
566 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
582async 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
591fn 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
609async 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
621async 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
632async 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 assert_eq!(fenced_reach(0, &listed, &[to_fence(3)]), 3);
677 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 let shuffled = [(9, FENCE_SIZE), (7, FENCE_SIZE), (6, FENCE_SIZE)];
687 assert_eq!(fenced_reach(5, &shuffled, &[]), 7);
688 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}