Skip to main content

hyperfile_cleaner/
s3.rs

1//! S3-backed cleaner implementation.
2//!
3//! `S3Cleaner` enumerates the segments referenced by the latest
4//! published inode of a hyperfile and (optionally) deletes anything
5//! in a configured `[low, high]` segid range that isn't referenced.
6//!
7//! See the crate-level [`Cleaner`] trait for the public API shape.
8
9use std::io::{Result, Error, ErrorKind};
10use std::collections::BTreeSet;
11use std::sync::Arc;
12use aws_sdk_s3::Client;
13use log::{debug, error};
14use btree_ondisk::bmap::BMap;
15use btree_ondisk::BlockLoader;
16use btree_ondisk::NullNodeCache;
17use hyperfile::{BlockIndex, BlockPtr, Cno, SegmentId, s3_code_kind, s3_error_kind};
18use hyperfile::file::ReadTiming;
19use hyperfile::meta_loader::s3::S3BlockLoader;
20use hyperfile::ondisk::InodeRaw;
21use hyperfile::inode::{Inode, OnDiskState};
22use hyperfile::segment::{Segment, SegmentSum, SegmentReadWrite};
23use hyperfile::staging::{Staging, config::StagingConfig, s3::S3Staging};
24use hyperfile::config::{HyperFileMetaConfig, HyperFileRuntimeConfig};
25use hyperfile::s3uri::S3Uri;
26use hyperfile::meta_format::BlockPtrFormat;
27use crate::Cleaner;
28
29/// S3-backed cleaner for a single hyperfile rooted at a given
30/// `s3://<bucket>/<prefix>` URI.
31///
32/// The cleaner does not retain or open the file's data. It only
33/// reads the published inode and walks the metadata B+tree to
34/// enumerate referenced segments, then deletes the unreferenced
35/// ones via `DeleteObjects`.
36///
37/// Concurrency: the cleaner is not aware of in-flight writers. If
38/// a writer publishes a new checkpoint while `collect` /
39/// `prune` is running, the result reflects whatever inode was
40/// loaded at the start of the call. New segments published after
41/// that point are outside the configured `[low, high]` range and
42/// are not affected.
43pub struct S3Cleaner {
44    client: Client,
45    bucket: String,
46    root_path: String,
47    staging: S3Staging,
48}
49
50impl S3Cleaner {
51    /// Construct a cleaner for `root_uri`, using the AWS SDK's
52    /// default credential / region resolution
53    /// (`aws_config::load_from_env`).
54    ///
55    /// Returns `InvalidInput` if `root_uri` is not a valid S3 URI.
56    pub async fn new(root_uri: &str) -> Result<Self> {
57        let cfg = aws_config::load_from_env().await;
58        let client = Client::new(&cfg);
59        Self::with_client(&client, root_uri).await
60    }
61
62    /// Construct a cleaner using a caller-supplied `Client`. Use
63    /// this when you need to control region / endpoint / credential
64    /// resolution explicitly (for example, in tests or in a tool
65    /// that already has a configured client).
66    ///
67    /// Returns `InvalidInput` if `root_uri` is not a valid S3 URI.
68    pub async fn with_client(client: &Client, root_uri: &str) -> Result<Self> {
69        let trimmed = trim_root_uri(root_uri);
70        let s3uri = S3Uri::parse(trimmed).map_err(|e| {
71            Error::new(
72                ErrorKind::InvalidInput,
73                format!("invalid S3 URI {:?}: {}", root_uri, e),
74            )
75        })?;
76        let runtime_config = HyperFileRuntimeConfig::default();
77        let staging_config = StagingConfig::new_s3_staging(s3uri.bucket, "", s3uri.key, None);
78        let staging = S3Staging::from(client, staging_config, runtime_config).await?;
79        Ok(Self {
80            client: client.clone(),
81            bucket: s3uri.bucket.to_owned(),
82            root_path: s3uri.key.to_owned(),
83            staging,
84        })
85    }
86
87    async fn load_segment_sum(&self, segid: SegmentId) -> Result<SegmentSum> {
88        self.staging.open(segid).await
89    }
90
91    /// The URI this cleaner was built for, as a writer would need it.
92    pub(crate) fn root_uri(&self) -> String {
93        format!("s3://{}/{}", self.bucket, self.root_path)
94    }
95
96    /// The client, for an operation that needs to open the file itself.
97    pub(crate) fn client(&self) -> &Client {
98        &self.client
99    }
100
101    async fn load_raw_inode(&self) -> Result<(InodeRaw, Option<OnDiskState>)> {
102        let mut raw_inode = InodeRaw::default();
103        let inode_state = self.staging.load_inode(raw_inode.as_mut_u8_slice()).await?;
104        Ok((raw_inode, inode_state))
105    }
106
107    /// Every location the bmap still points into, split by what holds it.
108    ///
109    /// `collect_ptrs` reports every location the map references — its metadata
110    /// nodes and the block pointers stored in its leaves — for both bmap shapes,
111    /// so this needs no shape branch of its own. It returns `Err` rather than a
112    /// short list if any subtree could not be enumerated, which is what makes it
113    /// safe to derive a delete set from: a truncated reachable set is
114    /// indistinguishable from a complete one.
115    ///
116    /// `collect_meta_ptrs` is the metadata-node subset of the same walk, and
117    /// reads no leaf node to answer. Having both is what lets an object's live
118    /// bytes be counted — a metadata node is `meta_block_size`, a data block is
119    /// `data_block_size`, and a pointer does not say which it is — and it is what
120    /// tells a compactor which objects it cannot free: a live metadata node is
121    /// not relocatable by rewriting data blocks.
122    fn walk_live_ptrs<L>(
123        bmap: BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, NullNodeCache>,
124    ) -> Result<LivePtrs>
125    where
126        L: BlockLoader<BlockPtr> + Clone,
127    {
128        // `collect_ptrs` is a plain `async fn`, but a bmap built with
129        // btree-ondisk's `rc` feature is `!Send`, so awaiting it directly
130        // would make `collect`/`prune` non-`Send` and break the `Cleaner`
131        // trait. The walk therefore stays on the blocking thread this
132        // function is called from, driven the same way btree-ondisk drives
133        // itself under `tokio-runtime`.
134        let handle = tokio::runtime::Handle::current();
135        let on_staging = |v: Vec<BlockPtr>| -> BTreeSet<BlockPtr> {
136            v.into_iter().filter(BlockPtrFormat::is_on_staging).collect()
137        };
138        let all = on_staging(handle.block_on(bmap.collect_ptrs())?);
139        let meta = on_staging(handle.block_on(bmap.collect_meta_ptrs())?);
140        Ok(LivePtrs { all, meta })
141    }
142
143    /// Every segment object that exists under the container's prefix, with its
144    /// size, and whatever else is there.
145    ///
146    /// A segment object is named by [`Segment::segid_to_staging_file_id`]: ten
147    /// digits, and a `.<part>` suffix when the checkpoint was streamed. Anything
148    /// else under the prefix — the inode object, a nested WAL prefix — is not one
149    /// and is skipped, as is any key with a further `/` in it. What was skipped is
150    /// reported rather than discarded: a key under this prefix that is neither the
151    /// inode nor a segment object is most likely a WAL, and a compaction must not
152    /// run against a container whose log it is not reading.
153    ///
154    /// The delete set is derived from what is *here*, not from arithmetic over
155    /// `[low, high]`. Two reasons, both new in `hyperfile 0.7.0`: a checkpoint's
156    /// object names are no longer derivable from its number, since a streamed one
157    /// is `<cno>.0`, `<cno>.1`, … with no bound the caller knows; and a partial
158    /// whose checkpoint was abandoned is referenced by nothing and named by
159    /// nothing, so a walk that only visits computed names cannot see it at all.
160    async fn list_segment_objects(&self) -> Result<ObjectListing> {
161        let prefix = format!("{}/", self.root_path);
162        let mut listing = ObjectListing::default();
163        let mut pages = self.client.list_objects_v2()
164            .bucket(&self.bucket)
165            .prefix(&prefix)
166            .into_paginator()
167            .send();
168        while let Some(page) = pages.next().await {
169            let page = page.map_err(|e| Error::new(
170                s3_error_kind(&e),
171                format!("listing segment objects under s3://{}/{} failed: {}",
172                    self.bucket, prefix, e),
173            ))?;
174            for obj in page.contents() {
175                let Some(key) = obj.key() else { continue };
176                if key == self.staging.inode_file {
177                    continue;
178                }
179                let Some(name) = key.strip_prefix(&prefix) else { continue };
180                match parse_segment_object_name(name) {
181                    Some(segid) => {
182                        listing.objects.push((segid, obj.size().unwrap_or(0).max(0) as u64));
183                    },
184                    None => {
185                        listing.foreign += 1;
186                        if listing.foreign_sample.is_none() {
187                            listing.foreign_sample = Some(key.to_string());
188                        }
189                    },
190                }
191            }
192        }
193        listing.objects.sort();
194        Ok(listing)
195    }
196
197    /// Delete `delete_keys` from `bucket` in batches of 1000 (the
198    /// `DeleteObjects` per-call max).
199    ///
200    /// Failures are tracked at two levels and merged into the same
201    /// returned error:
202    ///
203    /// 1. **SDK-level (transport / auth / etc.)**: the entire batch
204    ///    is recorded as failed. The SDK error is logged at
205    ///    `error!` level.
206    /// 2. **Per-key (S3 partial success in `DeleteObjectsOutput`)**:
207    ///    `DeleteObjects` is a partial-success API; even when the
208    ///    batch returns `Ok`, individual keys may have failed (e.g.
209    ///    `AccessDenied`, `NoSuchKey`). The response's `errors`
210    ///    list is parsed and each failing key recorded.
211    ///
212    /// Returns an error if any key (at either level) failed, whose kind is
213    /// that of the **first** failure, classified by `hyperfile`'s own
214    /// [`s3_error_kind`] and [`s3_code_kind`] — the same rule its batch delete
215    /// follows, so a caller decides whether to retry `prune` by the kind alone
216    /// (`hyperfile::is_retryable`): a throttled or unreachable store is worth
217    /// another try, a denied key is not. The message includes the
218    /// failed object count and a sample failed key. Successfully-deleted keys
219    /// stay deleted (S3 has no transactional batch delete).
220    async fn do_delete_objects(
221        client: &Client,
222        bucket: &str,
223        delete_keys: Vec<String>,
224    ) -> Result<()> {
225        use aws_sdk_s3::types::ObjectIdentifier;
226        if delete_keys.is_empty() {
227            return Ok(());
228        }
229        let mut failed_keys: Vec<String> = Vec::new();
230        let mut first_kind: Option<ErrorKind> = None;
231        for keys in delete_keys.chunks(1000) {
232            let obj_ids = keys.iter()
233                .map(|k| {
234                    ObjectIdentifier::builder()
235                        .key(k)
236                        .build()
237                        .expect("ObjectIdentifier requires non-empty key")
238                })
239                .collect::<Vec<ObjectIdentifier>>();
240            // We use quiet=true so the response only carries the
241            // `errors` list (not the success list); this is what
242            // we want for partial-failure tracking.
243            let delete = aws_sdk_s3::types::Delete::builder()
244                .set_objects(Some(obj_ids))
245                .quiet(true)
246                .build()
247                .expect("Delete::builder requires non-empty object list");
248            match client.delete_objects()
249                .bucket(bucket)
250                .delete(delete)
251                .send()
252                .await
253            {
254                Ok(output) => {
255                    // Partial-success path: even though the batch
256                    // returned Ok at the SDK level, individual keys
257                    // may have failed. Pick those out of the
258                    // response.
259                    if let Some(errors) = output.errors {
260                        for e in errors {
261                            let key = e.key.unwrap_or_default();
262                            let code = e.code.as_deref().unwrap_or("?");
263                            let msg = e.message.as_deref().unwrap_or("");
264                            error!("DeleteObjects per-key failure: key={} code={} message={}",
265                                key, code, msg);
266                            first_kind.get_or_insert(s3_code_kind(e.code.as_deref()));
267                            if !key.is_empty() {
268                                failed_keys.push(key);
269                            }
270                        }
271                    }
272                },
273                Err(sdk_err) => {
274                    // SDK-level failure: treat the whole batch as
275                    // failed (we don't know which keys made it).
276                    error!("DeleteObjects batch failed (bucket={}, count={}): {}",
277                        bucket, keys.len(), sdk_err);
278                    first_kind.get_or_insert(s3_error_kind(&sdk_err));
279                    failed_keys.extend(keys.iter().cloned());
280                }
281            }
282        }
283        if failed_keys.is_empty() {
284            Ok(())
285        } else {
286            Err(Error::new(
287                first_kind.unwrap_or(ErrorKind::Other),
288                format!(
289                    "DeleteObjects failed for {} object(s); first failed key: {:?}",
290                    failed_keys.len(),
291                    failed_keys.first(),
292                ),
293            ))
294        }
295    }
296
297    /// Everything `collect`, `report` and `compact` need from storage, gathered
298    /// once: the checkpoint being walked, the container's pointer format and
299    /// block sizes, every live location, and every object that exists.
300    ///
301    /// `high == 0` is a sentinel meaning "use the latest checkpoint
302    /// (`inode.get_last_cno()`)".
303    pub(crate) async fn view(&self, low: Cno, high: Cno) -> Result<ContainerView> {
304        // Read unconditionally, not only for the `high == 0` sentinel: the
305        // container's pointer format lives in the inode, and it decides both
306        // which object holds a checkpoint's summary and how a pointer decodes.
307        let (raw_inode, inode_state) = self.load_raw_inode().await?;
308        refuse_unsegmented(&raw_inode)?;
309        let fmt = container_ptr_format(&raw_inode);
310        let latest_compacted = raw_inode.is_compacted();
311        let high_cno = if high == 0 {
312            let inode = Inode::from_raw(&raw_inode, inode_state);
313            inode.get_last_cno()
314        } else {
315            high
316        };
317
318        debug!("view of container low: {}, high: {}, format: {:?}", low, high_cno, fmt);
319        validate_segid_range(low, high_cno)?;
320
321        // Which object holds this checkpoint's summary, metadata and inode:
322        // part 0 when the container streams its checkpoints, the bare name
323        // otherwise. `Staging::open` would find it either way — given a bare
324        // number with no object of that name it tries the summary part too —
325        // but naming it outright saves a 404 on every parted container, which
326        // since `hyperfile 0.7.0` is every container it creates.
327        let high_summary = summary_obj(high_cno, &fmt);
328        let ss = self.load_segment_sum(high_summary).await?;
329        // The whole inode is moved into the walk, not just its `i_bmap` field:
330        // `BMap::read` wants an 8-byte-aligned buffer, and `BMapRawType` is
331        // `[u8; N]`, whose own alignment is 1, so a copy of the field alone
332        // lands wherever the compiler put it. `InodeRaw` is `align(8)` and
333        // `i_bmap` sits at an 8-aligned offset within it, so borrowing the
334        // field out of an owned inode is aligned by construction.
335        let ss_inode = ss.hdr.s_inode;
336        // Both sizes come from the segment header rather than from the inode's
337        // `i_meta_config`: they have been there since the first release, while
338        // that field was zero on containers old enough that it cannot be
339        // decoded at all.
340        let meta_block_size = 1usize << ss.hdr.s_meta_blk_shift;
341        let data_block_size = 1usize << ss.hdr.s_data_blk_shift;
342
343        // Walk the bmap on a blocking thread: a bmap built with
344        // btree-ondisk's `rc` feature is `!Send`, so it cannot be held
345        // across an await in a `Cleaner` method.
346        // Counters are per-loader and the cleaner has nowhere to report
347        // them, so give this walk its own throwaway ReadTiming rather
348        // than threading one through the public API.
349        let loader = S3BlockLoader::new(
350            &self.client, &self.bucket, &self.root_path,
351            Arc::new(ReadTiming::default()),
352        );
353        let join = tokio::task::spawn_blocking(move || -> Result<LivePtrs> {
354            let bmap = BMap::<BlockIndex, BlockPtr, BlockPtr, S3BlockLoader, NullNodeCache>
355                ::read(&ss_inode.i_bmap, meta_block_size, loader, NullNodeCache)?;
356            Self::walk_live_ptrs(bmap)
357        });
358        let live = match join.await {
359            Ok(inner) => inner?,
360            Err(join_err) => {
361                return Err(Error::other(
362                    format!("bmap walk task failed to join: {}", join_err),
363                ));
364            }
365        };
366
367        let listing = self.list_segment_objects().await?;
368        Ok(ContainerView {
369            low,
370            high_cno,
371            latest_compacted,
372            fmt,
373            high_summary,
374            data_block_size,
375            meta_block_size,
376            live,
377            listing,
378        })
379    }
380
381    /// Inner shared implementation used by both `collect` and
382    /// `prune`. Returns `(referenced, unreferenced)` lists of segment
383    /// *objects* where:
384    ///  - `referenced` is every object the latest published inode's metadata
385    ///    tree still points into, whether or not it falls in `[low, high]`.
386    ///  - `unreferenced` is every object that exists under the container's
387    ///    prefix whose checkpoint number falls in `[low, high]` and which
388    ///    nothing points into, less the two kinds this keeps regardless (see
389    ///    [`partition_objects`]).
390    async fn collect_unref_seg(
391        &self,
392        low: Cno,
393        high: Cno,
394    ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
395        let view = self.view(low, high).await?;
396        Ok(partition_objects(
397            &view.object_ids(),
398            &view.referenced_objects(),
399            view.low,
400            view.high_cno,
401            view.high_summary,
402        ))
403    }
404}
405
406/// Every live location of a container, and the metadata-node subset of it.
407pub(crate) struct LivePtrs {
408    pub(crate) all: BTreeSet<BlockPtr>,
409    pub(crate) meta: BTreeSet<BlockPtr>,
410}
411
412/// What a listing of the container's prefix found.
413#[derive(Default)]
414pub(crate) struct ObjectListing {
415    /// Segment objects and their sizes, ascending.
416    pub(crate) objects: Vec<(SegmentId, u64)>,
417    /// How many keys under the prefix were neither the inode nor a segment
418    /// object. A WAL root nested under the container is the usual reason.
419    pub(crate) foreign: usize,
420    pub(crate) foreign_sample: Option<String>,
421}
422
423/// One pass over a container's storage, shared by every operation.
424pub(crate) struct ContainerView {
425    pub(crate) low: Cno,
426    pub(crate) high_cno: Cno,
427    /// Whether the published inode marks its checkpoint as a compaction
428    /// (`InodeRaw::FLAG_COMPACTED`): it moved blocks and changed no content.
429    pub(crate) latest_compacted: bool,
430    pub(crate) fmt: BlockPtrFormat,
431    pub(crate) high_summary: SegmentId,
432    pub(crate) data_block_size: usize,
433    pub(crate) meta_block_size: usize,
434    pub(crate) live: LivePtrs,
435    pub(crate) listing: ObjectListing,
436}
437
438impl ContainerView {
439    pub(crate) fn object_ids(&self) -> Vec<SegmentId> {
440        self.listing.objects.iter().map(|(segid, _)| *segid).collect()
441    }
442
443    /// The objects at least one live location names.
444    pub(crate) fn referenced_objects(&self) -> BTreeSet<SegmentId> {
445        self.live.all.iter()
446            .map(|p| BlockPtrFormat::decode(p, &self.fmt).0)
447            .collect()
448    }
449
450    /// Which object a live location is in.
451    pub(crate) fn object_of(&self, blkptr: &BlockPtr) -> SegmentId {
452        BlockPtrFormat::decode(blkptr, &self.fmt).0
453    }
454}
455
456/// `root_uri` without one trailing `/`, unless that `/` is part of the scheme.
457///
458/// Stripping it unconditionally turned `s3://` into `s3:/`, which the parse then
459/// refused for not starting with `s3://` — the opposite of what was wrong with it.
460/// `hyperfile 0.10.3` fixed the same thing in `StagingConfig::new_s3_uri`.
461fn trim_root_uri(root_uri: &str) -> &str {
462    match root_uri.strip_suffix('/') {
463        Some(r) if !r.ends_with(":/") => r,
464        _ => root_uri,
465    }
466}
467
468/// `S_IFMT` and the two device types, as the inode stores its mode. POSIX fixes
469/// these values, so they are the same on every host.
470const S_IFMT: u32 = 0o170000;
471const S_IFCHR: u32 = 0o020000;
472const S_IFBLK: u32 = 0o060000;
473
474/// Refuse an inode whose checkpoint fields do not hold checkpoint numbers.
475///
476/// An inline file keeps its data in the inode's tail, over `i_last_seq`,
477/// `i_last_cno` and the bmap root; a device node keeps its `rdev` in
478/// `i_last_cno`. Read as a checkpoint number either is whatever the bytes
479/// happen to be. Nothing would be deleted on the strength of it — the summary
480/// it named would not be found — but the error would point at a missing segment
481/// rather than at what is actually wrong.
482fn refuse_unsegmented(raw: &InodeRaw) -> Result<()> {
483    let fmt = raw.i_mode & S_IFMT;
484    let what = if raw.is_inline() {
485        Some("an inline file, whose data lives in the inode")
486    } else if fmt == S_IFCHR || fmt == S_IFBLK {
487        Some("a device node, which stores rdev where a checkpoint number would be")
488    } else {
489        None
490    };
491    match what {
492        Some(what) => Err(Error::new(
493            ErrorKind::InvalidInput,
494            format!("this container is {}: it has no segments to collect, prune or compact", what),
495        )),
496        None => Ok(()),
497    }
498}
499
500/// The pointer format the container was written with, as its inode records it.
501///
502/// Falls back to the pre-parting format rather than failing. A container written
503/// before `i_meta_config` was populated carries zero there, which decodes to
504/// nothing usable — and a container that old cannot be parted, because parting
505/// did not exist. The only thing this decides is how a pointer's low bits are
506/// read and which name holds a summary, and for every format but
507/// `PartedSegment` those are what they have always been.
508fn container_ptr_format(raw_inode: &InodeRaw) -> BlockPtrFormat {
509    match HyperFileMetaConfig::try_from_u32(raw_inode.i_meta_config) {
510        Ok(cfg) => cfg.block_ptr_format,
511        Err(e) => {
512            debug!("inode meta config {:#x} is not one this build can read ({}); \
513                reading pointers as {:?}", raw_inode.i_meta_config, e,
514                BlockPtrFormat::MicroGroup);
515            BlockPtrFormat::MicroGroup
516        },
517    }
518}
519
520/// The object holding a checkpoint's summary, metadata blocks and inode.
521fn summary_obj(cno: Cno, fmt: &BlockPtrFormat) -> SegmentId {
522    let segid = SegmentId::new_from_cno(cno);
523    if fmt.is_parted() {
524        segid.at_part(Segment::SUMMARY_PART)
525    } else {
526        segid
527    }
528}
529
530/// A segment object name, or `None` for a key that is not one.
531///
532/// The names are what [`Segment::segid_to_staging_file_id`] produces: ten digits
533/// zero-padded, optionally `.<part>`. `None` and `Some(0)` are different names
534/// on purpose upstream, so they stay different objects here.
535fn parse_segment_object_name(name: &str) -> Option<SegmentId> {
536    // Nested prefixes — a WAL root under the container, say — are not segment
537    // objects of this container.
538    if name.contains('/') {
539        return None;
540    }
541    let (seq_str, part_str) = match name.split_once('.') {
542        Some((seq, part)) => (seq, Some(part)),
543        None => (name, None),
544    };
545    if seq_str.len() != 10 || !seq_str.bytes().all(|b| b.is_ascii_digit()) {
546        return None;
547    }
548    // Ten digits can name more than a `u32` holds; such an object cannot have
549    // been written by this format, so it is not one of ours.
550    let seq_id = seq_str.parse::<u32>().ok()?;
551    match part_str {
552        None => Some(SegmentId::new(seq_id)),
553        Some(p) => {
554            if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
555                return None;
556            }
557            Some(SegmentId::with_part(seq_id, p.parse::<u16>().ok()?))
558        },
559    }
560}
561
562/// Split what exists into what is still pointed into and what can go.
563///
564/// `referenced` is object-granular, which is what makes a parted container
565/// reclaimable at all. Two kinds of object are kept even when no pointer names
566/// them:
567///
568/// - **The summary of `high`.** It is the object this cleaner just read to find
569///   the checkpoint's bmap, and the one it would read on the next run. A
570///   container whose newest checkpoint holds no live block — an empty file, or
571///   one whose every block was superseded within the same checkpoint — would
572///   otherwise have its own head deleted, and the next `collect` would fail with
573///   `NoSuchKey`.
574/// - **The summary part of a checkpoint that still has a live part.** Only
575///   reachable under `PartedSegment`: the parts carry data, part 0 carries the
576///   summary and metadata that describe them. Deleting it would leave a
577///   checkpoint whose blocks are live but which nothing can parse, which is what
578///   `open_cno` and a repair tool need. "Not a partial" is upstream's own
579///   predicate for that object — a partial is a part above zero, and an unparted
580///   checkpoint is never one.
581///
582/// Everything else in `[low, high]` that nothing points into is reclaimable,
583/// including the partials of a checkpoint that was abandoned — those share their
584/// checkpoint number with the retry that replaced them, so they are invisible to
585/// anything reasoning in whole checkpoints.
586fn partition_objects(
587    existing: &[SegmentId],
588    referenced: &BTreeSet<SegmentId>,
589    low: Cno,
590    high: Cno,
591    high_summary: SegmentId,
592) -> (Vec<SegmentId>, Vec<SegmentId>) {
593    let live_cnos: BTreeSet<Cno> = referenced.iter().map(|s| s.as_cno()).collect();
594    let mut unref = Vec::new();
595    for obj in existing {
596        let cno = obj.as_cno();
597        if cno < low || cno > high {
598            continue;
599        }
600        if referenced.contains(obj) {
601            continue;
602        }
603        if *obj == high_summary {
604            continue;
605        }
606        if !obj.is_partial() && live_cnos.contains(&cno) {
607            continue;
608        }
609        unref.push(*obj);
610    }
611    let v_ref = referenced.iter().copied().collect::<Vec<SegmentId>>();
612    (v_ref, unref)
613}
614
615/// Reject a checkpoint range that cannot be walked.
616///
617/// `[low, high]` is inclusive at both ends, so `low == high_cno` is a
618/// well-formed query — "what does checkpoint N reference, and is anything in
619/// `[N, N]` unreferenced" — and is answered normally. It is reached whenever a
620/// caller asks about the entire history of a file with a single checkpoint:
621/// `collect(1, 0)`, the form this crate's own documentation gives as the typical
622/// call, resolves `high` to `get_last_cno() == 1` and so lands on `low == high`.
623/// Rejecting it made `collect` and `prune` unusable on any freshly created file
624/// until it had been flushed at least twice.
625///
626/// `low > high_cno` is genuinely empty and stays an error, which also covers
627/// `high_cno == 0` (no checkpoint has ever been published, so there is no
628/// metadata tree to walk).
629///
630/// A checkpoint number past `u32::MAX` is refused rather than truncated: that is
631/// what a block pointer can name, so no object could carry the number, and
632/// `SegmentId::new_from_cno` would assert on it in a debug build.
633fn validate_segid_range(low: Cno, high_cno: Cno) -> Result<()> {
634    if low > high_cno {
635        return Err(Error::new(
636            ErrorKind::InvalidInput,
637            format!("invalid segment range [{}, {}]", low, high_cno),
638        ));
639    }
640    if high_cno > u32::MAX as Cno {
641        return Err(Error::new(
642            ErrorKind::InvalidInput,
643            format!("checkpoint {} is past what a block pointer can name ({})",
644                high_cno, u32::MAX),
645        ));
646    }
647    Ok(())
648}
649
650impl Cleaner for S3Cleaner {
651    async fn collect(
652        &self,
653        low: Cno,
654        high: Cno,
655    ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
656        self.collect_unref_seg(low, high).await
657    }
658
659    /// Prune unreferenced segment objects in `[low, high]`. Implemented
660    /// as `collect` followed by `DeleteObjects` of the
661    /// unreferenced list.
662    async fn prune(&self, low: Cno, high: Cno) -> Result<()> {
663        let (_, non_ref) = self.collect_unref_seg(low, high).await?;
664        let delete_keys = non_ref.iter()
665            .map(|segid| format!(
666                "{}/{}",
667                self.root_path,
668                Segment::segid_to_staging_file_id(*segid),
669            ))
670            .collect::<Vec<String>>();
671        debug!("unreferenced segments to delete: {:?}", delete_keys);
672        Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679
680    /// Builder calls in `do_delete_objects` panic only on empty
681    /// inputs that we guard against. Verify the empty-input fast
682    /// path.
683    #[tokio::test]
684    async fn delete_empty_keys_is_noop() {
685        let cfg = aws_config::load_from_env().await;
686        let client = Client::new(&cfg);
687        // Empty list -> no SDK call -> Ok regardless of credentials.
688        let r = S3Cleaner::do_delete_objects(&client, "any-bucket", Vec::new()).await;
689        assert!(r.is_ok(), "empty key list should not call S3");
690    }
691
692    /// `[low, high]` is inclusive at both ends, so a single-checkpoint
693    /// file -- where `collect(1, 0)` resolves to `low == high == 1` --
694    /// must be accepted. It used to be rejected, which made the
695    /// documented call form fail on any file flushed only once.
696    #[test]
697    fn segid_range_accepts_a_single_checkpoint() {
698        assert!(validate_segid_range(1, 1).is_ok());
699    }
700
701    #[test]
702    fn segid_range_accepts_a_normal_span() {
703        assert!(validate_segid_range(1, 5).is_ok());
704    }
705
706    /// Only a genuinely empty range is an error. `high_segid == 0` is the
707    /// "no checkpoint published yet" case and falls out of the same rule.
708    #[test]
709    fn segid_range_rejects_an_empty_span() {
710        for (low, high) in [(5u64, 3u64), (2, 1), (1, 0)] {
711            let e = validate_segid_range(low, high)
712                .expect_err("low > high must be rejected");
713            assert_eq!(e.kind(), ErrorKind::InvalidInput);
714            assert!(
715                e.to_string().contains(&format!("[{}, {}]", low, high)),
716                "error should name the range, got {:?}", e.to_string(),
717            );
718        }
719    }
720
721    #[test]
722    fn a_trailing_slash_is_trimmed_but_not_the_schemes() {
723        assert_eq!(trim_root_uri("s3://b/k/"), "s3://b/k");
724        assert_eq!(trim_root_uri("s3://b/k"), "s3://b/k");
725        assert_eq!(trim_root_uri("s3://"), "s3://");
726        assert_eq!(trim_root_uri("S3://"), "S3://");
727        assert_eq!(trim_root_uri(""), "");
728    }
729
730    /// An inline file's checkpoint fields hold its data, and a device node's hold
731    /// its rdev. Neither is a checkpoint number, so the walk refuses up front
732    /// rather than looking for a segment the bytes happen to name.
733    #[test]
734    fn an_inode_without_segments_is_refused() {
735        let mut inline = InodeRaw { i_mode: 0o100644, ..Default::default() };
736        inline.set_inline(b"hello");
737        let e = refuse_unsegmented(&inline).expect_err("inline must be refused");
738        assert_eq!(e.kind(), ErrorKind::InvalidInput);
739        assert!(e.to_string().contains("inline"), "{}", e);
740
741        for mode in [0o020644u32, 0o060644] {
742            let dev = InodeRaw { i_mode: mode, ..Default::default() };
743            let e = refuse_unsegmented(&dev).expect_err("a device node must be refused");
744            assert!(e.to_string().contains("device"), "{}", e);
745        }
746
747        for mode in [0o100644u32, 0o040755, 0o120777] {
748            let ok = InodeRaw { i_mode: mode, ..Default::default() };
749            assert!(refuse_unsegmented(&ok).is_ok(), "mode {:o} has segments", mode);
750        }
751    }
752
753    /// A checkpoint number no pointer could name is refused rather than
754    /// truncated into one that names a different object.
755    #[test]
756    fn segid_range_rejects_a_checkpoint_past_a_pointer() {
757        let e = validate_segid_range(1, u32::MAX as Cno + 1)
758            .expect_err("a cno past u32::MAX must be rejected");
759        assert_eq!(e.kind(), ErrorKind::InvalidInput);
760        assert!(validate_segid_range(1, u32::MAX as Cno).is_ok());
761    }
762
763    // --- object names ---
764
765    #[test]
766    fn object_names_round_trip_through_the_parser() {
767        for segid in [
768            SegmentId::new(1),
769            SegmentId::new(4294967295),
770            SegmentId::with_part(7, 0),
771            SegmentId::with_part(7, 16383),
772        ] {
773            let name = Segment::segid_to_staging_file_id(segid);
774            assert_eq!(parse_segment_object_name(&name), Some(segid),
775                "name {:?} did not parse back", name);
776        }
777    }
778
779    /// An unsuffixed name and part 0 are different objects upstream, so they
780    /// have to stay different here — sharing them would mean deleting the
781    /// summary of one container shape while reporting the other.
782    #[test]
783    fn a_bare_name_is_not_part_zero() {
784        assert_eq!(parse_segment_object_name("0000000007"), Some(SegmentId::new(7)));
785        assert_eq!(parse_segment_object_name("0000000007.0"),
786            Some(SegmentId::with_part(7, 0)));
787    }
788
789    #[test]
790    fn keys_that_are_not_segment_objects_are_skipped() {
791        for name in [
792            "inode",              // the inode object
793            "wal/0000000001",     // a nested prefix, not an object of ours
794            "0000000001/0_0_4096",
795            "000000001",          // nine digits
796            "00000000012",        // eleven
797            "9999999999",         // ten digits, past what a u32 can hold
798            "0000000001.",        // empty part
799            "0000000001.x",
800            "0000000001.65536",   // past what a u16 can hold
801            "0000000001.0.1",
802            "",
803        ] {
804            assert_eq!(parse_segment_object_name(name), None,
805                "{:?} should not be read as a segment object", name);
806        }
807    }
808
809    // --- what gets reclaimed ---
810
811    fn partition(
812        existing: &[SegmentId],
813        referenced: &[SegmentId],
814        low: Cno,
815        high: Cno,
816        high_summary: SegmentId,
817    ) -> Vec<SegmentId> {
818        let set: BTreeSet<SegmentId> = referenced.iter().copied().collect();
819        let (_, unref) = partition_objects(existing, &set, low, high, high_summary);
820        unref
821    }
822
823    /// The unparted case, which is every container written before 0.7.0: an
824    /// object is a checkpoint, and one nothing points into goes.
825    #[test]
826    fn an_unreferenced_checkpoint_is_reclaimable() {
827        let existing = [SegmentId::new(1), SegmentId::new(2), SegmentId::new(3)];
828        let unref = partition(&existing, &[SegmentId::new(3)], 1, 3, SegmentId::new(3));
829        assert_eq!(unref, vec![SegmentId::new(1), SegmentId::new(2)]);
830    }
831
832    /// Objects outside `[low, high]` are not candidates, which is what makes a
833    /// prune safe against a writer publishing underneath it.
834    #[test]
835    fn objects_outside_the_range_are_left_alone() {
836        let existing = [
837            SegmentId::new(1), SegmentId::new(2), SegmentId::new(3), SegmentId::new(4),
838        ];
839        let unref = partition(&existing, &[], 2, 3, SegmentId::new(9));
840        assert_eq!(unref, vec![SegmentId::new(2), SegmentId::new(3)]);
841    }
842
843    /// A checkpoint whose newest state holds no live block would otherwise have
844    /// its own head deleted, and the next `collect` would fail to read it.
845    #[test]
846    fn the_summary_of_high_is_kept_even_when_nothing_points_into_it() {
847        let existing = [SegmentId::new(1), SegmentId::new(2)];
848        let unref = partition(&existing, &[], 1, 2, SegmentId::new(2));
849        assert_eq!(unref, vec![SegmentId::new(1)]);
850
851        // Same for a streamed container, where the head is part 0.
852        let existing = [SegmentId::with_part(2, 0), SegmentId::with_part(2, 1)];
853        let unref = partition(&existing, &[], 1, 2, SegmentId::with_part(2, 0));
854        assert_eq!(unref, vec![SegmentId::with_part(2, 1)]);
855    }
856
857    /// The partials of an abandoned checkpoint share their number with the
858    /// retry that replaced them. Reclaiming them is the whole reason the
859    /// referenced set is object-granular.
860    #[test]
861    fn an_abandoned_partial_is_reclaimable_while_its_checkpoint_lives() {
862        let existing = [
863            SegmentId::with_part(5, 0), // summary of the checkpoint that landed
864            SegmentId::with_part(5, 1), // its data
865            SegmentId::with_part(5, 2), // written, then abandoned by a rollback
866        ];
867        let referenced = [SegmentId::with_part(5, 0), SegmentId::with_part(5, 1)];
868        let unref = partition(&existing, &referenced, 1, 9, SegmentId::with_part(9, 0));
869        assert_eq!(unref, vec![SegmentId::with_part(5, 2)]);
870    }
871
872    /// A live checkpoint has to stay parseable: its data parts are named by
873    /// pointers, its summary is what describes them.
874    #[test]
875    fn the_summary_part_of_a_live_checkpoint_is_kept() {
876        let existing = [SegmentId::with_part(4, 0), SegmentId::with_part(4, 3)];
877        let unref = partition(&existing, &[SegmentId::with_part(4, 3)], 1, 9,
878            SegmentId::with_part(9, 0));
879        assert!(unref.is_empty(), "part 0 describes the live part 3, got {:?}", unref);
880    }
881
882    /// With no live part left, the summary goes too — otherwise a parted
883    /// container would never give any storage back.
884    #[test]
885    fn a_wholly_dead_parted_checkpoint_goes_including_its_summary() {
886        let existing = [
887            SegmentId::with_part(4, 0), SegmentId::with_part(4, 1),
888            SegmentId::with_part(6, 0),
889        ];
890        let unref = partition(&existing, &[SegmentId::with_part(6, 0)], 1, 9,
891            SegmentId::with_part(6, 0));
892        assert_eq!(unref, vec![SegmentId::with_part(4, 0), SegmentId::with_part(4, 1)]);
893    }
894}