Skip to main content

hyperfile_cleaner/
compact.rs

1//! Offline compaction: rewriting the live blocks of mostly-dead objects so the
2//! objects can be reclaimed, and so a read of one file range costs fewer
3//! requests.
4//!
5//! ## What `prune` cannot do
6//!
7//! [`Cleaner::prune`](crate::Cleaner::prune) reclaims an object nothing points
8//! into. An object that is 5% live is not that object: those few blocks hold the
9//! file's only copy of their contents, so the other 95% cannot be given back
10//! while they stay there. Rewriting them into a new checkpoint is what turns the
11//! old object into one `prune` can take.
12//!
13//! The same rewrite is what makes a read cheaper. A request breaks where the
14//! object changes, so blocks of one file range scattered across many objects
15//! cost one request each; written out together they cost one. Both goals use the
16//! same mechanism and differ only in what they select.
17//!
18//! ## How the rewrite happens
19//!
20//! Not by a format this crate writes. Nothing here builds a segment, assigns a
21//! pointer or publishes an inode — that is `hyperfile`'s write path, and a second
22//! implementation of it would drift from the first. What this does instead is ask
23//! `hyperfile` to rewrite blocks it already knows how to rewrite:
24//!
25//! - [`Hyper::fs_relocate`] marks a run of blocks to be rewritten at the next flush
26//!   with their current bytes. It reads them with the read path's own coalescing,
27//!   so a contiguous run costs a few large requests rather than one per block; it
28//!   skips holes, explicit zero blocks and anything already dirty, so a sparse
29//!   file stays sparse; and it touches neither `mtime`, `ctime` nor the read cache.
30//! - One `fs_flush` at the end of the pass writes the dirty set as one checkpoint.
31//!   The dirty set is keyed by block index, so the blocks land in file order and
32//!   packed — which is both halves of what compaction is for.
33//!
34//! ## A compaction is not a change of content
35//!
36//! The pass has to publish a new checkpoint — blocks moved, so pointers, the map
37//! and the inode changed — and so `last_cno` advances. A consumer that reads a new
38//! `last_cno` as "the content changed" would take every compaction for a change.
39//! `hyperfile` therefore marks a publish whose every dirty block came from
40//! relocation with `InodeRaw::FLAG_COMPACTED`, and
41//! [`Hyper::fs_content_cno`] stays where it was across it. That is the number a
42//! consumer should compare.
43//!
44//! The mark is only set when the publish's number directly follows the previous
45//! one, so it holds for exactly one checkpoint. Two passes back to back would
46//! therefore move `content_cno` on the second, and [`S3Cleaner::compact`] refuses
47//! to start on a checkpoint that is already marked unless
48//! [`CompactOptions::allow_consecutive`] says otherwise.
49//!
50//! ## Beside the writer
51//!
52//! With [`CompactOptions::beside_writer`] the pass is not a second writer:
53//! `Hyper::fs_begin_compaction` takes up the stored version, `fs_relocate`
54//! copies the blocks as below, and `fs_publish_compaction` writes the copies'
55//! map and *attaches* it to the stored inode -- its object's metadata, with one
56//! conditional write that changes nothing else. The writer takes the
57//! compaction in before its next publish of data and keeps every block it
58//! changed, so `FailFast` on the writer's side still stops only a second writer.
59//! Until then readers read through the objects as they were, and the emptied
60//! objects become reclaimable only once the writer has published. What follows
61//! is about the default.
62//!
63//! ## Why offline
64//!
65//! A compactor is a writer, and it writes *old* bytes — the content it read
66//! earlier. `hyperfile`'s default conflict policy, `RetryLastWriterWins`,
67//! refreshes from storage on a conflict and re-publishes the dirty set, which for
68//! a compactor means republishing a stale copy of a block another writer has
69//! since changed. So compaction runs with
70//! [`FlushConflictPolicy::FailFast`]
71//! and the caller must be the container's only writer. A concurrent publish is
72//! then detected — the inode carries an `If-Match` on its ETag — and the pass
73//! fails rather than losing the other writer's data.
74//!
75//! A log is the other half of that contract. This refuses to run when the
76//! container's prefix holds keys that are neither the inode nor segment objects,
77//! because a WAL is the usual reason for them and a compactor that does not read
78//! the log would publish over entries recovery has not replayed yet. Beside the
79//! writer the pass publishes nothing, so it runs whatever the prefix holds.
80
81use std::io::{Error, ErrorKind, Result};
82use std::collections::{BTreeMap, BTreeSet};
83use log::{debug, info, warn};
84use hyperfile::{BlockIndex, Cno, SegmentId};
85use hyperfile::config::{FlushConflictPolicy, HyperFileConfig, HyperFileConfigBuilder,
86    HyperFileRuntimeConfig};
87use hyperfile::file::file::CompactionAttached;
88use hyperfile::file::flags::{FileFlags, HyperFileFlags};
89use hyperfile::file::hyper::Hyper;
90use hyperfile::meta_format::BlockPtrFormat;
91use hyperfile::staging::config::StagingConfig;
92use crate::s3::{ContainerView, S3Cleaner};
93
94
95/// How much of one stored object is still pointed into.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct ObjectUsage {
98    /// The object, `<cno>` or `<cno>.<part>`.
99    pub segid: SegmentId,
100    /// Its size on storage.
101    pub bytes: u64,
102    /// Live data blocks in it.
103    pub live_data_blocks: usize,
104    /// Live metadata nodes in it.
105    pub live_meta_blocks: usize,
106    /// What those occupy, by the container's own block sizes.
107    pub live_bytes: u64,
108    /// Whether the live metadata in it is rewritten by rewriting its live data.
109    ///
110    /// True for a data part — any part above 0 — of a `StreamSegment` container.
111    /// That layout puts every leaf of the block map in the object holding the data
112    /// under it, and the nodes above the leaves in part 0 only. A leaf in a data
113    /// part is therefore live only while none of the blocks it was written with
114    /// has changed, so those blocks are live and in the same object; relocating
115    /// them dirties the leaf, and the flush writes it elsewhere with them.
116    /// Under every other format the nodes sit in part 0 or the one object, apart
117    /// from the data they describe, and this is false.
118    pub meta_moves_with_data: bool,
119    /// Live index nodes in it with no block under them in this object, each
120    /// rewritten by relocating one block under it from wherever that is: a
121    /// block's new place dirties every node above it. What freeing the object
122    /// costs beyond its own live data.
123    pub extra_blocks: usize,
124    /// Live index nodes in it with no block on storage found under them (holes,
125    /// zero blocks): nothing a compaction marks rewrites them, and the object is
126    /// not a candidate.
127    pub unfreeable_nodes: usize,
128    /// What freeing it rewrites: its live data blocks and the extra ones, and
129    /// the nodes the flush writes anew.
130    pub rewrite_bytes: u64,
131}
132
133impl ObjectUsage {
134    /// Nothing points into it: `prune` can take it, compaction has no work here.
135    pub fn is_dead(&self) -> bool {
136        self.live_data_blocks == 0 && self.live_meta_blocks == 0
137    }
138
139    /// Live bytes over stored bytes. Zero for a dead object, and the cost side
140    /// of the trade: rewriting this much frees [`Self::bytes`].
141    pub fn live_ratio(&self) -> f64 {
142        if self.bytes == 0 {
143            return 0.0;
144        }
145        self.live_bytes as f64 / self.bytes as f64
146    }
147
148    /// What freeing it rewrites over what it stores: [`Self::rewrite_bytes`]
149    /// over [`Self::bytes`]. The cost side of the trade, as the policy's
150    /// `max_live_ratio` measures it.
151    pub fn cost_ratio(&self) -> f64 {
152        if self.bytes == 0 {
153            return 0.0;
154        }
155        self.rewrite_bytes as f64 / self.bytes as f64
156    }
157
158    /// Whether a live metadata node is in it. A node is rewritten when the
159    /// flush writes something under it anew, so compaction frees such an object
160    /// by relocating its own live data and, for a node with nothing under it
161    /// here, one block under it from elsewhere ([`Self::extra_blocks`]).
162    pub fn holds_metadata(&self) -> bool {
163        self.live_meta_blocks > 0
164    }
165}
166
167/// What a container's storage is made of, and what could be given back.
168#[derive(Clone, Debug)]
169pub struct Report {
170    /// The checkpoint the walk was taken from.
171    pub high_cno: Cno,
172    /// Whether the newest published checkpoint is itself a compaction
173    /// (`InodeRaw::FLAG_COMPACTED`). `compact` will not run on top of one unless
174    /// asked to, since a second pass in a row moves `content_cno`.
175    pub latest_compacted: bool,
176    /// A compaction attached to the stored inode beside the writer and not yet
177    /// taken in, as its object's metadata has it: the version it was built on,
178    /// its parts, blocks moved and its map. `Unreadable` stops `prune`.
179    pub attached: hyperfile::compaction::StoredCompaction,
180    pub data_block_size: usize,
181    pub meta_block_size: usize,
182    /// Objects whose checkpoint falls in the queried `[low, high]`, ascending.
183    pub objects: Vec<ObjectUsage>,
184    /// Objects outside that range, which no operation here will touch.
185    pub out_of_range: usize,
186    /// Keys under the container's prefix that are neither the inode nor a segment
187    /// object. A WAL root nested under the container is the usual reason, and
188    /// compaction refuses to run while any are present.
189    pub foreign_keys: usize,
190    pub foreign_sample: Option<String>,
191}
192
193impl Report {
194    /// Bytes stored by the objects in range.
195    pub fn bytes(&self) -> u64 {
196        self.objects.iter().map(|o| o.bytes).sum()
197    }
198
199    /// Bytes still pointed into.
200    pub fn bytes_live(&self) -> u64 {
201        self.objects.iter().map(|o| o.live_bytes).sum()
202    }
203
204    /// Objects nothing points into, and what they hold. This is `prune`'s work,
205    /// and it needs no rewrite.
206    pub fn dead(&self) -> (usize, u64) {
207        let dead = self.objects.iter().filter(|o| o.is_dead());
208        (dead.clone().count(), dead.map(|o| o.bytes).sum())
209    }
210
211    /// What compaction at `max_live_ratio` would cost and free: `(objects,
212    /// bytes_to_rewrite, bytes_freed)`.
213    ///
214    /// An estimate from the same numbers [`S3Cleaner::compact`] selects by, so a
215    /// dry run and this agree. The bytes freed are the objects' own, which
216    /// `prune` collects afterwards; the rewrite itself publishes a new checkpoint
217    /// holding the live blocks.
218    pub fn compactable(&self, max_live_ratio: f64) -> (usize, u64, u64) {
219        let picked = self.objects.iter()
220            .filter(|o| is_candidate(o, max_live_ratio));
221        (
222            picked.clone().count(),
223            picked.clone().map(|o| o.rewrite_bytes).sum(),
224            picked.map(|o| o.bytes).sum(),
225        )
226    }
227}
228
229/// Which objects compaction may rewrite, and how much it may do at once.
230#[derive(Clone, Debug)]
231pub struct CompactOptions {
232    /// Rewrite an object only if at most this much of it is still live. At `1.0`
233    /// every live object is a candidate, which rewrites the whole container.
234    pub max_live_ratio: f64,
235    /// The most live bytes one pass rewrites. Objects are taken whole and
236    /// cheapest first until the next would pass this; what is left waits for the
237    /// next pass. Unlimited by default.
238    ///
239    /// On a parted container with partial segments enabled — the default for
240    /// both — this is only a size: `fs_relocate` writes the pass out as partials
241    /// once it crosses the dirty-data limits, so memory is bounded by those
242    /// limits whatever the pass. Where no partial can be written, everything the
243    /// pass relocates stays dirty until its one flush, so the pass is also capped
244    /// at [`UNBOUNDED_PASS_BYTES`]; and a container that is not parted writes a
245    /// checkpoint as one object, so its pass is capped at what one object holds.
246    pub max_pass_bytes: u64,
247    /// The runtime configuration of the handle that does the rewrite: the size of
248    /// the partials a pass is written out as (`data_cache_dirty_min_bytes_to_part`
249    /// and the dirty-data limits), `segment_buffer_size`, the read cache,
250    /// multipart uploads. Give the one the container's writer uses, and what a
251    /// compaction writes is shaped like what the writer writes.
252    ///
253    /// `None` uses [`compaction_runtime_default`]. Either way the cleaner
254    /// overrides one field, `flush_conflict_policy`, to `FailFast`: a compactor
255    /// writes bytes it read earlier, and retrying on a conflict would republish
256    /// them over another writer's newer ones.
257    pub runtime: Option<HyperFileRuntimeConfig>,
258    /// How many bytes of blocks to hand `fs_relocate` at once. It holds what it
259    /// reads in a buffer of its own before the dirty cache takes it, so this bounds
260    /// that second copy.
261    pub relocate_chunk_bytes: usize,
262    /// Select and report, write nothing. No file is opened.
263    pub dry_run: bool,
264    /// Run even though the newest checkpoint is already a compaction. The flag that
265    /// keeps `content_cno` still holds for one checkpoint only, so a second pass in
266    /// a row is seen by consumers as a change of content. Set this when that is
267    /// acceptable, for example to finish a container larger than one pass.
268    pub allow_consecutive: bool,
269    /// Run even though the prefix holds keys this crate does not recognize. Only
270    /// set this having established that they are not a WAL. Beside the writer
271    /// they are reported and never refused: that pass publishes nothing.
272    pub allow_foreign_keys: bool,
273    /// Compact beside the container's writer: attach the pass to the stored inode
274    /// rather than publish a checkpoint of its own (`Hyper::fs_begin_compaction`
275    /// and `fs_publish_compaction` in `hyperfile`). It keeps the checkpoint
276    /// number and the content checkpoint, and a writer of hyperfile 0.12 or later
277    /// takes it in before its next publish of data rather than failing as on a
278    /// second writer. Needs a container with parts (`PartedSegment`,
279    /// `StreamSegment`). `allow_consecutive` does not apply: an attached
280    /// compaction never moves `content_cno`.
281    ///
282    /// The pass fails with `ResourceBusy` while a compaction is attached and not
283    /// yet taken in, or while the writer's publish is on its way -- after
284    /// waiting up to `busy_wait` for either to end -- and with `TimedOut` past
285    /// `max_age`; either way try again later. A writer with a
286    /// write-ahead log takes it in too, with hyperfile 0.12.1 or later, its log
287    /// under the container's prefix or not.
288    pub beside_writer: bool,
289    /// Beside the writer, the longest a pass may take from its start to its
290    /// attach; past it the pass is given up. Its copies are referenced by
291    /// nothing until attached, and only a `prune` grace keeps them, so set this
292    /// below the grace of any [`S3Cleaner::prune_with`] that may run meanwhile,
293    /// less a margin. Ten minutes by default. It is measured by the store's
294    /// clock at the attach, as `prune` measures its grace.
295    pub max_age: std::time::Duration,
296    /// Beside the writer, the grace of the `prune_with` that runs beside this
297    /// pass, when known: the pass is refused (`InvalidInput`), nothing done,
298    /// unless `max_age` is below it by [`ATTACH_MARGIN`] at least. `None`, the
299    /// default, checks nothing.
300    pub prune_grace: Option<std::time::Duration>,
301    /// Beside the writer, how long to keep trying to begin while the writer's
302    /// publish is on its way -- its checkpoint on storage past the stored inode
303    /// -- or a compaction is attached and not taken in yet: the begin is tried
304    /// again every quarter of a second until this has passed, then the pass
305    /// fails with `ResourceBusy`. On a container written often, a pass has to
306    /// meet a gap between two publishes. Ten seconds by default; zero tries once.
307    pub busy_wait: std::time::Duration,
308}
309
310/// How often [`CompactOptions::busy_wait`] tries the begin again.
311const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(250);
312
313/// How far below a prune's grace `CompactOptions::max_age` must be: what the
314/// attach itself takes after its last check, and the store's whole seconds.
315/// hyperfile's own, which its compactor checks by.
316pub use hyperfile::compaction::ATTACH_MARGIN;
317
318impl Default for CompactOptions {
319    fn default() -> Self {
320        Self {
321            max_live_ratio: 0.5,
322            max_pass_bytes: u64::MAX,
323            runtime: None,
324            relocate_chunk_bytes: 64 * 1024 * 1024,
325            dry_run: false,
326            allow_consecutive: false,
327            allow_foreign_keys: false,
328            beside_writer: false,
329            max_age: std::time::Duration::from_secs(600),
330            prune_grace: None,
331            busy_wait: std::time::Duration::from_secs(10),
332        }
333    }
334}
335
336/// See [`CompactOptions::prune_grace`].
337fn check_prune_grace(opts: &CompactOptions) -> Result<()> {
338    match opts.prune_grace {
339        Some(grace) if opts.beside_writer && opts.max_age + ATTACH_MARGIN > grace => Err(Error::new(ErrorKind::InvalidInput,
340            format!("max_age {:?} is not below the prune grace {:?} by {:?}: a prune could take the copies for \
341                     unreferenced before they are attached", opts.max_age, grace, ATTACH_MARGIN))),
342        _ => Ok(()),
343    }
344}
345
346/// What a compaction pass did.
347#[derive(Clone, Debug, Default)]
348pub struct CompactOutcome {
349    /// The objects whose live blocks were rewritten, ascending.
350    pub selected: Vec<SegmentId>,
351    /// Of those, the ones a walk taken afterwards still finds referenced. Empty
352    /// on a pass that did what it set out to; anything here is an object that was
353    /// not freed, and is reported rather than assumed away.
354    pub still_referenced: Vec<SegmentId>,
355    /// Blocks `fs_relocate` marked: what was done, not what was planned. A hole,
356    /// an explicit zero block or a block already dirty is not counted.
357    pub blocks_rewritten: usize,
358    pub bytes_rewritten: u64,
359    /// The selected objects' stored bytes — what `prune` can now reclaim.
360    pub bytes_freed: u64,
361    /// Checkpoints published: one for a pass that rewrote anything, none
362    /// otherwise. That is how far `last_cno` advanced. Always none beside the
363    /// writer, whose pass keeps the number: see `attached`.
364    pub checkpoints: usize,
365    /// Beside the writer, what was attached: the version it was built on and the
366    /// one it was attached to, the parts its objects are in, blocks moved, and
367    /// how many conditional writes of the inode it took.
368    pub attached: Option<CompactionAttached>,
369    /// `fs_content_cno` before and after the pass. Equal when consumers will not
370    /// see the pass as a change of content, which is the ordinary case. They
371    /// differ when the publish could not be marked: its number did not follow the
372    /// previous one — an earlier flush failed and gave its number up — or the
373    /// newest checkpoint was already a compaction and the pass ran anyway.
374    pub content_cno_before: Cno,
375    pub content_cno_after: Cno,
376    /// Whether the candidates outlasted the pass budget. Another pass would find
377    /// more to do, at the cost of `content_cno` moving once (see
378    /// [`CompactOptions::allow_consecutive`]).
379    pub more_remaining: bool,
380    pub dry_run: bool,
381}
382
383impl CompactOutcome {
384    /// Whether a consumer comparing `content_cno` will see this pass as a change.
385    pub fn content_moved(&self) -> bool {
386        self.content_cno_before != self.content_cno_after
387    }
388}
389
390impl S3Cleaner {
391    /// What the container's storage is made of: per-object liveness for every
392    /// object whose checkpoint falls in `[low, high]`.
393    ///
394    /// Read-only, and the same walk `collect` does plus one `ListObjectsV2` for
395    /// sizes. `high == 0` means the latest published checkpoint.
396    pub async fn report(&self, low: Cno, high: Cno) -> Result<Report> {
397        let view = self.view(low, high).await?;
398        Ok(build_report(&view))
399    }
400
401    /// Rewrite the live blocks of mostly-dead objects so `prune` can reclaim
402    /// them.
403    ///
404    /// The caller must be the container's only writer for the duration; see the
405    /// [module docs](self) for why that is not a nicety. Nothing is deleted here
406    /// — a compaction makes objects reclaimable and `prune` reclaims them, which
407    /// keeps the destructive step in one place.
408    pub async fn compact(
409        &self,
410        low: Cno,
411        high: Cno,
412        opts: &CompactOptions,
413    ) -> Result<CompactOutcome> {
414        check_prune_grace(opts)?;
415        let view = self.view(low, high).await?;
416        // Beside the writer the pass publishes nothing a log could be under.
417        if view.listing.foreign > 0 && !opts.allow_foreign_keys && !opts.beside_writer {
418            return Err(Error::new(
419                ErrorKind::InvalidInput,
420                format!(
421                    "{} key(s) under the container's prefix are neither the inode nor \
422                     segment objects (for example {:?}); a WAL is the usual reason, and \
423                     compacting past a log this pass does not read would publish over \
424                     entries recovery has not replayed. Set allow_foreign_keys once you \
425                     have established otherwise",
426                    view.listing.foreign,
427                    view.listing.foreign_sample.as_deref().unwrap_or("?"),
428                ),
429            ));
430        }
431
432        if view.latest_compacted && !opts.allow_consecutive && !opts.dry_run && !opts.beside_writer {
433            return Err(Error::new(
434                ErrorKind::InvalidInput,
435                format!(
436                    "checkpoint {} is already a compaction, and the flag that keeps \
437                     content_cno still holds for one checkpoint only: a second pass in a \
438                     row would be seen by consumers as a change of content. Write to the \
439                     file first, or set allow_consecutive",
440                    view.high_cno,
441                ),
442            ));
443        }
444
445        let report = build_report(&view);
446        let mut runtime = compaction_runtime(opts.runtime.as_ref());
447        if opts.beside_writer {
448            // Not the writer: a checkpoint the writer has on storage and has not
449            // yet pointed the inode at is the writer's to publish. Taking it up
450            // here would publish it under the writer and fail its own inode write.
451            runtime.take_up_on_open = false;
452            // hyperfile checks by it too, at the attach.
453            if let Some(grace) = opts.prune_grace {
454                runtime.compaction_prune_grace_secs = Some(grace.as_secs());
455            }
456        }
457        let pass_cap = pass_cap(opts.max_pass_bytes, &view.fmt, &runtime);
458        let (selected, bytes_planned, bytes_freed, more_remaining) =
459            plan_pass(&report.objects, opts.max_live_ratio, pass_cap);
460        debug!("compact: {} object(s) selected of {} in range, {} live bytes (cap {})",
461            selected.len(), report.objects.len(), bytes_planned, pass_cap);
462
463        let mut outcome = CompactOutcome {
464            selected: selected.iter().copied().collect(),
465            bytes_freed,
466            more_remaining,
467            dry_run: opts.dry_run,
468            ..Default::default()
469        };
470        if opts.dry_run {
471            // The plan's own numbers, which is all a dry run can report: nothing
472            // is opened, so nothing can be counted as done.
473            outcome.blocks_rewritten =
474                (bytes_planned / view.data_block_size.max(1) as u64) as usize;
475            outcome.bytes_rewritten = bytes_planned;
476            return Ok(outcome);
477        }
478
479        let config = compaction_config(&self.root_uri(), &runtime);
480        let mut file = Hyper::open(
481            self.client().clone(), config, HyperFileFlags::from_flags(FileFlags::rdwr()),
482        ).await?;
483        let result = self.relocate_and_publish(&mut file, &view, &selected, opts,
484            &mut outcome).await;
485        match result {
486            // Published, or nothing to publish: close as usual.
487            Ok(()) => { let _ = file.fs_release().await; },
488            // A failed pass publishes nothing. `fs_release` would flush what was
489            // marked, so a pass reported failed could still have published part
490            // of itself. The handle is dropped instead; any partials it wrote sit
491            // above the published checkpoint, where the next open steps past
492            // them and a later `prune` collects them once a publish passes them.
493            Err(e) => {
494                drop(file);
495                return Err(e);
496            },
497        }
498        if outcome.checkpoints == 0 && outcome.attached.is_none_or(|p| p.moved == 0) {
499            return Ok(outcome);
500        }
501
502        // Say what was actually freed rather than what should have been. A
503        // selected object that is still referenced means a block was not
504        // relocated, which is worth reporting where it can be seen. Beside the
505        // writer, by the attached map while it is attached: the stored one still
506        // points at every selected object until the writer takes it in.
507        let after = self.view(low, 0).await?;
508        let referenced = match (after.attached_root()?, outcome.attached) {
509            (Some(root), Some(_)) => self.reachable_objects(&after, root).await?,
510            _ => after.referenced_objects(),
511        };
512        outcome.still_referenced = outcome.selected.iter()
513            .filter(|segid| referenced.contains(segid))
514            .copied()
515            .collect();
516        if !outcome.still_referenced.is_empty() {
517            warn!("compact: {} of {} selected object(s) are still referenced: {:?}",
518                outcome.still_referenced.len(), outcome.selected.len(),
519                outcome.still_referenced);
520        }
521        if outcome.content_moved() {
522            if opts.beside_writer {
523                // An attached compaction never moves it: the writer published
524                // between this pass's open and its attach.
525                info!("compact: content_cno moved {} -> {} by the writer's own publishes during the pass; \
526                    the compaction does not move it", outcome.content_cno_before, outcome.content_cno_after);
527            } else {
528                warn!("compact: content_cno moved {} -> {}; consumers will see this pass \
529                    as a change of content", outcome.content_cno_before,
530                    outcome.content_cno_after);
531            }
532        }
533        info!("compact: rewrote {} block(s) ({} bytes) in {} checkpoint(s), freeing {} bytes \
534            across {} object(s)", outcome.blocks_rewritten, outcome.bytes_rewritten,
535            outcome.checkpoints, outcome.bytes_freed, outcome.selected.len());
536        Ok(outcome)
537    }
538
539    /// Mark every block of the selected objects for relocation, then publish once.
540    async fn relocate_and_publish(
541        &self,
542        file: &mut Hyper<'static>,
543        view: &ContainerView,
544        selected: &BTreeSet<SegmentId>,
545        opts: &CompactOptions,
546        outcome: &mut CompactOutcome,
547    ) -> Result<()> {
548        outcome.content_cno_before = file.fs_content_cno()?;
549        outcome.content_cno_after = outcome.content_cno_before;
550        if selected.is_empty() {
551            return Ok(());
552        }
553        if opts.beside_writer {
554            // Takes up the version stored now: the placements below are its.
555            let started = std::time::Instant::now();
556            loop {
557                match file.fs_begin_compaction().await {
558                    Ok(()) => break,
559                    Err(e) if e.kind() == ErrorKind::ResourceBusy && started.elapsed() + BUSY_RETRY <= opts.busy_wait => {
560                        debug!("compact: {}; trying again", e);
561                        tokio::time::sleep(BUSY_RETRY).await;
562                    },
563                    Err(e) => return Err(e),
564                }
565            }
566            let res = self.relocate_selected(file, view, selected, opts, outcome).await;
567            if res.is_err() || outcome.blocks_rewritten == 0 {
568                let _ = file.fs_abort_compaction().await;
569                return res;
570            }
571            let attached = file.fs_publish_compaction(opts.max_age).await?;
572            outcome.content_cno_after = file.fs_content_cno()?;
573            debug!("compact: attached a compaction of checkpoint {} to checkpoint {}: {} block(s) moved \
574                into parts {}..{}, in {} attempt(s)", attached.base, attached.attached_to, attached.moved,
575                attached.parts.0, attached.parts.1, attached.attempts);
576            outcome.attached = Some(attached);
577            return Ok(());
578        }
579        self.relocate_selected(file, view, selected, opts, outcome).await?;
580        if outcome.blocks_rewritten == 0 {
581            return Ok(());
582        }
583
584        let cno = file.fs_flush().await?;
585        outcome.checkpoints = 1;
586        outcome.content_cno_after = file.fs_content_cno()?;
587        debug!("compact: published checkpoint {} with {} relocated block(s); content_cno \
588            {} -> {}", cno, outcome.blocks_rewritten, outcome.content_cno_before,
589            outcome.content_cno_after);
590        Ok(())
591    }
592
593    /// Mark every block of the selected objects for relocation.
594    async fn relocate_selected(
595        &self,
596        file: &mut Hyper<'static>,
597        view: &ContainerView,
598        selected: &BTreeSet<SegmentId>,
599        opts: &CompactOptions,
600        outcome: &mut CompactOutcome,
601    ) -> Result<()> {
602        let bs = view.data_block_size;
603        let chunk_blocks = (opts.relocate_chunk_bytes / bs.max(1)).max(1);
604
605        // Which blocks are in the selected objects. `block_placement` answers
606        // exactly that, per index, from the live map — so it needs no agreement
607        // with a second reading of the container's layout. It is asked only about
608        // the windows the walk found mapped blocks in, never about the holes
609        // between them. Runs go to `fs_relocate` in index order, which is also
610        // the order the flush writes them in.
611        let mut pending: Vec<BlockIndex> = Vec::new();
612        for (start, n) in view.live.windows.iter().copied() {
613            let places = file.fs_block_placement(start, n).await?;
614            for (i, place) in places.iter().enumerate() {
615                if let Some((segid, _)) = place
616                    && selected.contains(segid)
617                {
618                    pending.push(start + i as BlockIndex);
619                    if pending.len() >= chunk_blocks {
620                        outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
621                        pending.clear();
622                    }
623                }
624            }
625        }
626        // A block under each live node of a selected object with nothing under it
627        // there: relocating it dirties the node, and the flush writes it anew.
628        let mut extra: BTreeSet<BlockIndex> = BTreeSet::new();
629        for node in &view.live.meta {
630            if !selected.contains(&view.object_of(node)) {
631                continue;
632            }
633            if let Some((key, under)) = view.live.node_keys.get(node) {
634                if !selected.contains(&view.object_of(under)) {
635                    extra.insert(*key);
636                }
637            }
638        }
639        if !extra.is_empty() {
640            debug!("compact: {} block(s) relocated for the index nodes over them", extra.len());
641        }
642        for key in extra {
643            pending.push(key);
644            if pending.len() >= chunk_blocks {
645                outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
646                pending.clear();
647            }
648        }
649        if !pending.is_empty() {
650            outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
651        }
652        outcome.bytes_rewritten = (outcome.blocks_rewritten * bs) as u64;
653        Ok(())
654    }
655}
656
657/// Hand `indices` to `fs_relocate` as runs of consecutive blocks.
658async fn relocate_runs(file: &mut Hyper<'static>, indices: &[BlockIndex]) -> Result<usize> {
659    let runs = into_runs(indices);
660    let marked = file.fs_relocate(&runs).await?;
661    debug!("compact: relocate {} block(s) in {} run(s) marked {}",
662        indices.len(), runs.len(), marked);
663    Ok(marked)
664}
665
666/// The most a pass holds in memory when nothing can write it out early: a parted
667/// container with partial segments turned off, or a container that is not parted.
668/// There `fs_relocate` keeps every block dirty until the pass's one flush.
669pub const UNBOUNDED_PASS_BYTES: u64 = 512 * 1024 * 1024;
670
671/// What `hyperfile` takes the most bytes of one object to be, for this format and
672/// configuration. A copy of `HyperTrait::max_object_bytes`, which is private, with
673/// its 16 KiB floor.
674fn max_object_bytes(fmt: &BlockPtrFormat, runtime: &HyperFileRuntimeConfig) -> u64 {
675    runtime.segment_max_object_bytes.clamp(16 * 1024, fmt.max_object_bytes()) as u64
676}
677
678/// What one pass may rewrite.
679///
680/// Where `fs_relocate` can write partials, the caller's budget alone: memory is
681/// bounded by the dirty-data limits. Where it cannot, also
682/// [`UNBOUNDED_PASS_BYTES`]. And on a container that is not parted, a checkpoint
683/// is one object and `hyperfile` refuses a flush larger, so the pass also fits
684/// one object, with room for the summary and index nodes it carries.
685fn pass_cap(max_pass_bytes: u64, fmt: &BlockPtrFormat, runtime: &HyperFileRuntimeConfig) -> u64 {
686    if fmt.is_parted() {
687        if runtime.parted_segment_enabled {
688            return max_pass_bytes;
689        }
690        return max_pass_bytes.min(UNBOUNDED_PASS_BYTES);
691    }
692    let one_object = max_object_bytes(fmt, runtime);
693    max_pass_bytes.min(UNBOUNDED_PASS_BYTES).min(one_object / 4 * 3)
694}
695
696/// Candidates, cheapest first, taken whole while they fit `cap`.
697///
698/// Returns `(selected, live_bytes, stored_bytes, more_remaining)`. An object is
699/// never split across passes: one that does not fit ends the selection, so the
700/// cheapest work is done first and nothing is half-moved.
701fn plan_pass(
702    objects: &[ObjectUsage],
703    max_live_ratio: f64,
704    cap: u64,
705) -> (BTreeSet<SegmentId>, u64, u64, bool) {
706    let mut selected = BTreeSet::new();
707    let mut live = 0u64;
708    let mut stored = 0u64;
709    let candidates = select_candidates(objects, max_live_ratio);
710    let total = candidates.len();
711    for usage in candidates {
712        if live.saturating_add(usage.rewrite_bytes) > cap {
713            break;
714        }
715        live += usage.rewrite_bytes;
716        stored += usage.bytes;
717        selected.insert(usage.segid);
718    }
719    let more = selected.len() < total;
720    (selected, live, stored, more)
721}
722
723/// Per-object liveness, from one view.
724///
725/// A location's size depends on what it holds, and a pointer does not say: a
726/// metadata node is `meta_block_size` and a data block is `data_block_size`. The
727/// metadata subset of the walk is what separates them.
728pub(crate) fn build_report(view: &ContainerView) -> Report {
729    let mut live_data: BTreeMap<SegmentId, usize> = BTreeMap::new();
730    let mut live_meta: BTreeMap<SegmentId, usize> = BTreeMap::new();
731    let mut extra: BTreeMap<SegmentId, usize> = BTreeMap::new();
732    let mut unfreeable: BTreeMap<SegmentId, usize> = BTreeMap::new();
733    for blkptr in &view.live.all {
734        let segid = view.object_of(blkptr);
735        if view.live.meta.contains(blkptr) {
736            *live_meta.entry(segid).or_default() += 1;
737            match view.live.node_keys.get(blkptr) {
738                Some((_, under)) if view.object_of(under) == segid => {},
739                Some(_) => *extra.entry(segid).or_default() += 1,
740                None => *unfreeable.entry(segid).or_default() += 1,
741            }
742        } else {
743            *live_data.entry(segid).or_default() += 1;
744        }
745    }
746
747    let mut objects = Vec::new();
748    let mut out_of_range = 0;
749    for (segid, bytes) in &view.listing.objects {
750        let cno = segid.as_cno();
751        if cno < view.low || cno > view.high_cno {
752            out_of_range += 1;
753            continue;
754        }
755        let live_data_blocks = live_data.get(segid).copied().unwrap_or(0);
756        let live_meta_blocks = live_meta.get(segid).copied().unwrap_or(0);
757        let extra_blocks = extra.get(segid).copied().unwrap_or(0);
758        let live_bytes = (live_data_blocks * view.data_block_size + live_meta_blocks * view.meta_block_size) as u64;
759        objects.push(ObjectUsage {
760            segid: *segid,
761            bytes: *bytes,
762            live_data_blocks,
763            live_meta_blocks,
764            live_bytes,
765            meta_moves_with_data: view.fmt.is_stream() && segid.is_partial(),
766            extra_blocks,
767            unfreeable_nodes: unfreeable.get(segid).copied().unwrap_or(0),
768            rewrite_bytes: live_bytes + (extra_blocks * view.data_block_size) as u64,
769        });
770    }
771
772    Report {
773        high_cno: view.high_cno,
774        latest_compacted: view.latest_compacted,
775        attached: view.compaction.clone(),
776        data_block_size: view.data_block_size,
777        meta_block_size: view.meta_block_size,
778        objects,
779        out_of_range,
780        foreign_keys: view.listing.foreign,
781        foreign_sample: view.listing.foreign_sample.clone(),
782    }
783}
784
785/// Whether rewriting this object's live data, and a block under each of its
786/// live nodes that has none here, would free it.
787///
788/// Three exclusions, each for its own reason: a dead object is `prune`'s work and
789/// rewriting nothing frees nothing; an object holding a node with no block on
790/// storage under it cannot be freed by anything a compaction marks; and one
791/// above the ratio costs more to rewrite than the policy accepts.
792///
793/// Getting the middle one wrong costs a rewrite, never data: compaction deletes
794/// nothing, `prune` keeps whatever the walk afterwards finds live, and
795/// [`CompactOutcome::still_referenced`] reports an object selected and not freed.
796fn is_candidate(usage: &ObjectUsage, max_live_ratio: f64) -> bool {
797    !usage.is_dead()
798        && usage.unfreeable_nodes == 0
799        && usage.cost_ratio() <= max_live_ratio
800}
801
802/// Candidates, cheapest first.
803///
804/// Ordered by live ratio ascending, which is the same as bytes freed per byte
805/// rewritten descending, with the larger object first among equals so a budget
806/// spent early buys more.
807fn select_candidates(
808    objects: &[ObjectUsage],
809    max_live_ratio: f64,
810) -> Vec<&ObjectUsage> {
811    let mut picked: Vec<&ObjectUsage> = objects.iter()
812        .filter(|o| is_candidate(o, max_live_ratio))
813        .collect();
814    picked.sort_by(|a, b| {
815        a.cost_ratio().total_cmp(&b.cost_ratio())
816            .then(b.bytes.cmp(&a.bytes))
817            .then(a.segid.cmp(&b.segid))
818    });
819    picked
820}
821
822/// Consecutive indices, as `(first, count)`.
823///
824/// What `read_ahead` wants: it takes a byte range and plans it the way a read of
825/// the same range would, so one call per run of adjacent blocks turns into a few
826/// large requests. Asking per block instead would be one request per block, which
827/// for scattered blocks it will be anyway.
828fn into_runs(indices: &[BlockIndex]) -> Vec<(BlockIndex, usize)> {
829    let mut runs: Vec<(BlockIndex, usize)> = Vec::new();
830    for idx in indices {
831        match runs.last_mut() {
832            Some((start, count)) if *start + *count as BlockIndex == *idx => *count += 1,
833            _ => runs.push((*idx, 1)),
834        }
835    }
836    runs
837}
838
839/// The runtime configuration a compaction uses when the caller gives none.
840///
841/// Partials of 64 MiB: large enough that a compacted range reads in few requests,
842/// small enough to bound what a pass holds. The flush interval is an hour so that
843/// partials are cut by size rather than by how long the reads took.
844pub fn compaction_runtime_default() -> HyperFileRuntimeConfig {
845    const PART: usize = 64 * 1024 * 1024;
846    HyperFileRuntimeConfig {
847        data_cache_dirty_max_bytes_threshold: PART,
848        data_cache_dirty_min_bytes_to_part: PART,
849        segment_buffer_size: PART,
850        data_cache_dirty_max_flush_interval: 3_600_000,
851        ..HyperFileRuntimeConfig::default()
852    }
853}
854
855/// The caller's runtime configuration, or the default, with the one field a
856/// compaction cannot leave to the caller.
857///
858/// Nothing else needs forcing. A pass never publishes before its flush — since
859/// `hyperfile 0.10.4`, `fs_relocate` answers the dirty-data limits with a partial
860/// or not at all, never with a publish — so the limits can be whatever the
861/// caller's writer uses.
862fn compaction_runtime(given: Option<&HyperFileRuntimeConfig>) -> HyperFileRuntimeConfig {
863    let mut runtime = given.cloned().unwrap_or_else(compaction_runtime_default);
864    // A compactor writes bytes it read earlier. Refreshing and re-publishing on a
865    // conflict, which `RetryLastWriterWins` does, would republish a stale copy
866    // over another writer's newer one.
867    runtime.flush_conflict_policy = FlushConflictPolicy::FailFast;
868    runtime
869}
870
871fn compaction_config(root_uri: &str, runtime: &HyperFileRuntimeConfig) -> HyperFileConfig {
872    let staging = StagingConfig::new_s3_uri(root_uri, None);
873    HyperFileConfigBuilder::new()
874        .with_staging_config(&staging)
875        .with_runtime_config(runtime)
876        .build()
877}
878
879#[cfg(test)]
880mod tests {
881    #[test]
882    fn max_age_must_be_below_the_prune_grace() {
883        use std::time::Duration;
884        let at = |max_age: u64, grace: Option<u64>, beside: bool| super::check_prune_grace(&CompactOptions {
885            beside_writer: beside, max_age: Duration::from_secs(max_age), prune_grace: grace.map(Duration::from_secs),
886            ..Default::default() }).map_err(|e| e.kind());
887        assert_eq!(at(600, None, true), Ok(()));
888        assert_eq!(at(25, Some(30), true), Ok(()));
889        assert_eq!(at(26, Some(30), true), Err(std::io::ErrorKind::InvalidInput));
890        assert_eq!(at(600, Some(30), true), Err(std::io::ErrorKind::InvalidInput));
891        assert_eq!(at(600, Some(30), false), Ok(()), "offline, max_age does not apply");
892    }
893
894    use super::*;
895
896    fn usage(segid: SegmentId, bytes: u64, data: usize, meta: usize) -> ObjectUsage {
897        ObjectUsage {
898            segid,
899            bytes,
900            live_data_blocks: data,
901            live_meta_blocks: meta,
902            live_bytes: (data * 4096 + meta * 4096) as u64,
903            meta_moves_with_data: false,
904            extra_blocks: 0,
905            unfreeable_nodes: 0,
906            rewrite_bytes: (data * 4096 + meta * 4096) as u64,
907        }
908    }
909
910    #[test]
911    fn a_dead_object_is_pruned_not_compacted() {
912        let o = usage(SegmentId::new(1), 1 << 20, 0, 0);
913        assert!(o.is_dead());
914        assert!(!is_candidate(&o, 1.0), "nothing to rewrite frees nothing");
915    }
916
917    /// An object a live node sits in is a candidate: its node is rewritten by
918    /// relocating a block under it, counted in what freeing it costs.
919    #[test]
920    fn an_object_holding_metadata_is_a_candidate_at_its_cost() {
921        let o = usage(SegmentId::with_part(3, 0), 1 << 20, 1, 1);
922        assert!(o.holds_metadata());
923        assert!(is_candidate(&o, 1.0));
924        // 100 extra blocks for nodes over data elsewhere: 0.4 of 1 MiB over the
925        // live data's.
926        let costly = ObjectUsage { extra_blocks: 100, rewrite_bytes: o.rewrite_bytes + 100 * 4096, ..o.clone() };
927        assert!(costly.cost_ratio() > 0.39 && costly.live_ratio() < 0.01);
928        assert!(!is_candidate(&costly, 0.3), "the extra blocks are in its cost");
929        assert!(is_candidate(&costly, 0.5));
930    }
931
932    /// A node with no block on storage under it cannot be rewritten by a
933    /// compaction: its object is not a candidate.
934    #[test]
935    fn a_node_over_nothing_on_storage_keeps_its_object_out() {
936        let o = ObjectUsage { unfreeable_nodes: 1, ..usage(SegmentId::with_part(3, 0), 1 << 20, 1, 1) };
937        assert!(!is_candidate(&o, 1.0));
938    }
939
940    #[test]
941    fn the_ratio_is_a_ceiling() {
942        let low = usage(SegmentId::new(1), 4096 * 100, 5, 0);   // 5% live
943        let high = usage(SegmentId::new(2), 4096 * 100, 90, 0); // 90% live
944        assert!(is_candidate(&low, 0.5));
945        assert!(!is_candidate(&high, 0.5));
946        assert!(is_candidate(&high, 0.9));
947    }
948
949    /// Cheapest first, and the bigger object first among equals: the budget is
950    /// finite and the point is how much it buys.
951    #[test]
952    fn candidates_come_cheapest_first() {
953        let objects = vec![
954            usage(SegmentId::new(1), 4096 * 100, 40, 0), // 40%
955            usage(SegmentId::new(2), 4096 * 100, 5, 0),  // 5%
956            usage(SegmentId::new(3), 4096 * 200, 10, 0), // 5%, larger
957        ];
958        let picked = select_candidates(&objects, 0.5);
959        let order: Vec<SegmentId> = picked.iter().map(|o| o.segid).collect();
960        assert_eq!(order, vec![SegmentId::new(3), SegmentId::new(2), SegmentId::new(1)]);
961    }
962
963    #[test]
964    fn runs_are_maximal() {
965        assert_eq!(into_runs(&[]), vec![]);
966        assert_eq!(into_runs(&[7]), vec![(7, 1)]);
967        assert_eq!(into_runs(&[0, 1, 2, 5, 6, 9]), vec![(0, 3), (5, 2), (9, 1)]);
968    }
969
970    /// A pass takes objects whole and cheapest first, and stops at the first one
971    /// that does not fit rather than skipping to a smaller one: the cheapest work
972    /// is done first, and the pass says there is more.
973    #[test]
974    fn a_pass_takes_whole_objects_until_the_budget() {
975        let objects = vec![
976            usage(SegmentId::new(1), 4096 * 100, 10, 0), // 10%, 40 KiB live
977            usage(SegmentId::new(2), 4096 * 100, 20, 0), // 20%, 80 KiB live
978            usage(SegmentId::new(3), 4096 * 100, 1, 0),  //  1%,  4 KiB live
979        ];
980        let (picked, live, stored, more) = plan_pass(&objects, 0.5, 4096 * 15);
981        assert_eq!(picked.into_iter().collect::<Vec<_>>(),
982            vec![SegmentId::new(1), SegmentId::new(3)]);
983        assert_eq!(live, 4096 * 11);
984        assert_eq!(stored, 4096 * 200);
985        assert!(more, "object 2 did not fit and is still a candidate");
986
987        let (picked, _, _, more) = plan_pass(&objects, 0.5, u64::MAX);
988        assert_eq!(picked.len(), 3);
989        assert!(!more);
990    }
991
992    /// Where partials can be written, memory is bounded by the dirty-data limits
993    /// and only the caller's budget applies. Where they cannot, the pass is held
994    /// in memory whole and is capped; and a container that is not parted also has
995    /// to fit its pass in one object, as `hyperfile` reckons one — the caller's
996    /// `segment_max_object_bytes` included.
997    #[test]
998    fn the_pass_cap_follows_what_can_write_it_out() {
999        let big = u64::MAX;
1000        let parts_on = compaction_runtime(None);
1001        assert!(parts_on.parted_segment_enabled);
1002        assert_eq!(pass_cap(big, &BlockPtrFormat::PartedSegment, &parts_on), big);
1003
1004        let parts_off = HyperFileRuntimeConfig { parted_segment_enabled: false, ..parts_on.clone() };
1005        assert_eq!(pass_cap(big, &BlockPtrFormat::PartedSegment, &parts_off), UNBOUNDED_PASS_BYTES);
1006
1007        let mg = BlockPtrFormat::MicroGroup.max_object_bytes() as u64;
1008        let cap = pass_cap(big, &BlockPtrFormat::MicroGroup, &parts_on);
1009        assert!(cap < mg && cap <= UNBOUNDED_PASS_BYTES);
1010
1011        let small_objects = HyperFileRuntimeConfig {
1012            segment_max_object_bytes: 1024 * 1024, ..parts_on.clone()
1013        };
1014        assert_eq!(pass_cap(big, &BlockPtrFormat::MicroGroup, &small_objects), 1024 * 1024 / 4 * 3,
1015            "the caller's object size is what hyperfile refuses past");
1016        assert_eq!(pass_cap(4096, &BlockPtrFormat::MicroGroup, &parts_on), 4096,
1017            "a smaller budget is kept as given");
1018    }
1019
1020    /// The caller's configuration is used as given, except for the conflict
1021    /// policy, which a compactor cannot leave at retry-and-overwrite.
1022    #[test]
1023    fn a_given_runtime_is_kept_but_for_the_conflict_policy() {
1024        use hyperfile::config::FlushConflictPolicy;
1025        let given = HyperFileRuntimeConfig {
1026            data_cache_dirty_min_bytes_to_part: 16 * 1024 * 1024,
1027            data_cache_dirty_max_bytes_threshold: 16 * 1024 * 1024,
1028            segment_mpu_chunk_size: 16 * 1024 * 1024,
1029            flush_conflict_policy: FlushConflictPolicy::RetryLastWriterWins,
1030            ..HyperFileRuntimeConfig::default()
1031        };
1032        let used = compaction_runtime(Some(&given));
1033        assert_eq!(used.flush_conflict_policy, FlushConflictPolicy::FailFast);
1034        assert_eq!(HyperFileRuntimeConfig {
1035            flush_conflict_policy: FlushConflictPolicy::RetryLastWriterWins, ..used
1036        }, given);
1037        assert_eq!(compaction_runtime(None).flush_conflict_policy, FlushConflictPolicy::FailFast);
1038    }
1039
1040    /// An object whose live data alone is over the budget is never taken, and
1041    /// the pass reports that it left work behind instead of doing nothing quietly.
1042    #[test]
1043    fn an_object_larger_than_the_budget_is_reported_not_split() {
1044        let objects = vec![usage(SegmentId::new(1), 4096 * 1000, 100, 0)];
1045        let (picked, live, _, more) = plan_pass(&objects, 0.5, 4096 * 10);
1046        assert!(picked.is_empty());
1047        assert_eq!(live, 0);
1048        assert!(more);
1049    }
1050
1051    /// `compactable` must answer from the same rule the pass selects by,
1052    /// otherwise a dry run and the pass disagree about what will happen.
1053    #[test]
1054    fn the_estimate_agrees_with_the_selection() {
1055        let report = Report {
1056            high_cno: 9,
1057            latest_compacted: false,
1058            attached: Default::default(),
1059            data_block_size: 4096,
1060            meta_block_size: 4096,
1061            objects: vec![
1062                usage(SegmentId::new(1), 4096 * 100, 5, 0),
1063                usage(SegmentId::new(2), 4096 * 100, 80, 0),
1064                usage(SegmentId::new(3), 4096 * 100, 0, 0),
1065                usage(SegmentId::new(4), 4096 * 100, 2, 3),
1066            ],
1067            out_of_range: 0,
1068            foreign_keys: 0,
1069            foreign_sample: None,
1070        };
1071        let (n, rewrite, freed) = report.compactable(0.5);
1072        assert_eq!(n, 2, "the 5% object and the 5% one holding nodes qualify");
1073        assert_eq!(rewrite, (5 + 2 + 3) * 4096);
1074        assert_eq!(freed, 2 * 4096 * 100);
1075        assert_eq!(report.dead(), (1, 4096 * 100));
1076        let picked = select_candidates(&report.objects, CompactOptions::default().max_live_ratio);
1077        assert_eq!(picked.len(), n);
1078    }
1079}