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::{BTreeMap, BTreeSet};
11use std::sync::Arc;
12use aws_sdk_s3::Client;
13use log::{debug, error};
14use btree_ondisk::bmap::BMap;
15use btree_ondisk::BlockLoader;
16use hyperfile::{BlockIndex, BlockPtr, Cno, SegmentId, s3_code_kind, s3_error_kind};
17use hyperfile::file::ReadTiming;
18use hyperfile::meta_loader::s3::S3BlockLoader;
19use hyperfile::ondisk::InodeRaw;
20use hyperfile::compaction::{PendingCompaction, StoredCompaction};
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    pause_after_view: std::sync::Mutex<Option<PauseHook>>,
49}
50
51/// See [`S3Cleaner::set_pause_after_view`].
52#[doc(hidden)]
53pub type PauseHook = std::sync::Arc<dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> + Send + Sync>;
54
55impl S3Cleaner {
56    /// Construct a cleaner for `root_uri`, using the AWS SDK's
57    /// default credential / region resolution
58    /// (`aws_config::load_from_env`).
59    ///
60    /// Returns `InvalidInput` if `root_uri` is not a valid S3 URI.
61    pub async fn new(root_uri: &str) -> Result<Self> {
62        let cfg = aws_config::load_from_env().await;
63        let client = Client::new(&cfg);
64        Self::with_client(&client, root_uri).await
65    }
66
67    /// Construct a cleaner using a caller-supplied `Client`. Use
68    /// this when you need to control region / endpoint / credential
69    /// resolution explicitly (for example, in tests or in a tool
70    /// that already has a configured client).
71    ///
72    /// Returns `InvalidInput` if `root_uri` is not a valid S3 URI.
73    pub async fn with_client(client: &Client, root_uri: &str) -> Result<Self> {
74        let trimmed = trim_root_uri(root_uri);
75        let s3uri = S3Uri::parse(trimmed).map_err(|e| {
76            Error::new(
77                ErrorKind::InvalidInput,
78                format!("invalid S3 URI {:?}: {}", root_uri, e),
79            )
80        })?;
81        let runtime_config = HyperFileRuntimeConfig::default();
82        let staging_config = StagingConfig::new_s3_staging(s3uri.bucket, "", s3uri.key, None);
83        let staging = S3Staging::from(client, staging_config, runtime_config).await?;
84        Ok(Self {
85            client: client.clone(),
86            bucket: s3uri.bucket.to_owned(),
87            root_path: s3uri.key.to_owned(),
88            staging,
89            pause_after_view: std::sync::Mutex::new(None),
90        })
91    }
92
93    /// For tests: run `hook` in `prune_with`, between reading the container and
94    /// taking the store's time, every time it judges.
95    #[doc(hidden)]
96    pub fn set_pause_after_view(&self, hook: Option<PauseHook>) {
97        *self.pause_after_view.lock().unwrap() = hook;
98    }
99
100    async fn load_segment_sum(&self, segid: SegmentId) -> Result<SegmentSum> {
101        self.staging.open(segid).await
102    }
103
104    /// The URI this cleaner was built for, as a writer would need it.
105    pub(crate) fn root_uri(&self) -> String {
106        format!("s3://{}/{}", self.bucket, self.root_path)
107    }
108
109    /// The client, for an operation that needs to open the file itself.
110    pub(crate) fn client(&self) -> &Client {
111        &self.client
112    }
113
114    async fn load_raw_inode(&self) -> Result<(InodeRaw, Option<OnDiskState>)> {
115        let mut raw_inode = InodeRaw::default();
116        let inode_state = self.staging.load_inode(raw_inode.as_mut_u8_slice()).await?;
117        Ok((raw_inode, inode_state))
118    }
119
120    /// Every location the bmap still points into, split by what holds it.
121    ///
122    /// `collect_ptrs` reports every location the map references — its metadata
123    /// nodes and the block pointers stored in its leaves — for both bmap shapes,
124    /// so this needs no shape branch of its own. It returns `Err` rather than a
125    /// short list if any subtree could not be enumerated, which is what makes it
126    /// safe to derive a delete set from: a truncated reachable set is
127    /// indistinguishable from a complete one.
128    ///
129    /// `collect_meta_ptrs` is the metadata-node subset of the same walk, and
130    /// reads no leaf node to answer. Having both is what lets an object's live
131    /// bytes be counted — a metadata node is `meta_block_size`, a data block is
132    /// `data_block_size`, and a pointer does not say which it is — and it is what
133    /// tells a compactor which objects it cannot free: a live metadata node is
134    /// not relocatable by rewriting data blocks.
135    fn walk_live_ptrs<L>(
136        bmap: BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
137    ) -> Result<LivePtrs>
138    where
139        L: BlockLoader<BlockPtr> + Clone,
140    {
141        // `collect_ptrs` is a plain `async fn`, but a bmap built with
142        // btree-ondisk's `rc` feature is `!Send`, so awaiting it directly
143        // would make `collect`/`prune` non-`Send` and break the `Cleaner`
144        // trait. The walk therefore stays on the blocking thread this
145        // function is called from, driven the same way btree-ondisk drives
146        // itself under `tokio-runtime`.
147        let handle = tokio::runtime::Handle::current();
148        let on_staging = |v: Vec<BlockPtr>| -> BTreeSet<BlockPtr> {
149            v.into_iter().filter(BlockPtrFormat::is_on_staging).collect()
150        };
151        let all = on_staging(handle.block_on(bmap.collect_ptrs())?);
152        let meta = on_staging(handle.block_on(bmap.collect_meta_ptrs())?);
153
154        // Where in the file the mapped blocks are, as windows of at most
155        // `DATA_WINDOW_BLOCKS`. `compact` asks `block_placement` about these
156        // rather than about every index from 0 to EOF: a file can be sparse on a
157        // scale that sweep cannot cover — one with blocks at `1 << 56` has 2^44
158        // indices below them. `seek_key` skips a hole in O(log n), and the walk
159        // above has already loaded every node, so this costs no request.
160        //
161        // Done here, on the map this walk already holds, rather than through
162        // `Hyper::fs_seek_data` on the compacting handle: that takes `&self`,
163        // and holding a `&Hyper` across an await keeps a future from being
164        // `Send`, since a `Hyper` is not `Sync`.
165        let mut windows: Vec<(BlockIndex, usize)> = Vec::new();
166        let mut pos: BlockIndex = 0;
167        loop {
168            let key = match handle.block_on(bmap.seek_key(&pos)) {
169                Ok(key) => key,
170                Err(e) if e.kind() == ErrorKind::NotFound => break,
171                Err(e) => return Err(e),
172            };
173            match windows.last_mut() {
174                Some((start, n)) if *start + *n as BlockIndex == key
175                    && *n + DATA_WINDOW_BLOCKS <= 4 * DATA_WINDOW_BLOCKS =>
176                {
177                    *n += DATA_WINDOW_BLOCKS;
178                },
179                _ => windows.push((key, DATA_WINDOW_BLOCKS)),
180            }
181            match key.checked_add(DATA_WINDOW_BLOCKS as BlockIndex) {
182                Some(next) => pos = next,
183                None => break,
184            }
185        }
186        let node_keys = Self::walk_node_keys(&bmap, &handle)?;
187        Ok(LivePtrs { all, meta, windows, node_keys })
188    }
189
190    /// For each index node of the map (the root, inside the inode, aside): a
191    /// key under it whose block is on storage, and that block's pointer. To
192    /// rewrite a node, a compaction relocates that block: a block's new place
193    /// dirties every node above it, and the flush writes them anew. A node
194    /// with no block on storage anywhere under it -- holes and zero blocks only
195    /// -- is left out: nothing a compaction marks rewrites it. Each node's
196    /// subtree is searched until a block is found, at most all of it.
197    ///
198    /// The nodes are read as a lookup reads them, after the walk above read them
199    /// all: no request of its own beyond what the loader keeps.
200    fn walk_node_keys<L>(
201        bmap: &BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
202        handle: &tokio::runtime::Handle,
203    ) -> Result<BTreeMap<BlockPtr, (BlockIndex, BlockPtr)>>
204    where
205        L: BlockLoader<BlockPtr> + Clone,
206    {
207        let mut keys = BTreeMap::new();
208        if bmap.is_direct() {
209            return Ok(keys);
210        }
211        let first = match handle.block_on(bmap.seek_key(&0)) {
212            Ok(k) => k,
213            Err(e) if e.kind() == ErrorKind::NotFound => return Ok(keys),
214            Err(e) => return Err(e),
215        };
216        // (level, a key in the node), from the root down.
217        let mut stack = vec![(bmap.height() - 1, first)];
218        while let Some((level, key)) = stack.pop() {
219            let children = handle.block_on(bmap.node_children(level, &key))?;
220            for (k, p, _) in children.iter() {
221                if BlockPtrFormat::is_on_staging(p) {
222                    if let Some(found) = Self::block_on_storage_under(bmap, handle, level - 1, *k)? {
223                        keys.insert(*p, found);
224                    }
225                }
226                if level - 1 >= 2 {
227                    stack.push((level - 1, *k));
228                }
229            }
230        }
231        Ok(keys)
232    }
233
234    /// A key in the subtree of the node at `level` holding `key`, whose block is
235    /// on storage, with its pointer: the first found, the subtree searched in
236    /// key order, down to its leaves, until one is. `None` when it has none --
237    /// holes and zero blocks only. The nodes are the walk's, read already.
238    fn block_on_storage_under<L>(
239        bmap: &BMap<'_, BlockIndex, BlockPtr, BlockPtr, L, Prefetched>,
240        handle: &tokio::runtime::Handle,
241        level: usize,
242        key: BlockIndex,
243    ) -> Result<Option<(BlockIndex, BlockPtr)>>
244    where
245        L: BlockLoader<BlockPtr> + Clone,
246    {
247        if level <= 1 {
248            let entries = handle.block_on(bmap.leaf_entries(&key))?;
249            return Ok(entries.into_iter().find(|(_, v)| BlockPtrFormat::is_on_staging(v)));
250        }
251        for (k, _, _) in handle.block_on(bmap.node_children(level, &key))? {
252            if let Some(found) = Self::block_on_storage_under(bmap, handle, level - 1, k)? {
253                return Ok(Some(found));
254            }
255        }
256        Ok(None)
257    }
258
259    /// Every segment object that exists under the container's prefix, with its
260    /// size, and whatever else is there.
261    ///
262    /// A segment object is named by [`Segment::segid_to_staging_file_id`]: ten
263    /// digits, and a `.<part>` suffix when the checkpoint was streamed. Anything
264    /// else under the prefix — the inode object, a nested WAL prefix — is not one
265    /// and is skipped, as is any key with a further `/` in it. What was skipped is
266    /// reported rather than discarded: a key under this prefix that is neither the
267    /// inode nor a segment object is most likely a WAL, and a compaction must not
268    /// run against a container whose log it is not reading.
269    ///
270    /// The delete set is derived from what is *here*, not from arithmetic over
271    /// `[low, high]`. Two reasons, both new in `hyperfile 0.7.0`: a checkpoint's
272    /// object names are no longer derivable from its number, since a streamed one
273    /// is `<cno>.0`, `<cno>.1`, … with no bound the caller knows; and a partial
274    /// whose checkpoint was abandoned is referenced by nothing and named by
275    /// nothing, so a walk that only visits computed names cannot see it at all.
276    async fn list_segment_objects(&self) -> Result<ObjectListing> {
277        let prefix = format!("{}/", self.root_path);
278        let mut listing = ObjectListing::default();
279        let mut pages = self.client.list_objects_v2()
280            .bucket(&self.bucket)
281            .prefix(&prefix)
282            .into_paginator()
283            .send();
284        while let Some(page) = pages.next().await {
285            let page = page.map_err(|e| Error::new(
286                s3_error_kind(&e),
287                format!("listing segment objects under s3://{}/{} failed: {}",
288                    self.bucket, prefix, e),
289            ))?;
290            for obj in page.contents() {
291                let Some(key) = obj.key() else { continue };
292                if key == self.staging.inode_file {
293                    continue;
294                }
295                let Some(name) = key.strip_prefix(&prefix) else { continue };
296                match parse_segment_object_name(name) {
297                    Some(segid) => {
298                        listing.objects.push((segid, obj.size().unwrap_or(0).max(0) as u64));
299                        if let Some(t) = obj.last_modified() {
300                            listing.modified.insert(segid, t.secs());
301                        }
302                    },
303                    None => {
304                        listing.foreign += 1;
305                        if listing.foreign_sample.is_none() {
306                            listing.foreign_sample = Some(key.to_string());
307                        }
308                    },
309                }
310            }
311        }
312        listing.objects.sort();
313        Ok(listing)
314    }
315
316    /// Delete `delete_keys` from `bucket` in batches of 1000 (the
317    /// `DeleteObjects` per-call max).
318    ///
319    /// Failures are tracked at two levels and merged into the same
320    /// returned error:
321    ///
322    /// 1. **SDK-level (transport / auth / etc.)**: the entire batch
323    ///    is recorded as failed. The SDK error is logged at
324    ///    `error!` level.
325    /// 2. **Per-key (S3 partial success in `DeleteObjectsOutput`)**:
326    ///    `DeleteObjects` is a partial-success API; even when the
327    ///    batch returns `Ok`, individual keys may have failed (e.g.
328    ///    `AccessDenied`, `NoSuchKey`). The response's `errors`
329    ///    list is parsed and each failing key recorded.
330    ///
331    /// Returns an error if any key (at either level) failed, whose kind is
332    /// that of the **first** failure, classified by `hyperfile`'s own
333    /// [`s3_error_kind`] and [`s3_code_kind`] — the same rule its batch delete
334    /// follows, so a caller decides whether to retry `prune` by the kind alone
335    /// (`hyperfile::is_retryable`): a throttled or unreachable store is worth
336    /// another try, a denied key is not. The message includes the
337    /// failed object count and a sample failed key. Successfully-deleted keys
338    /// stay deleted (S3 has no transactional batch delete).
339    async fn do_delete_objects(
340        client: &Client,
341        bucket: &str,
342        delete_keys: Vec<String>,
343    ) -> Result<()> {
344        use aws_sdk_s3::types::ObjectIdentifier;
345        if delete_keys.is_empty() {
346            return Ok(());
347        }
348        let mut failed_keys: Vec<String> = Vec::new();
349        let mut first_kind: Option<ErrorKind> = None;
350        for keys in delete_keys.chunks(1000) {
351            let obj_ids = keys.iter()
352                .map(|k| {
353                    ObjectIdentifier::builder()
354                        .key(k)
355                        .build()
356                        .expect("ObjectIdentifier requires non-empty key")
357                })
358                .collect::<Vec<ObjectIdentifier>>();
359            // We use quiet=true so the response only carries the
360            // `errors` list (not the success list); this is what
361            // we want for partial-failure tracking.
362            let delete = aws_sdk_s3::types::Delete::builder()
363                .set_objects(Some(obj_ids))
364                .quiet(true)
365                .build()
366                .expect("Delete::builder requires non-empty object list");
367            match client.delete_objects()
368                .bucket(bucket)
369                .delete(delete)
370                .send()
371                .await
372            {
373                Ok(output) => {
374                    // Partial-success path: even though the batch
375                    // returned Ok at the SDK level, individual keys
376                    // may have failed. Pick those out of the
377                    // response.
378                    if let Some(errors) = output.errors {
379                        for e in errors {
380                            let key = e.key.unwrap_or_default();
381                            let code = e.code.as_deref().unwrap_or("?");
382                            let msg = e.message.as_deref().unwrap_or("");
383                            error!("DeleteObjects per-key failure: key={} code={} message={}",
384                                key, code, msg);
385                            first_kind.get_or_insert(s3_code_kind(e.code.as_deref()));
386                            if !key.is_empty() {
387                                failed_keys.push(key);
388                            }
389                        }
390                    }
391                },
392                Err(sdk_err) => {
393                    // SDK-level failure: treat the whole batch as
394                    // failed (we don't know which keys made it).
395                    error!("DeleteObjects batch failed (bucket={}, count={}): {}",
396                        bucket, keys.len(), sdk_err);
397                    first_kind.get_or_insert(s3_error_kind(&sdk_err));
398                    failed_keys.extend(keys.iter().cloned());
399                }
400            }
401        }
402        if failed_keys.is_empty() {
403            Ok(())
404        } else {
405            Err(Error::new(
406                first_kind.unwrap_or(ErrorKind::Other),
407                format!(
408                    "DeleteObjects failed for {} object(s); first failed key: {:?}",
409                    failed_keys.len(),
410                    failed_keys.first(),
411                ),
412            ))
413        }
414    }
415
416    /// Everything `collect`, `report` and `compact` need from storage, gathered
417    /// once: the checkpoint being walked, the container's pointer format and
418    /// block sizes, every live location, and every object that exists.
419    ///
420    /// `high == 0` is a sentinel meaning "use the latest checkpoint
421    /// (`inode.get_last_cno()`)".
422    pub(crate) async fn view(&self, low: Cno, high: Cno) -> Result<ContainerView> {
423        // Read unconditionally, not only for the `high == 0` sentinel: the
424        // container's pointer format lives in the inode, and it decides both
425        // which object holds a checkpoint's summary and how a pointer decodes.
426        let (raw_inode, inode_state) = self.load_raw_inode().await?;
427        refuse_unsegmented(&raw_inode)?;
428        let fmt = container_ptr_format(&raw_inode)?;
429        let latest_compacted = raw_inode.is_compacted();
430        let compaction = inode_state.as_ref().map(|s| s.compaction.clone()).unwrap_or_default();
431        let latest_cno = Inode::from_raw(&raw_inode, inode_state).get_last_cno();
432        let high_cno = if high == 0 { latest_cno } else { high };
433
434        debug!("view of container low: {}, high: {}, format: {:?}", low, high_cno, fmt);
435        validate_segid_range(low, high_cno)?;
436
437        // Which object holds this checkpoint's summary, metadata and inode:
438        // part 0 when the container streams its checkpoints, the bare name
439        // otherwise. `Staging::open` would find it either way — given a bare
440        // number with no object of that name it tries the summary part too —
441        // but naming it outright saves a 404 on every parted container, which
442        // since `hyperfile 0.7.0` is every container it creates.
443        let high_summary = summary_obj(high_cno, &fmt);
444        let ss = self.load_segment_sum(high_summary).await?;
445        // The summary has to be the checkpoint asked for. Every segment this
446        // crate's hyperfile writes carries its checkpoint number, in either
447        // layout; a header that does not is not one, and walking a bmap read out
448        // of it would report whatever the bytes happen to point at.
449        if !ss.hdr.has_magic() || ss.hdr.s_cno != high_cno {
450            return Err(Error::new(
451                ErrorKind::InvalidData,
452                format!(
453                    "{} does not read as checkpoint {}'s summary (magic {:#x}, checkpoint {})",
454                    high_summary, high_cno, ss.hdr.s_magic, ss.hdr.s_cno,
455                ),
456            ));
457        }
458        // The whole inode is moved into the walk, not just its `i_bmap` field:
459        // `BMap::read` wants an 8-byte-aligned buffer, and `BMapRawType` is
460        // `[u8; N]`, whose own alignment is 1, so a copy of the field alone
461        // lands wherever the compiler put it. `InodeRaw` is `align(8)` and
462        // `i_bmap` sits at an 8-aligned offset within it, so borrowing the
463        // field out of an owned inode is aligned by construction.
464        // The newest checkpoint is walked as the stored inode has it, the map
465        // every reader opens, rather than as its summary does. An older
466        // checkpoint asked for is walked as its summary has it.
467        let walked_stored = high_cno == latest_cno;
468        let ss_inode = if walked_stored { raw_inode } else { ss.hdr.s_inode };
469        // Both sizes come from the segment header rather than from the inode's
470        // `i_meta_config`: they have been there since the first release, while
471        // that field was zero on containers old enough that it cannot be
472        // decoded at all.
473        let meta_block_size = 1usize << ss.hdr.s_meta_blk_shift;
474        let data_block_size = 1usize << ss.hdr.s_data_blk_shift;
475
476        // Walk the bmap on a blocking thread: a bmap built with
477        // btree-ondisk's `rc` feature is `!Send`, so it cannot be held
478        // across an await in a `Cleaner` method.
479        // Counters are per-loader and the cleaner has nowhere to report
480        // them, so give this walk its own throwaway ReadTiming rather
481        // than threading one through the public API.
482        let timing = Arc::new(ReadTiming::default());
483        let loader = S3BlockLoader::new(
484            &self.client, &self.bucket, &self.root_path, timing.clone(),
485        );
486        let join = tokio::task::spawn_blocking(move || -> Result<LivePtrs> {
487            // Every node, read level by level and many at a time, before the
488            // walk asks for them one by one.
489            let nodes = prefetch_nodes(&loader, meta_block_size, &ss_inode)?;
490            let bmap = BMap::<BlockIndex, BlockPtr, BlockPtr, S3BlockLoader, Prefetched>
491                ::read(&ss_inode.i_bmap, meta_block_size, loader, Prefetched(Arc::new(nodes)))?;
492            let live = Self::walk_live_ptrs(bmap);
493            debug!("map walk: {} node reads", timing.snapshot().meta_gets);
494            live
495        });
496        let live = match join.await {
497            Ok(inner) => inner?,
498            Err(join_err) => {
499                return Err(Error::other(
500                    format!("bmap walk task failed to join: {}", join_err),
501                ));
502            }
503        };
504
505        let listing = self.list_segment_objects().await?;
506        // The object the walk read has to be one the listing names, under that
507        // name. Otherwise this cleaner and the store disagree about what the
508        // objects are called — and `prune` keeps `high_summary` by its name.
509        if !listing.objects.iter().any(|(segid, _)| *segid == high_summary) {
510            return Err(Error::new(
511                ErrorKind::InvalidData,
512                format!(
513                    "the listing has no object named {}, the summary just read; \
514                     refusing to judge what is referenced",
515                    high_summary,
516                ),
517            ));
518        }
519        Ok(ContainerView {
520            low,
521            high_cno,
522            stored: raw_inode,
523            walked_stored,
524            walked: ss_inode,
525            compaction,
526            latest_compacted,
527            fmt,
528            high_summary,
529            data_block_size,
530            meta_block_size,
531            live,
532            listing,
533        })
534    }
535
536    /// Inner shared implementation used by both `collect` and
537    /// `prune`. Returns `(referenced, unreferenced)` lists of segment
538    /// *objects* where:
539    ///  - `referenced` is every object the latest published inode's metadata
540    ///    tree still points into, whether or not it falls in `[low, high]`.
541    ///  - `unreferenced` is every object that exists under the container's
542    ///    prefix whose checkpoint number falls in `[low, high]` and which
543    ///    nothing points into, less the two kinds this keeps regardless (see
544    ///    [`partition_objects`]).
545    async fn collect_unref_seg(
546        &self,
547        low: Cno,
548        high: Cno,
549    ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
550        self.collect_within(low, high, std::time::Duration::ZERO, 1).await
551    }
552
553    /// [`Self::collect_unref_seg`], keeping what a reader may still read within
554    /// `grace`: everything a version current at any time in the last `grace`
555    /// points into, and every object written in it. See [`PruneOptions`].
556    async fn collect_within(
557        &self,
558        low: Cno,
559        high: Cno,
560        grace: std::time::Duration,
561        attempts: usize,
562    ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
563        // A compaction attached while this judged would have its copies, old
564        // enough and named by nothing this read, taken for unreferenced. It
565        // checks they are younger than its `max_age` by the store's clock before
566        // attaching; this takes the store's time below, after reading the
567        // inode. So the inode is read again once the time is taken, and the
568        // whole judged again if a compaction appeared: then what this keeps is
569        // as of a time after its own, and copies younger than its grace stay.
570        let attempts = attempts.max(1);
571        for _ in 0..attempts {
572            let (judged, attached_before) = self.collect_within_once(low, high, grace).await?;
573            if grace.is_zero() {
574                return Ok(judged);
575            }
576            let (_, state) = self.load_raw_inode().await?;
577            let attached_now = state.map(|s| s.compaction).unwrap_or_default();
578            if attached_now == attached_before {
579                return Ok(judged);
580            }
581            debug!("prune: a compaction was attached while judging; judging again");
582        }
583        Err(Error::new(ErrorKind::ResourceBusy, format!(
584            "compactions were attached while prune judged, {} times; try again", attempts)))
585    }
586
587    /// One judgement of [`Self::collect_within`], with the compaction the stored
588    /// inode had when it was read.
589    async fn collect_within_once(
590        &self,
591        low: Cno,
592        high: Cno,
593        grace: std::time::Duration,
594    ) -> Result<((Vec<SegmentId>, Vec<SegmentId>), StoredCompaction)> {
595        let view = self.view(low, high).await?;
596        let attached_before = view.compaction.clone();
597        if !grace.is_zero() {
598            let hook = self.pause_after_view.lock().unwrap().clone();
599            if let Some(hook) = hook {
600                hook().await;
601            }
602        }
603        // What the newest version reads through is never reclaimable, whatever
604        // `high` says.
605        let mut roots = Vec::new();
606        if !view.walked_stored {
607            roots.push(view.stored);
608        }
609        // Nor what a compaction attached to it reads through: the writer's next
610        // publish of data takes its copies in, whatever the grace.
611        if let Some(root) = view.attached_root()? {
612            roots.push(root);
613        }
614        let mut young = BTreeSet::new();
615        if !grace.is_zero() {
616            // The store's clock, not this host's: what is compared with it is the
617            // store's own times.
618            let (now, _) = self.staging.load_segment_timestamp(SegmentId::new_from_cno(view.high_cno)).await?;
619            let cutoff = now.saturating_sub(grace.as_secs().min(i64::MAX as u64) as i64);
620            young = view.listing.modified.iter().filter(|(_, t)| **t >= cutoff).map(|(s, _)| *s).collect();
621            let versions = self.versions_since(&view, cutoff).await?;
622            // Each version's summary is kept with what it points into: it is all
623            // that says when the version became current, and without the one the
624            // window opens at, the next prune opens it at an older version whose
625            // objects this one took.
626            young.extend(versions.iter().map(|(id, _)| *id));
627            roots.extend(versions.into_iter().map(|(_, v)| v));
628        }
629        debug!("prune roots: {:?}", roots.iter().map(|r| (r.i_last_cno, r.fingerprint())).collect::<Vec<_>>());
630        let more = match self.walk_more(&view, roots.clone()).await {
631            Ok(m) => m,
632            Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
633                let attached = view.attached_root().ok().flatten().map(|r| r.i_bmap);
634                for r in &roots {
635                    if let Err(e2) = self.walk_more(&view, vec![*r]).await {
636                        error!("prune: root of checkpoint {} (fingerprint {:#x}, {}) reaches a deleted object: {}", r.i_last_cno,
637                            r.fingerprint(), if Some(r.i_bmap) == attached { "the attached compaction" } else { "a version" }, e2);
638                    }
639                }
640                return Err(e);
641            },
642            Err(e) => return Err(e),
643        };
644        let mut referenced = view.referenced_objects();
645        referenced.extend(more.iter().map(|p| view.object_of(p)));
646        let (v_ref, mut unref) = partition_objects(
647            &view.object_ids(),
648            &referenced,
649            view.low,
650            view.high_cno,
651            view.high_summary,
652        );
653        unref.retain(|o| !young.contains(o));
654        Ok(((v_ref, unref), attached_before))
655    }
656
657    /// The inodes of every version current at some time since `cutoff`: each
658    /// published since, and the one current at `cutoff`.
659    ///
660    /// A checkpoint is its summary object, and its inode is in that object's
661    /// header; a version's time is when that object was written. A compaction
662    /// attached to the stored inode is not a version: no reader opens it until
663    /// the writer has taken it in and published.
664    async fn versions_since(&self, view: &ContainerView, cutoff: i64) -> Result<Vec<(SegmentId, InodeRaw)>> {
665        let stream = view.fmt.is_stream();
666        let modified = |id: &SegmentId| view.listing.modified.get(id).copied();
667        let summaries: Vec<(SegmentId, i64)> = view.listing.objects.iter()
668            .map(|(id, _)| *id)
669            .filter(|id| *id == summary_obj(id.as_cno(), &view.fmt))
670            .filter_map(|id| modified(&id).map(|t| (id, t)))
671            .collect();
672        // From the newest checkpoint written before the window: the version
673        // current when it opened is that one or a compaction of it.
674        let from = summaries.iter().rposition(|(_, t)| *t < cutoff).unwrap_or(0);
675        let mut versions: Vec<(i64, SegmentId, InodeRaw)> = Vec::new();
676        for (id, t) in &summaries[from..] {
677            match self.staging.load_segment_header(*id, stream).await {
678                Ok(hdr) => versions.push((*t, *id, hdr.s_inode)),
679                // Gone since the listing, or never a checkpoint: nothing to keep.
680                Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
681                    debug!("prune: {} has no readable summary ({}); not a version to keep", id, e);
682                },
683                Err(e) => return Err(e),
684            }
685        }
686        debug!("prune window from {}: versions {:?}", cutoff, versions.iter().map(|(t, _, v)| (v.i_last_cno, *t)).collect::<Vec<_>>());
687        // The window: every version from the last one written before it.
688        let opened = versions.iter().filter(|(t, _, _)| *t < cutoff).map(|(t, _, _)| *t).max();
689        Ok(versions.into_iter()
690            .filter(|(t, _, _)| opened.is_none_or(|o| *t >= o))
691            .map(|(_, id, v)| (id, v))
692            .collect())
693    }
694
695    /// `prune`, keeping what readers may still be reading; see [`PruneOptions`].
696    /// Returns the objects deleted, or with `dry_run` the objects it would delete.
697    pub async fn prune_with(&self, low: Cno, high: Cno, opts: &PruneOptions) -> Result<Vec<SegmentId>> {
698        let (_, unref) = self.collect_within(low, high, opts.grace, opts.judge_attempts).await?;
699        if opts.dry_run {
700            return Ok(unref);
701        }
702        let delete_keys = unref.iter()
703            .map(|segid| format!("{}/{}", self.root_path, Segment::segid_to_staging_file_id(*segid)))
704            .collect::<Vec<String>>();
705        debug!("unreferenced segments to delete: {:?}", delete_keys);
706        Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await?;
707        Ok(unref)
708    }
709
710    /// Every object the map of `root` points into, read whole.
711    pub(crate) async fn reachable_objects(&self, view: &ContainerView, root: InodeRaw) -> Result<BTreeSet<SegmentId>> {
712        let loader = S3BlockLoader::new(
713            &self.client, &self.bucket, &self.root_path,
714            Arc::new(ReadTiming::default()),
715        );
716        let meta_block_size = view.meta_block_size;
717        let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
718            walk_roots(&loader, meta_block_size, &[root], BTreeSet::new())
719        });
720        let ptrs = match join.await {
721            Ok(inner) => inner?,
722            Err(join_err) => return Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
723        };
724        Ok(ptrs.iter().map(|p| view.object_of(p)).collect())
725    }
726
727    /// Every location the maps of `roots` reach that `view` did not: the nodes
728    /// under a pointer `view` already walked are the same nodes, since an object
729    /// is never changed once written, so only what differs is read.
730    async fn walk_more(&self, view: &ContainerView, roots: Vec<InodeRaw>) -> Result<BTreeSet<BlockPtr>> {
731        let roots: Vec<InodeRaw> = roots.into_iter()
732            .filter(|r| r.i_bmap != view.walked_root().i_bmap)
733            .collect();
734        if roots.is_empty() {
735            return Ok(BTreeSet::new());
736        }
737        let loader = S3BlockLoader::new(
738            &self.client, &self.bucket, &self.root_path,
739            Arc::new(ReadTiming::default()),
740        );
741        let known = view.live.meta.clone();
742        let meta_block_size = view.meta_block_size;
743        let join = tokio::task::spawn_blocking(move || -> Result<BTreeSet<BlockPtr>> {
744            walk_roots(&loader, meta_block_size, &roots, known)
745        });
746        match join.await {
747            Ok(inner) => inner,
748            Err(join_err) => Err(Error::other(format!("bmap walk task failed to join: {}", join_err))),
749        }
750    }
751}
752
753/// The nodes of the map of `root`, by pointer: read a level at a time, each
754/// level at the loader's concurrency, as [`walk_roots`] reads them.
755fn prefetch_nodes(loader: &S3BlockLoader, meta_block_size: usize, root: &InodeRaw)
756    -> Result<std::collections::HashMap<BlockPtr, Vec<u8>>>
757{
758    use btree_ondisk::node::{BtreeNode, BTREE_NODE_LEVEL_MIN};
759    let handle = tokio::runtime::Handle::current();
760    let mut nodes = std::collections::HashMap::new();
761    let top = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
762    if !top.is_large() || top.get_level() == BTREE_NODE_LEVEL_MIN {
763        return Ok(nodes);
764    }
765    let ud = top.get_userdata();
766    let mut frontier: Vec<BlockPtr> = (0..top.get_nchild()).map(|i| *top.get_val::<BlockPtr>(i))
767        .filter(BlockPtrFormat::is_on_staging).collect();
768    while !frontier.is_empty() {
769        let level: Vec<BlockPtr> = std::mem::take(&mut frontier);
770        let mut ask: Vec<BlockPtr> = level.iter().copied().filter(|p| !nodes.contains_key(p)).collect();
771        ask.sort_unstable();
772        ask.dedup();
773        let mut bufs: Vec<Vec<u8>> = vec![vec![0u8; meta_block_size]; ask.len()];
774        let extra = handle.block_on(loader.read_batch(&ask, &mut bufs, ud))?;
775        // What the loader hands back besides is kept for when the walk asks for
776        // it, and is not walked: it is any node of an object the walk read that
777        // some node seen anywhere named, superseded ones among them, whose
778        // children may be in objects a prune has taken.
779        for (p, b) in ask.into_iter().zip(bufs).chain(extra) {
780            nodes.entry(p).or_insert(b);
781        }
782        for p in level {
783            let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&nodes[&p])?;
784            if node.get_level() > BTREE_NODE_LEVEL_MIN {
785                frontier.extend((0..node.get_nchild()).map(|i| *node.get_val::<BlockPtr>(i))
786                    .filter(BlockPtrFormat::is_on_staging));
787            }
788        }
789    }
790    Ok(nodes)
791}
792
793/// Nodes read ahead, answered to the map that asks; nothing kept besides.
794#[derive(Clone)]
795pub(crate) struct Prefetched(Arc<std::collections::HashMap<BlockPtr, Vec<u8>>>);
796
797impl btree_ondisk::NodeCache<BlockPtr> for Prefetched {
798    fn push(&self, _: &BlockPtr, _: &[u8]) {}
799    async fn load(&self, p: BlockPtr, data: &mut [u8]) -> Result<bool> {
800        match self.0.get(&p) {
801            Some(b) => { data.copy_from_slice(b); Ok(true) },
802            None => Ok(false),
803        }
804    }
805    fn invalid(&self, _: &BlockPtr) {}
806    fn evict(&self) {}
807    fn get_stats(&self) -> btree_ondisk::NodeTieredCacheStats { btree_ondisk::NodeTieredCacheStats::default() }
808    fn shutdown(&self) {}
809    async fn reset(&self) -> Result<()> { Ok(()) }
810}
811
812/// Every location on staging reachable from the maps of `roots`, less the
813/// subtrees under node pointers in `known`. Driven on the calling thread, as
814/// [`S3Cleaner::walk_live_ptrs`] is.
815fn walk_roots(loader: &S3BlockLoader, meta_block_size: usize, roots: &[InodeRaw], mut known: BTreeSet<BlockPtr>)
816    -> Result<BTreeSet<BlockPtr>>
817{
818    use btree_ondisk::node::{BtreeNode, DirectNode, BTREE_NODE_LEVEL_MIN};
819    let handle = tokio::runtime::Handle::current();
820    let mut found = BTreeSet::new();
821    for root in roots {
822        let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&root.i_bmap)?;
823        let ud = node.get_userdata();
824        // Child node pointers to read, level by level.
825        let mut frontier: Vec<BlockPtr> = Vec::new();
826        if !node.is_large() {
827            let direct = DirectNode::<BlockPtr>::from_slice_ref(&root.i_bmap)?;
828            for i in 0..direct.get_capacity() {
829                found.insert(*direct.get_val(i));
830            }
831        } else {
832            let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
833            for i in 0..node.get_nchild() {
834                let v = *node.get_val::<BlockPtr>(i);
835                if leaf {
836                    found.insert(v);
837                } else if known.insert(v) {
838                    found.insert(v);
839                    frontier.push(v);
840                }
841            }
842        }
843        let mut side: std::collections::HashMap<BlockPtr, Vec<u8>> = std::collections::HashMap::new();
844        while !frontier.is_empty() {
845            let mut bufs: Vec<Vec<u8>> = Vec::with_capacity(frontier.len());
846            let mut ask: Vec<BlockPtr> = Vec::new();
847            let mut have: Vec<(BlockPtr, Vec<u8>)> = Vec::new();
848            for p in frontier.drain(..) {
849                match side.remove(&p) {
850                    Some(b) => have.push((p, b)),
851                    None => { ask.push(p); bufs.push(vec![0u8; meta_block_size]); },
852                }
853            }
854            if !ask.is_empty() {
855                for (p, b) in handle.block_on(loader.read_batch(&ask, &mut bufs, ud))? {
856                    side.insert(p, b);
857                }
858                have.extend(ask.into_iter().zip(bufs));
859            }
860            for (_, bytes) in have {
861                let node = BtreeNode::<BlockIndex, BlockPtr, BlockPtr>::from_slice_ref(&bytes)?;
862                let leaf = node.get_level() == BTREE_NODE_LEVEL_MIN;
863                for i in 0..node.get_nchild() {
864                    let v = *node.get_val::<BlockPtr>(i);
865                    if leaf {
866                        found.insert(v);
867                    } else if known.insert(v) {
868                        found.insert(v);
869                        frontier.push(v);
870                    }
871                }
872            }
873        }
874    }
875    found.retain(BlockPtrFormat::is_on_staging);
876    Ok(found)
877}
878
879/// How [`S3Cleaner::prune_with`] decides what nothing reads any more.
880///
881/// [`Cleaner::prune`] takes everything the newest version does not point into,
882/// less what a compaction attached to it points into (and refuses, deleting
883/// nothing, where the inode says one is attached and its metadata does not
884/// read). A reader that opened an older version, or a plan made under one and
885/// fetched outside the handle, reads objects the newest version no longer points
886/// at, and a compaction beside the writer writes copies nothing points at until
887/// it attaches them. `grace` keeps both:
888///
889/// - every object that a version current at any time in the last `grace` points
890///   into: each checkpoint published in it, and the version current when it
891///   began;
892/// - every object written in the last `grace`.
893///
894/// So `grace` has to be longer than any reader holds a version, and a
895/// compaction's `max_age` shorter than `grace`. Times are the store's. Nothing
896/// above the newest published number is taken either way: the writer's next
897/// checkpoint is being written there.
898#[derive(Clone, Debug)]
899pub struct PruneOptions {
900    /// How long a version is kept after it stops being the newest, and an object
901    /// after it is written. Zero is [`Cleaner::prune`].
902    pub grace: std::time::Duration,
903    /// Decide and report, delete nothing.
904    pub dry_run: bool,
905    /// How many times the whole is judged when a compaction keeps being attached
906    /// while it judges, before giving up with `ResourceBusy`, nothing deleted.
907    /// Three by default; zero is taken as one.
908    pub judge_attempts: usize,
909}
910
911impl Default for PruneOptions {
912    fn default() -> Self {
913        Self { grace: std::time::Duration::ZERO, dry_run: false, judge_attempts: 3 }
914    }
915}
916
917/// Every live location of a container, and the metadata-node subset of it.
918pub(crate) struct LivePtrs {
919    pub(crate) all: BTreeSet<BlockPtr>,
920    pub(crate) meta: BTreeSet<BlockPtr>,
921    /// `(first, count)` ranges of block indices that together cover every
922    /// mapped block, ascending. They may also cover holes; they skip the large
923    /// ones.
924    pub(crate) windows: Vec<(BlockIndex, usize)>,
925    /// Each index node's pointer to a block under it on storage, by key: see
926    /// [`S3Cleaner::walk_node_keys`].
927    pub(crate) node_keys: BTreeMap<BlockPtr, (BlockIndex, BlockPtr)>,
928}
929
930/// The granularity of [`LivePtrs::windows`]: a mapped block starts a window this
931/// long, and windows that touch are merged up to four of these.
932pub(crate) const DATA_WINDOW_BLOCKS: usize = 64 * 1024;
933
934/// What a listing of the container's prefix found.
935#[derive(Default)]
936pub(crate) struct ObjectListing {
937    /// Segment objects and their sizes, ascending.
938    pub(crate) objects: Vec<(SegmentId, u64)>,
939    /// When each was written, in seconds since the epoch, as the store reports.
940    pub(crate) modified: std::collections::BTreeMap<SegmentId, i64>,
941    /// How many keys under the prefix were neither the inode nor a segment
942    /// object. A WAL root nested under the container is the usual reason.
943    pub(crate) foreign: usize,
944    pub(crate) foreign_sample: Option<String>,
945}
946
947/// One pass over a container's storage, shared by every operation.
948pub(crate) struct ContainerView {
949    pub(crate) low: Cno,
950    pub(crate) high_cno: Cno,
951    /// The inode as stored: the newest version, which readers open.
952    pub(crate) stored: InodeRaw,
953    /// Whether `live` is the stored inode's map. Not when an older `high` was
954    /// asked for, whose own map was walked instead.
955    pub(crate) walked_stored: bool,
956    /// The inode whose map was walked when it is not the stored one.
957    pub(crate) walked: InodeRaw,
958    /// What the stored inode object's metadata says of an attached compaction.
959    pub(crate) compaction: StoredCompaction,
960    /// Whether the published inode marks its checkpoint as a compaction
961    /// (`InodeRaw::FLAG_COMPACTED`): it moved blocks and changed no content.
962    pub(crate) latest_compacted: bool,
963    pub(crate) fmt: BlockPtrFormat,
964    pub(crate) high_summary: SegmentId,
965    pub(crate) data_block_size: usize,
966    pub(crate) meta_block_size: usize,
967    pub(crate) live: LivePtrs,
968    pub(crate) listing: ObjectListing,
969}
970
971impl ContainerView {
972    /// The inode whose map `live` is.
973    /// The map of the compaction attached to the stored inode, as an inode to
974    /// walk, or `None` where none is. The attached-compaction bit without
975    /// metadata that reads is refused rather than guessed at: what the
976    /// compaction's copies are cannot then be known, and they may be all that
977    /// the writer's next publish reads through.
978    pub(crate) fn attached_root(&self) -> Result<Option<InodeRaw>> {
979        let root = |p: &PendingCompaction| {
980            let mut r = self.stored;
981            r.i_bmap = p.root;
982            r
983        };
984        match &self.compaction {
985            StoredCompaction::Pending(p) => Ok(Some(root(p))),
986            StoredCompaction::Unreadable(why) => Err(Error::new(ErrorKind::InvalidData, format!(
987                "the inode object's compaction metadata does not read ({}); refusing to judge what \
988                 an attached compaction reads through", why))),
989            StoredCompaction::None if self.stored.is_compaction_pending() => Err(Error::new(ErrorKind::InvalidData,
990                "the inode says a compaction is attached and its object has no compaction metadata; \
991                 refusing to judge what that compaction reads through")),
992            StoredCompaction::None => Ok(None),
993        }
994    }
995
996    pub(crate) fn walked_root(&self) -> &InodeRaw {
997        if self.walked_stored { &self.stored } else { &self.walked }
998    }
999
1000    pub(crate) fn object_ids(&self) -> Vec<SegmentId> {
1001        self.listing.objects.iter().map(|(segid, _)| *segid).collect()
1002    }
1003
1004    /// The objects at least one live location names.
1005    pub(crate) fn referenced_objects(&self) -> BTreeSet<SegmentId> {
1006        self.live.all.iter()
1007            .map(|p| BlockPtrFormat::decode(p, &self.fmt).0)
1008            .collect()
1009    }
1010
1011    /// Which object a live location is in.
1012    pub(crate) fn object_of(&self, blkptr: &BlockPtr) -> SegmentId {
1013        BlockPtrFormat::decode(blkptr, &self.fmt).0
1014    }
1015}
1016
1017/// `root_uri` without one trailing `/`, unless that `/` is part of the scheme.
1018///
1019/// Stripping it unconditionally turned `s3://` into `s3:/`, which the parse then
1020/// refused for not starting with `s3://` — the opposite of what was wrong with it.
1021/// `hyperfile 0.10.3` fixed the same thing in `StagingConfig::new_s3_uri`.
1022fn trim_root_uri(root_uri: &str) -> &str {
1023    match root_uri.strip_suffix('/') {
1024        Some(r) if !r.ends_with(":/") => r,
1025        _ => root_uri,
1026    }
1027}
1028
1029/// `S_IFMT` and the two device types, as the inode stores its mode. POSIX fixes
1030/// these values, so they are the same on every host.
1031const S_IFMT: u32 = 0o170000;
1032const S_IFCHR: u32 = 0o020000;
1033const S_IFBLK: u32 = 0o060000;
1034
1035/// Refuse an inode whose checkpoint fields do not hold checkpoint numbers.
1036///
1037/// An inline file keeps its data in the inode's tail, over `i_last_seq`,
1038/// `i_last_cno` and the bmap root; a device node keeps its `rdev` in
1039/// `i_last_cno`. Read as a checkpoint number either is whatever the bytes
1040/// happen to be. Nothing would be deleted on the strength of it — the summary
1041/// it named would not be found — but the error would point at a missing segment
1042/// rather than at what is actually wrong.
1043fn refuse_unsegmented(raw: &InodeRaw) -> Result<()> {
1044    let fmt = raw.i_mode & S_IFMT;
1045    let what = if raw.is_inline() {
1046        Some("an inline file, whose data lives in the inode")
1047    } else if fmt == S_IFCHR || fmt == S_IFBLK {
1048        Some("a device node, which stores rdev where a checkpoint number would be")
1049    } else {
1050        None
1051    };
1052    match what {
1053        Some(what) => Err(Error::new(
1054            ErrorKind::InvalidInput,
1055            format!("this container is {}: it has no segments to collect, prune or compact", what),
1056        )),
1057        None => Ok(()),
1058    }
1059}
1060
1061/// The pointer format the container was written with, as its inode records it.
1062///
1063/// A container written before `i_meta_config` was populated carries zero there;
1064/// it predates every format with parts, so its pointers read as `MicroGroup`.
1065/// That is the only case read on a guess.
1066///
1067/// Anything else that does not decode is refused. Up to 0.10.5 every such value
1068/// fell back to `MicroGroup`, and on a `StreamSegment` container — format byte 4,
1069/// new in `hyperfile 0.11.0` — that made a 0.10.5 cleaner decode no pointer into
1070/// any of its `<cno>.<part>` objects and report every one of them unreferenced,
1071/// the newest checkpoint included. Measured: a container of two checkpoints in
1072/// twelve objects came back `referenced=0`, all twelve offered to `prune`. A
1073/// format this build does not know is a reason to stop, not to guess.
1074fn container_ptr_format(raw_inode: &InodeRaw) -> Result<BlockPtrFormat> {
1075    if raw_inode.i_meta_config == 0 {
1076        return Ok(BlockPtrFormat::MicroGroup);
1077    }
1078    HyperFileMetaConfig::try_from_u32(raw_inode.i_meta_config)
1079        .map(|cfg| cfg.block_ptr_format)
1080        .map_err(|e| Error::new(
1081            ErrorKind::Unsupported,
1082            format!(
1083                "the container's inode records a format this build cannot read \
1084                 (meta config {:#x}: {}); a cleaner built against an older hyperfile \
1085                 must not walk it, since it would misread every pointer",
1086                raw_inode.i_meta_config, e,
1087            ),
1088        ))
1089}
1090
1091/// The object holding a checkpoint's summary, metadata blocks and inode.
1092fn summary_obj(cno: Cno, fmt: &BlockPtrFormat) -> SegmentId {
1093    let segid = SegmentId::new_from_cno(cno);
1094    if fmt.is_parted() {
1095        segid.at_part(Segment::SUMMARY_PART)
1096    } else {
1097        segid
1098    }
1099}
1100
1101/// A segment object name, or `None` for a key that is not one.
1102///
1103/// The names are what [`Segment::segid_to_staging_file_id`] produces: ten digits
1104/// zero-padded, optionally `.<part>`. `None` and `Some(0)` are different names
1105/// on purpose upstream, so they stay different objects here.
1106fn parse_segment_object_name(name: &str) -> Option<SegmentId> {
1107    // Nested prefixes — a WAL root under the container, say — are not segment
1108    // objects of this container.
1109    if name.contains('/') {
1110        return None;
1111    }
1112    let (seq_str, part_str) = match name.split_once('.') {
1113        Some((seq, part)) => (seq, Some(part)),
1114        None => (name, None),
1115    };
1116    if seq_str.len() != 10 || !seq_str.bytes().all(|b| b.is_ascii_digit()) {
1117        return None;
1118    }
1119    // Ten digits can name more than a `u32` holds; such an object cannot have
1120    // been written by this format, so it is not one of ours.
1121    let seq_id = seq_str.parse::<u32>().ok()?;
1122    match part_str {
1123        None => Some(SegmentId::new(seq_id)),
1124        Some(p) => {
1125            if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
1126                return None;
1127            }
1128            Some(SegmentId::with_part(seq_id, p.parse::<u16>().ok()?))
1129        },
1130    }
1131}
1132
1133/// Split what exists into what is still pointed into and what can go.
1134///
1135/// `referenced` is object-granular, which is what makes a parted container
1136/// reclaimable at all. One object is kept even when no pointer names it:
1137///
1138/// - **The summary of `high`.** It is the object this cleaner just read to find
1139///   the checkpoint's bmap, and the one it would read on the next run. A
1140///   container whose newest checkpoint holds no live block — an empty file, or
1141///   one whose every block was superseded within the same checkpoint — would
1142///   otherwise have its own head deleted, and the next `collect` would fail with
1143///   `NoSuchKey`.
1144///
1145/// A checkpoint's part 0 nothing points into goes even while another part of it
1146/// is live. A block is read through its pointer, which names its part, and no
1147/// reader of a version prune keeps opens an older checkpoint's summary: the
1148/// newest is the one above, and those of the versions in a grace window are kept
1149/// by [`S3Cleaner::prune_with`]. What it would keep is `open_cno` of that
1150/// checkpoint, which a prune breaks anyway by taking objects only it named.
1151/// Keeping it cost up to one object per checkpoint with cold data elsewhere.
1152///
1153/// Everything else in `[low, high]` that nothing points into is reclaimable,
1154/// including the partials of a checkpoint that was abandoned — those share their
1155/// checkpoint number with the retry that replaced them, so they are invisible to
1156/// anything reasoning in whole checkpoints.
1157fn partition_objects(
1158    existing: &[SegmentId],
1159    referenced: &BTreeSet<SegmentId>,
1160    low: Cno,
1161    high: Cno,
1162    high_summary: SegmentId,
1163) -> (Vec<SegmentId>, Vec<SegmentId>) {
1164    let mut unref = Vec::new();
1165    for obj in existing {
1166        let cno = obj.as_cno();
1167        if cno < low || cno > high {
1168            continue;
1169        }
1170        if referenced.contains(obj) {
1171            continue;
1172        }
1173        if *obj == high_summary {
1174            continue;
1175        }
1176        unref.push(*obj);
1177    }
1178    let v_ref = referenced.iter().copied().collect::<Vec<SegmentId>>();
1179    (v_ref, unref)
1180}
1181
1182/// Reject a checkpoint range that cannot be walked.
1183///
1184/// `[low, high]` is inclusive at both ends, so `low == high_cno` is a
1185/// well-formed query — "what does checkpoint N reference, and is anything in
1186/// `[N, N]` unreferenced" — and is answered normally. It is reached whenever a
1187/// caller asks about the entire history of a file with a single checkpoint:
1188/// `collect(1, 0)`, the form this crate's own documentation gives as the typical
1189/// call, resolves `high` to `get_last_cno() == 1` and so lands on `low == high`.
1190/// Rejecting it made `collect` and `prune` unusable on any freshly created file
1191/// until it had been flushed at least twice.
1192///
1193/// `low > high_cno` is genuinely empty and stays an error, which also covers
1194/// `high_cno == 0` (no checkpoint has ever been published, so there is no
1195/// metadata tree to walk).
1196///
1197/// A checkpoint number past `u32::MAX` is refused rather than truncated: that is
1198/// what a block pointer can name, so no object could carry the number, and
1199/// `SegmentId::new_from_cno` would assert on it in a debug build.
1200fn validate_segid_range(low: Cno, high_cno: Cno) -> Result<()> {
1201    if low > high_cno {
1202        return Err(Error::new(
1203            ErrorKind::InvalidInput,
1204            format!("invalid segment range [{}, {}]", low, high_cno),
1205        ));
1206    }
1207    if high_cno > u32::MAX as Cno {
1208        return Err(Error::new(
1209            ErrorKind::InvalidInput,
1210            format!("checkpoint {} is past what a block pointer can name ({})",
1211                high_cno, u32::MAX),
1212        ));
1213    }
1214    Ok(())
1215}
1216
1217impl Cleaner for S3Cleaner {
1218    async fn collect(
1219        &self,
1220        low: Cno,
1221        high: Cno,
1222    ) -> Result<(Vec<SegmentId>, Vec<SegmentId>)> {
1223        self.collect_unref_seg(low, high).await
1224    }
1225
1226    /// Prune unreferenced segment objects in `[low, high]`. Implemented
1227    /// as `collect` followed by `DeleteObjects` of the
1228    /// unreferenced list.
1229    async fn prune(&self, low: Cno, high: Cno) -> Result<()> {
1230        let (_, non_ref) = self.collect_unref_seg(low, high).await?;
1231        let delete_keys = non_ref.iter()
1232            .map(|segid| format!(
1233                "{}/{}",
1234                self.root_path,
1235                Segment::segid_to_staging_file_id(*segid),
1236            ))
1237            .collect::<Vec<String>>();
1238        debug!("unreferenced segments to delete: {:?}", delete_keys);
1239        Self::do_delete_objects(&self.client, &self.bucket, delete_keys).await
1240    }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use super::*;
1246
1247    /// Builder calls in `do_delete_objects` panic only on empty
1248    /// inputs that we guard against. Verify the empty-input fast
1249    /// path.
1250    #[tokio::test]
1251    async fn delete_empty_keys_is_noop() {
1252        let cfg = aws_config::load_from_env().await;
1253        let client = Client::new(&cfg);
1254        // Empty list -> no SDK call -> Ok regardless of credentials.
1255        let r = S3Cleaner::do_delete_objects(&client, "any-bucket", Vec::new()).await;
1256        assert!(r.is_ok(), "empty key list should not call S3");
1257    }
1258
1259    /// `[low, high]` is inclusive at both ends, so a single-checkpoint
1260    /// file -- where `collect(1, 0)` resolves to `low == high == 1` --
1261    /// must be accepted. It used to be rejected, which made the
1262    /// documented call form fail on any file flushed only once.
1263    #[test]
1264    fn segid_range_accepts_a_single_checkpoint() {
1265        assert!(validate_segid_range(1, 1).is_ok());
1266    }
1267
1268    #[test]
1269    fn segid_range_accepts_a_normal_span() {
1270        assert!(validate_segid_range(1, 5).is_ok());
1271    }
1272
1273    /// Only a genuinely empty range is an error. `high_segid == 0` is the
1274    /// "no checkpoint published yet" case and falls out of the same rule.
1275    #[test]
1276    fn segid_range_rejects_an_empty_span() {
1277        for (low, high) in [(5u64, 3u64), (2, 1), (1, 0)] {
1278            let e = validate_segid_range(low, high)
1279                .expect_err("low > high must be rejected");
1280            assert_eq!(e.kind(), ErrorKind::InvalidInput);
1281            assert!(
1282                e.to_string().contains(&format!("[{}, {}]", low, high)),
1283                "error should name the range, got {:?}", e.to_string(),
1284            );
1285        }
1286    }
1287
1288    #[test]
1289    fn a_trailing_slash_is_trimmed_but_not_the_schemes() {
1290        assert_eq!(trim_root_uri("s3://b/k/"), "s3://b/k");
1291        assert_eq!(trim_root_uri("s3://b/k"), "s3://b/k");
1292        assert_eq!(trim_root_uri("s3://"), "s3://");
1293        assert_eq!(trim_root_uri("S3://"), "S3://");
1294        assert_eq!(trim_root_uri(""), "");
1295    }
1296
1297    /// Only a zero meta config is read on a guess; a value that does not decode is
1298    /// refused rather than read as `MicroGroup`, which is how a 0.10.5 cleaner
1299    /// misread every pointer of a `StreamSegment` container.
1300    #[test]
1301    fn an_unknown_format_is_refused_not_guessed() {
1302        let legacy = InodeRaw { i_meta_config: 0, ..Default::default() };
1303        assert_eq!(container_ptr_format(&legacy).unwrap(), BlockPtrFormat::MicroGroup);
1304
1305        for fmt in [BlockPtrFormat::MicroGroup, BlockPtrFormat::PartedSegment,
1306                    BlockPtrFormat::StreamSegment] {
1307            let cfg = HyperFileMetaConfig::new(56, 4096, 4096, fmt);
1308            let raw = InodeRaw { i_meta_config: cfg.as_u32(), ..Default::default() };
1309            assert_eq!(container_ptr_format(&raw).unwrap(), fmt);
1310        }
1311
1312        let future = HyperFileMetaConfig::new(56, 4096, 4096, BlockPtrFormat::PartedSegment)
1313            .as_u32() & !0xFF | 0x7F;
1314        let raw = InodeRaw { i_meta_config: future, ..Default::default() };
1315        let e = container_ptr_format(&raw).expect_err("an unknown format byte must be refused");
1316        assert_eq!(e.kind(), ErrorKind::Unsupported);
1317    }
1318
1319    /// An inline file's checkpoint fields hold its data, and a device node's hold
1320    /// its rdev. Neither is a checkpoint number, so the walk refuses up front
1321    /// rather than looking for a segment the bytes happen to name.
1322    #[test]
1323    fn an_inode_without_segments_is_refused() {
1324        let mut inline = InodeRaw { i_mode: 0o100644, ..Default::default() };
1325        inline.set_inline(b"hello");
1326        let e = refuse_unsegmented(&inline).expect_err("inline must be refused");
1327        assert_eq!(e.kind(), ErrorKind::InvalidInput);
1328        assert!(e.to_string().contains("inline"), "{}", e);
1329
1330        for mode in [0o020644u32, 0o060644] {
1331            let dev = InodeRaw { i_mode: mode, ..Default::default() };
1332            let e = refuse_unsegmented(&dev).expect_err("a device node must be refused");
1333            assert!(e.to_string().contains("device"), "{}", e);
1334        }
1335
1336        for mode in [0o100644u32, 0o040755, 0o120777] {
1337            let ok = InodeRaw { i_mode: mode, ..Default::default() };
1338            assert!(refuse_unsegmented(&ok).is_ok(), "mode {:o} has segments", mode);
1339        }
1340    }
1341
1342    /// A checkpoint number no pointer could name is refused rather than
1343    /// truncated into one that names a different object.
1344    #[test]
1345    fn segid_range_rejects_a_checkpoint_past_a_pointer() {
1346        let e = validate_segid_range(1, u32::MAX as Cno + 1)
1347            .expect_err("a cno past u32::MAX must be rejected");
1348        assert_eq!(e.kind(), ErrorKind::InvalidInput);
1349        assert!(validate_segid_range(1, u32::MAX as Cno).is_ok());
1350    }
1351
1352    // --- object names ---
1353
1354    #[test]
1355    fn object_names_round_trip_through_the_parser() {
1356        for segid in [
1357            SegmentId::new(1),
1358            SegmentId::new(4294967295),
1359            SegmentId::with_part(7, 0),
1360            SegmentId::with_part(7, 16383),
1361        ] {
1362            let name = Segment::segid_to_staging_file_id(segid);
1363            assert_eq!(parse_segment_object_name(&name), Some(segid),
1364                "name {:?} did not parse back", name);
1365        }
1366    }
1367
1368    /// An unsuffixed name and part 0 are different objects upstream, so they
1369    /// have to stay different here — sharing them would mean deleting the
1370    /// summary of one container shape while reporting the other.
1371    #[test]
1372    fn a_bare_name_is_not_part_zero() {
1373        assert_eq!(parse_segment_object_name("0000000007"), Some(SegmentId::new(7)));
1374        assert_eq!(parse_segment_object_name("0000000007.0"),
1375            Some(SegmentId::with_part(7, 0)));
1376    }
1377
1378    #[test]
1379    fn keys_that_are_not_segment_objects_are_skipped() {
1380        for name in [
1381            "inode",              // the inode object
1382            "wal/0000000001",     // a nested prefix, not an object of ours
1383            "0000000001/0_0_4096",
1384            "000000001",          // nine digits
1385            "00000000012",        // eleven
1386            "9999999999",         // ten digits, past what a u32 can hold
1387            "0000000001.",        // empty part
1388            "0000000001.x",
1389            "0000000001.65536",   // past what a u16 can hold
1390            "0000000001.0.1",
1391            "",
1392        ] {
1393            assert_eq!(parse_segment_object_name(name), None,
1394                "{:?} should not be read as a segment object", name);
1395        }
1396    }
1397
1398    // --- what gets reclaimed ---
1399
1400    fn partition(
1401        existing: &[SegmentId],
1402        referenced: &[SegmentId],
1403        low: Cno,
1404        high: Cno,
1405        high_summary: SegmentId,
1406    ) -> Vec<SegmentId> {
1407        let set: BTreeSet<SegmentId> = referenced.iter().copied().collect();
1408        let (_, unref) = partition_objects(existing, &set, low, high, high_summary);
1409        unref
1410    }
1411
1412    /// The unparted case, which is every container written before 0.7.0: an
1413    /// object is a checkpoint, and one nothing points into goes.
1414    #[test]
1415    fn an_unreferenced_checkpoint_is_reclaimable() {
1416        let existing = [SegmentId::new(1), SegmentId::new(2), SegmentId::new(3)];
1417        let unref = partition(&existing, &[SegmentId::new(3)], 1, 3, SegmentId::new(3));
1418        assert_eq!(unref, vec![SegmentId::new(1), SegmentId::new(2)]);
1419    }
1420
1421    /// Objects outside `[low, high]` are not candidates, which is what makes a
1422    /// prune safe against a writer publishing underneath it.
1423    #[test]
1424    fn objects_outside_the_range_are_left_alone() {
1425        let existing = [
1426            SegmentId::new(1), SegmentId::new(2), SegmentId::new(3), SegmentId::new(4),
1427        ];
1428        let unref = partition(&existing, &[], 2, 3, SegmentId::new(9));
1429        assert_eq!(unref, vec![SegmentId::new(2), SegmentId::new(3)]);
1430    }
1431
1432    /// A checkpoint whose newest state holds no live block would otherwise have
1433    /// its own head deleted, and the next `collect` would fail to read it.
1434    #[test]
1435    fn the_summary_of_high_is_kept_even_when_nothing_points_into_it() {
1436        let existing = [SegmentId::new(1), SegmentId::new(2)];
1437        let unref = partition(&existing, &[], 1, 2, SegmentId::new(2));
1438        assert_eq!(unref, vec![SegmentId::new(1)]);
1439
1440        // Same for a streamed container, where the head is part 0.
1441        let existing = [SegmentId::with_part(2, 0), SegmentId::with_part(2, 1)];
1442        let unref = partition(&existing, &[], 1, 2, SegmentId::with_part(2, 0));
1443        assert_eq!(unref, vec![SegmentId::with_part(2, 1)]);
1444    }
1445
1446    /// The partials of an abandoned checkpoint share their number with the
1447    /// retry that replaced them. Reclaiming them is the whole reason the
1448    /// referenced set is object-granular.
1449    #[test]
1450    fn an_abandoned_partial_is_reclaimable_while_its_checkpoint_lives() {
1451        let existing = [
1452            SegmentId::with_part(5, 0), // summary of the checkpoint that landed
1453            SegmentId::with_part(5, 1), // its data
1454            SegmentId::with_part(5, 2), // written, then abandoned by a rollback
1455        ];
1456        let referenced = [SegmentId::with_part(5, 0), SegmentId::with_part(5, 1)];
1457        let unref = partition(&existing, &referenced, 1, 9, SegmentId::with_part(9, 0));
1458        assert_eq!(unref, vec![SegmentId::with_part(5, 2)]);
1459    }
1460
1461    /// A part 0 nothing points into goes though another part of its checkpoint
1462    /// is live: blocks are read through their pointers, not through it.
1463    #[test]
1464    fn the_summary_part_nothing_points_into_goes_while_its_checkpoint_lives() {
1465        let existing = [SegmentId::with_part(4, 0), SegmentId::with_part(4, 3)];
1466        let unref = partition(&existing, &[SegmentId::with_part(4, 3)], 1, 9,
1467            SegmentId::with_part(9, 0));
1468        assert_eq!(unref, vec![SegmentId::with_part(4, 0)]);
1469    }
1470
1471    /// With no live part left, the summary goes too — otherwise a parted
1472    /// container would never give any storage back.
1473    #[test]
1474    fn a_wholly_dead_parted_checkpoint_goes_including_its_summary() {
1475        let existing = [
1476            SegmentId::with_part(4, 0), SegmentId::with_part(4, 1),
1477            SegmentId::with_part(6, 0),
1478        ];
1479        let unref = partition(&existing, &[SegmentId::with_part(6, 0)], 1, 9,
1480            SegmentId::with_part(6, 0));
1481        assert_eq!(unref, vec![SegmentId::with_part(4, 0), SegmentId::with_part(4, 1)]);
1482    }
1483}