1use 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
53pub const DEFAULT_MIN_AGE: Duration = Duration::from_secs(24 * 60 * 60);
55
56const CONCURRENCY: usize = 16;
58
59const HINT_READ_BYTES: u64 = 32;
62
63pub fn fenced_through_path(namespace: &str) -> Path {
78 Path::from(format!("{namespace}/gc/fenced-through"))
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct GcOptions {
84 pub min_age: Duration,
89 pub dry_run: bool,
91 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
118pub struct GcReport {
119 pub segments_deleted: usize,
121 pub bytes_freed: u64,
123 pub segments_too_young: usize,
126 pub wal_objects_fenced: usize,
129 pub wal_bytes_freed: u64,
131 pub wal_too_young: usize,
134 pub indexes_deleted: usize,
140 pub indexes_too_young: usize,
143 pub sparse_indexes_deleted: usize,
148 pub sparse_indexes_too_young: usize,
151 pub attr_indexes_deleted: usize,
156 pub attr_indexes_too_young: usize,
159 pub staging_deleted: usize,
165 pub staging_too_young: usize,
168}
169
170pub(crate) struct Found {
172 pub(crate) lo: u64,
173 pub(crate) hi: u64,
174 pub(crate) modified_ms: i64,
178 pub(crate) newest_ms: i64,
182 pub(crate) objects: Vec<(Path, u64)>,
184 pub(crate) indexes: Vec<FoundIndex>,
186 pub(crate) sparse_indexes: Vec<FoundIndex>,
188 pub(crate) attr_indexes: Vec<FoundIndex>,
190 pub(crate) staging: Vec<(Path, u64, i64)>,
193}
194
195pub(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
203struct Plan {
205 delete: Vec<Found>,
206 too_young: usize,
207}
208
209#[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 fn enough(self, modified_ms: i64) -> bool {
227 self.now_ms.saturating_sub(modified_ms).max(0) >= self.min_age_ms
228 }
229}
230
231struct 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 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
258pub(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
330pub(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
338fn 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#[derive(Default)]
369struct IndexPlan {
370 delete: Vec<(Path, u64)>,
371 too_young: usize,
372}
373
374fn 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
400fn 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
419fn 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
440fn 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
452fn 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
487pub(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#[derive(Default)]
497struct WalPlan {
498 fence: Vec<WalObject>,
499 too_young: usize,
500}
501
502fn 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
535pub(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 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
627pub(crate) async fn list_wal(store: &dyn ObjectStore, namespace: &str) -> Result<Vec<WalObject>> {
630 list_wal_after(store, namespace, 0).await
631}
632
633pub(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
661async fn read_hint(store: &dyn ObjectStore, namespace: &str) -> Result<u64> {
664 match store.get(&fenced_through_path(namespace)).await {
665 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
681async 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
690fn 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
708async 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
720async 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
731async 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 assert_eq!(fenced_reach(0, &listed, &[to_fence(3)]), 3);
776 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 let shuffled = [(9, FENCE_SIZE), (7, FENCE_SIZE), (6, FENCE_SIZE)];
786 assert_eq!(fenced_reach(5, &shuffled, &[]), 7);
787 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}