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, and with
284    /// `TimedOut` past `max_age`; either way try again later. A writer with a
285    /// write-ahead log takes it in too, with hyperfile 0.12.1 or later, its log
286    /// under the container's prefix or not.
287    pub beside_writer: bool,
288    /// Beside the writer, the longest a pass may take from its start to its
289    /// attach; past it the pass is given up. Its copies are referenced by
290    /// nothing until attached, and only a `prune` grace keeps them, so set this
291    /// below the grace of any [`S3Cleaner::prune_with`] that may run meanwhile,
292    /// less a margin. Ten minutes by default. It is measured by the store's
293    /// clock at the attach, as `prune` measures its grace.
294    pub max_age: std::time::Duration,
295    /// Beside the writer, the grace of the `prune_with` that runs beside this
296    /// pass, when known: the pass is refused (`InvalidInput`), nothing done,
297    /// unless `max_age` is below it by [`ATTACH_MARGIN`] at least. `None`, the
298    /// default, checks nothing.
299    pub prune_grace: Option<std::time::Duration>,
300}
301
302/// How far below a prune's grace `CompactOptions::max_age` must be: what the
303/// attach itself takes after its last check, and the store's whole seconds.
304/// hyperfile's own, which its compactor checks by.
305pub use hyperfile::compaction::ATTACH_MARGIN;
306
307impl Default for CompactOptions {
308    fn default() -> Self {
309        Self {
310            max_live_ratio: 0.5,
311            max_pass_bytes: u64::MAX,
312            runtime: None,
313            relocate_chunk_bytes: 64 * 1024 * 1024,
314            dry_run: false,
315            allow_consecutive: false,
316            allow_foreign_keys: false,
317            beside_writer: false,
318            max_age: std::time::Duration::from_secs(600),
319            prune_grace: None,
320        }
321    }
322}
323
324/// See [`CompactOptions::prune_grace`].
325fn check_prune_grace(opts: &CompactOptions) -> Result<()> {
326    match opts.prune_grace {
327        Some(grace) if opts.beside_writer && opts.max_age + ATTACH_MARGIN > grace => Err(Error::new(ErrorKind::InvalidInput,
328            format!("max_age {:?} is not below the prune grace {:?} by {:?}: a prune could take the copies for \
329                     unreferenced before they are attached", opts.max_age, grace, ATTACH_MARGIN))),
330        _ => Ok(()),
331    }
332}
333
334/// What a compaction pass did.
335#[derive(Clone, Debug, Default)]
336pub struct CompactOutcome {
337    /// The objects whose live blocks were rewritten, ascending.
338    pub selected: Vec<SegmentId>,
339    /// Of those, the ones a walk taken afterwards still finds referenced. Empty
340    /// on a pass that did what it set out to; anything here is an object that was
341    /// not freed, and is reported rather than assumed away.
342    pub still_referenced: Vec<SegmentId>,
343    /// Blocks `fs_relocate` marked: what was done, not what was planned. A hole,
344    /// an explicit zero block or a block already dirty is not counted.
345    pub blocks_rewritten: usize,
346    pub bytes_rewritten: u64,
347    /// The selected objects' stored bytes — what `prune` can now reclaim.
348    pub bytes_freed: u64,
349    /// Checkpoints published: one for a pass that rewrote anything, none
350    /// otherwise. That is how far `last_cno` advanced. Always none beside the
351    /// writer, whose pass keeps the number: see `attached`.
352    pub checkpoints: usize,
353    /// Beside the writer, what was attached: the version it was built on and the
354    /// one it was attached to, the parts its objects are in, blocks moved, and
355    /// how many conditional writes of the inode it took.
356    pub attached: Option<CompactionAttached>,
357    /// `fs_content_cno` before and after the pass. Equal when consumers will not
358    /// see the pass as a change of content, which is the ordinary case. They
359    /// differ when the publish could not be marked: its number did not follow the
360    /// previous one — an earlier flush failed and gave its number up — or the
361    /// newest checkpoint was already a compaction and the pass ran anyway.
362    pub content_cno_before: Cno,
363    pub content_cno_after: Cno,
364    /// Whether the candidates outlasted the pass budget. Another pass would find
365    /// more to do, at the cost of `content_cno` moving once (see
366    /// [`CompactOptions::allow_consecutive`]).
367    pub more_remaining: bool,
368    pub dry_run: bool,
369}
370
371impl CompactOutcome {
372    /// Whether a consumer comparing `content_cno` will see this pass as a change.
373    pub fn content_moved(&self) -> bool {
374        self.content_cno_before != self.content_cno_after
375    }
376}
377
378impl S3Cleaner {
379    /// What the container's storage is made of: per-object liveness for every
380    /// object whose checkpoint falls in `[low, high]`.
381    ///
382    /// Read-only, and the same walk `collect` does plus one `ListObjectsV2` for
383    /// sizes. `high == 0` means the latest published checkpoint.
384    pub async fn report(&self, low: Cno, high: Cno) -> Result<Report> {
385        let view = self.view(low, high).await?;
386        Ok(build_report(&view))
387    }
388
389    /// Rewrite the live blocks of mostly-dead objects so `prune` can reclaim
390    /// them.
391    ///
392    /// The caller must be the container's only writer for the duration; see the
393    /// [module docs](self) for why that is not a nicety. Nothing is deleted here
394    /// — a compaction makes objects reclaimable and `prune` reclaims them, which
395    /// keeps the destructive step in one place.
396    pub async fn compact(
397        &self,
398        low: Cno,
399        high: Cno,
400        opts: &CompactOptions,
401    ) -> Result<CompactOutcome> {
402        check_prune_grace(opts)?;
403        let view = self.view(low, high).await?;
404        // Beside the writer the pass publishes nothing a log could be under.
405        if view.listing.foreign > 0 && !opts.allow_foreign_keys && !opts.beside_writer {
406            return Err(Error::new(
407                ErrorKind::InvalidInput,
408                format!(
409                    "{} key(s) under the container's prefix are neither the inode nor \
410                     segment objects (for example {:?}); a WAL is the usual reason, and \
411                     compacting past a log this pass does not read would publish over \
412                     entries recovery has not replayed. Set allow_foreign_keys once you \
413                     have established otherwise",
414                    view.listing.foreign,
415                    view.listing.foreign_sample.as_deref().unwrap_or("?"),
416                ),
417            ));
418        }
419
420        if view.latest_compacted && !opts.allow_consecutive && !opts.dry_run && !opts.beside_writer {
421            return Err(Error::new(
422                ErrorKind::InvalidInput,
423                format!(
424                    "checkpoint {} is already a compaction, and the flag that keeps \
425                     content_cno still holds for one checkpoint only: a second pass in a \
426                     row would be seen by consumers as a change of content. Write to the \
427                     file first, or set allow_consecutive",
428                    view.high_cno,
429                ),
430            ));
431        }
432
433        let report = build_report(&view);
434        let mut runtime = compaction_runtime(opts.runtime.as_ref());
435        if opts.beside_writer {
436            // Not the writer: a checkpoint the writer has on storage and has not
437            // yet pointed the inode at is the writer's to publish. Taking it up
438            // here would publish it under the writer and fail its own inode write.
439            runtime.take_up_on_open = false;
440            // hyperfile checks by it too, at the attach.
441            if let Some(grace) = opts.prune_grace {
442                runtime.compaction_prune_grace_secs = Some(grace.as_secs());
443            }
444        }
445        let pass_cap = pass_cap(opts.max_pass_bytes, &view.fmt, &runtime);
446        let (selected, bytes_planned, bytes_freed, more_remaining) =
447            plan_pass(&report.objects, opts.max_live_ratio, pass_cap);
448        debug!("compact: {} object(s) selected of {} in range, {} live bytes (cap {})",
449            selected.len(), report.objects.len(), bytes_planned, pass_cap);
450
451        let mut outcome = CompactOutcome {
452            selected: selected.iter().copied().collect(),
453            bytes_freed,
454            more_remaining,
455            dry_run: opts.dry_run,
456            ..Default::default()
457        };
458        if opts.dry_run {
459            // The plan's own numbers, which is all a dry run can report: nothing
460            // is opened, so nothing can be counted as done.
461            outcome.blocks_rewritten =
462                (bytes_planned / view.data_block_size.max(1) as u64) as usize;
463            outcome.bytes_rewritten = bytes_planned;
464            return Ok(outcome);
465        }
466
467        let config = compaction_config(&self.root_uri(), &runtime);
468        let mut file = Hyper::open(
469            self.client().clone(), config, HyperFileFlags::from_flags(FileFlags::rdwr()),
470        ).await?;
471        let result = self.relocate_and_publish(&mut file, &view, &selected, opts,
472            &mut outcome).await;
473        match result {
474            // Published, or nothing to publish: close as usual.
475            Ok(()) => { let _ = file.fs_release().await; },
476            // A failed pass publishes nothing. `fs_release` would flush what was
477            // marked, so a pass reported failed could still have published part
478            // of itself. The handle is dropped instead; any partials it wrote sit
479            // above the published checkpoint, where the next open steps past
480            // them and a later `prune` collects them once a publish passes them.
481            Err(e) => {
482                drop(file);
483                return Err(e);
484            },
485        }
486        if outcome.checkpoints == 0 && outcome.attached.is_none_or(|p| p.moved == 0) {
487            return Ok(outcome);
488        }
489
490        // Say what was actually freed rather than what should have been. A
491        // selected object that is still referenced means a block was not
492        // relocated, which is worth reporting where it can be seen. Beside the
493        // writer, by the attached map while it is attached: the stored one still
494        // points at every selected object until the writer takes it in.
495        let after = self.view(low, 0).await?;
496        let referenced = match (after.attached_root()?, outcome.attached) {
497            (Some(root), Some(_)) => self.reachable_objects(&after, root).await?,
498            _ => after.referenced_objects(),
499        };
500        outcome.still_referenced = outcome.selected.iter()
501            .filter(|segid| referenced.contains(segid))
502            .copied()
503            .collect();
504        if !outcome.still_referenced.is_empty() {
505            warn!("compact: {} of {} selected object(s) are still referenced: {:?}",
506                outcome.still_referenced.len(), outcome.selected.len(),
507                outcome.still_referenced);
508        }
509        if outcome.content_moved() {
510            warn!("compact: content_cno moved {} -> {}; consumers will see this pass \
511                as a change of content", outcome.content_cno_before,
512                outcome.content_cno_after);
513        }
514        info!("compact: rewrote {} block(s) ({} bytes) in {} checkpoint(s), freeing {} bytes \
515            across {} object(s)", outcome.blocks_rewritten, outcome.bytes_rewritten,
516            outcome.checkpoints, outcome.bytes_freed, outcome.selected.len());
517        Ok(outcome)
518    }
519
520    /// Mark every block of the selected objects for relocation, then publish once.
521    async fn relocate_and_publish(
522        &self,
523        file: &mut Hyper<'static>,
524        view: &ContainerView,
525        selected: &BTreeSet<SegmentId>,
526        opts: &CompactOptions,
527        outcome: &mut CompactOutcome,
528    ) -> Result<()> {
529        outcome.content_cno_before = file.fs_content_cno()?;
530        outcome.content_cno_after = outcome.content_cno_before;
531        if selected.is_empty() {
532            return Ok(());
533        }
534        if opts.beside_writer {
535            // Takes up the version stored now: the placements below are its.
536            file.fs_begin_compaction().await?;
537            let res = self.relocate_selected(file, view, selected, opts, outcome).await;
538            if res.is_err() || outcome.blocks_rewritten == 0 {
539                let _ = file.fs_abort_compaction().await;
540                return res;
541            }
542            let attached = file.fs_publish_compaction(opts.max_age).await?;
543            outcome.content_cno_after = file.fs_content_cno()?;
544            debug!("compact: attached a compaction of checkpoint {} to checkpoint {}: {} block(s) moved \
545                into parts {}..{}, in {} attempt(s)", attached.base, attached.attached_to, attached.moved,
546                attached.parts.0, attached.parts.1, attached.attempts);
547            outcome.attached = Some(attached);
548            return Ok(());
549        }
550        self.relocate_selected(file, view, selected, opts, outcome).await?;
551        if outcome.blocks_rewritten == 0 {
552            return Ok(());
553        }
554
555        let cno = file.fs_flush().await?;
556        outcome.checkpoints = 1;
557        outcome.content_cno_after = file.fs_content_cno()?;
558        debug!("compact: published checkpoint {} with {} relocated block(s); content_cno \
559            {} -> {}", cno, outcome.blocks_rewritten, outcome.content_cno_before,
560            outcome.content_cno_after);
561        Ok(())
562    }
563
564    /// Mark every block of the selected objects for relocation.
565    async fn relocate_selected(
566        &self,
567        file: &mut Hyper<'static>,
568        view: &ContainerView,
569        selected: &BTreeSet<SegmentId>,
570        opts: &CompactOptions,
571        outcome: &mut CompactOutcome,
572    ) -> Result<()> {
573        let bs = view.data_block_size;
574        let chunk_blocks = (opts.relocate_chunk_bytes / bs.max(1)).max(1);
575
576        // Which blocks are in the selected objects. `block_placement` answers
577        // exactly that, per index, from the live map — so it needs no agreement
578        // with a second reading of the container's layout. It is asked only about
579        // the windows the walk found mapped blocks in, never about the holes
580        // between them. Runs go to `fs_relocate` in index order, which is also
581        // the order the flush writes them in.
582        let mut pending: Vec<BlockIndex> = Vec::new();
583        for (start, n) in view.live.windows.iter().copied() {
584            let places = file.fs_block_placement(start, n).await?;
585            for (i, place) in places.iter().enumerate() {
586                if let Some((segid, _)) = place
587                    && selected.contains(segid)
588                {
589                    pending.push(start + i as BlockIndex);
590                    if pending.len() >= chunk_blocks {
591                        outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
592                        pending.clear();
593                    }
594                }
595            }
596        }
597        // A block under each live node of a selected object with nothing under it
598        // there: relocating it dirties the node, and the flush writes it anew.
599        let mut extra: BTreeSet<BlockIndex> = BTreeSet::new();
600        for node in &view.live.meta {
601            if !selected.contains(&view.object_of(node)) {
602                continue;
603            }
604            if let Some((key, under)) = view.live.node_keys.get(node) {
605                if !selected.contains(&view.object_of(under)) {
606                    extra.insert(*key);
607                }
608            }
609        }
610        if !extra.is_empty() {
611            debug!("compact: {} block(s) relocated for the index nodes over them", extra.len());
612        }
613        for key in extra {
614            pending.push(key);
615            if pending.len() >= chunk_blocks {
616                outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
617                pending.clear();
618            }
619        }
620        if !pending.is_empty() {
621            outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
622        }
623        outcome.bytes_rewritten = (outcome.blocks_rewritten * bs) as u64;
624        Ok(())
625    }
626}
627
628/// Hand `indices` to `fs_relocate` as runs of consecutive blocks.
629async fn relocate_runs(file: &mut Hyper<'static>, indices: &[BlockIndex]) -> Result<usize> {
630    let runs = into_runs(indices);
631    let marked = file.fs_relocate(&runs).await?;
632    debug!("compact: relocate {} block(s) in {} run(s) marked {}",
633        indices.len(), runs.len(), marked);
634    Ok(marked)
635}
636
637/// The most a pass holds in memory when nothing can write it out early: a parted
638/// container with partial segments turned off, or a container that is not parted.
639/// There `fs_relocate` keeps every block dirty until the pass's one flush.
640pub const UNBOUNDED_PASS_BYTES: u64 = 512 * 1024 * 1024;
641
642/// What `hyperfile` takes the most bytes of one object to be, for this format and
643/// configuration. A copy of `HyperTrait::max_object_bytes`, which is private, with
644/// its 16 KiB floor.
645fn max_object_bytes(fmt: &BlockPtrFormat, runtime: &HyperFileRuntimeConfig) -> u64 {
646    runtime.segment_max_object_bytes.clamp(16 * 1024, fmt.max_object_bytes()) as u64
647}
648
649/// What one pass may rewrite.
650///
651/// Where `fs_relocate` can write partials, the caller's budget alone: memory is
652/// bounded by the dirty-data limits. Where it cannot, also
653/// [`UNBOUNDED_PASS_BYTES`]. And on a container that is not parted, a checkpoint
654/// is one object and `hyperfile` refuses a flush larger, so the pass also fits
655/// one object, with room for the summary and index nodes it carries.
656fn pass_cap(max_pass_bytes: u64, fmt: &BlockPtrFormat, runtime: &HyperFileRuntimeConfig) -> u64 {
657    if fmt.is_parted() {
658        if runtime.parted_segment_enabled {
659            return max_pass_bytes;
660        }
661        return max_pass_bytes.min(UNBOUNDED_PASS_BYTES);
662    }
663    let one_object = max_object_bytes(fmt, runtime);
664    max_pass_bytes.min(UNBOUNDED_PASS_BYTES).min(one_object / 4 * 3)
665}
666
667/// Candidates, cheapest first, taken whole while they fit `cap`.
668///
669/// Returns `(selected, live_bytes, stored_bytes, more_remaining)`. An object is
670/// never split across passes: one that does not fit ends the selection, so the
671/// cheapest work is done first and nothing is half-moved.
672fn plan_pass(
673    objects: &[ObjectUsage],
674    max_live_ratio: f64,
675    cap: u64,
676) -> (BTreeSet<SegmentId>, u64, u64, bool) {
677    let mut selected = BTreeSet::new();
678    let mut live = 0u64;
679    let mut stored = 0u64;
680    let candidates = select_candidates(objects, max_live_ratio);
681    let total = candidates.len();
682    for usage in candidates {
683        if live.saturating_add(usage.rewrite_bytes) > cap {
684            break;
685        }
686        live += usage.rewrite_bytes;
687        stored += usage.bytes;
688        selected.insert(usage.segid);
689    }
690    let more = selected.len() < total;
691    (selected, live, stored, more)
692}
693
694/// Per-object liveness, from one view.
695///
696/// A location's size depends on what it holds, and a pointer does not say: a
697/// metadata node is `meta_block_size` and a data block is `data_block_size`. The
698/// metadata subset of the walk is what separates them.
699pub(crate) fn build_report(view: &ContainerView) -> Report {
700    let mut live_data: BTreeMap<SegmentId, usize> = BTreeMap::new();
701    let mut live_meta: BTreeMap<SegmentId, usize> = BTreeMap::new();
702    let mut extra: BTreeMap<SegmentId, usize> = BTreeMap::new();
703    let mut unfreeable: BTreeMap<SegmentId, usize> = BTreeMap::new();
704    for blkptr in &view.live.all {
705        let segid = view.object_of(blkptr);
706        if view.live.meta.contains(blkptr) {
707            *live_meta.entry(segid).or_default() += 1;
708            match view.live.node_keys.get(blkptr) {
709                Some((_, under)) if view.object_of(under) == segid => {},
710                Some(_) => *extra.entry(segid).or_default() += 1,
711                None => *unfreeable.entry(segid).or_default() += 1,
712            }
713        } else {
714            *live_data.entry(segid).or_default() += 1;
715        }
716    }
717
718    let mut objects = Vec::new();
719    let mut out_of_range = 0;
720    for (segid, bytes) in &view.listing.objects {
721        let cno = segid.as_cno();
722        if cno < view.low || cno > view.high_cno {
723            out_of_range += 1;
724            continue;
725        }
726        let live_data_blocks = live_data.get(segid).copied().unwrap_or(0);
727        let live_meta_blocks = live_meta.get(segid).copied().unwrap_or(0);
728        let extra_blocks = extra.get(segid).copied().unwrap_or(0);
729        let live_bytes = (live_data_blocks * view.data_block_size + live_meta_blocks * view.meta_block_size) as u64;
730        objects.push(ObjectUsage {
731            segid: *segid,
732            bytes: *bytes,
733            live_data_blocks,
734            live_meta_blocks,
735            live_bytes,
736            meta_moves_with_data: view.fmt.is_stream() && segid.is_partial(),
737            extra_blocks,
738            unfreeable_nodes: unfreeable.get(segid).copied().unwrap_or(0),
739            rewrite_bytes: live_bytes + (extra_blocks * view.data_block_size) as u64,
740        });
741    }
742
743    Report {
744        high_cno: view.high_cno,
745        latest_compacted: view.latest_compacted,
746        attached: view.compaction.clone(),
747        data_block_size: view.data_block_size,
748        meta_block_size: view.meta_block_size,
749        objects,
750        out_of_range,
751        foreign_keys: view.listing.foreign,
752        foreign_sample: view.listing.foreign_sample.clone(),
753    }
754}
755
756/// Whether rewriting this object's live data, and a block under each of its
757/// live nodes that has none here, would free it.
758///
759/// Three exclusions, each for its own reason: a dead object is `prune`'s work and
760/// rewriting nothing frees nothing; an object holding a node with no block on
761/// storage under it cannot be freed by anything a compaction marks; and one
762/// above the ratio costs more to rewrite than the policy accepts.
763///
764/// Getting the middle one wrong costs a rewrite, never data: compaction deletes
765/// nothing, `prune` keeps whatever the walk afterwards finds live, and
766/// [`CompactOutcome::still_referenced`] reports an object selected and not freed.
767fn is_candidate(usage: &ObjectUsage, max_live_ratio: f64) -> bool {
768    !usage.is_dead()
769        && usage.unfreeable_nodes == 0
770        && usage.cost_ratio() <= max_live_ratio
771}
772
773/// Candidates, cheapest first.
774///
775/// Ordered by live ratio ascending, which is the same as bytes freed per byte
776/// rewritten descending, with the larger object first among equals so a budget
777/// spent early buys more.
778fn select_candidates(
779    objects: &[ObjectUsage],
780    max_live_ratio: f64,
781) -> Vec<&ObjectUsage> {
782    let mut picked: Vec<&ObjectUsage> = objects.iter()
783        .filter(|o| is_candidate(o, max_live_ratio))
784        .collect();
785    picked.sort_by(|a, b| {
786        a.cost_ratio().total_cmp(&b.cost_ratio())
787            .then(b.bytes.cmp(&a.bytes))
788            .then(a.segid.cmp(&b.segid))
789    });
790    picked
791}
792
793/// Consecutive indices, as `(first, count)`.
794///
795/// What `read_ahead` wants: it takes a byte range and plans it the way a read of
796/// the same range would, so one call per run of adjacent blocks turns into a few
797/// large requests. Asking per block instead would be one request per block, which
798/// for scattered blocks it will be anyway.
799fn into_runs(indices: &[BlockIndex]) -> Vec<(BlockIndex, usize)> {
800    let mut runs: Vec<(BlockIndex, usize)> = Vec::new();
801    for idx in indices {
802        match runs.last_mut() {
803            Some((start, count)) if *start + *count as BlockIndex == *idx => *count += 1,
804            _ => runs.push((*idx, 1)),
805        }
806    }
807    runs
808}
809
810/// The runtime configuration a compaction uses when the caller gives none.
811///
812/// Partials of 64 MiB: large enough that a compacted range reads in few requests,
813/// small enough to bound what a pass holds. The flush interval is an hour so that
814/// partials are cut by size rather than by how long the reads took.
815pub fn compaction_runtime_default() -> HyperFileRuntimeConfig {
816    const PART: usize = 64 * 1024 * 1024;
817    HyperFileRuntimeConfig {
818        data_cache_dirty_max_bytes_threshold: PART,
819        data_cache_dirty_min_bytes_to_part: PART,
820        segment_buffer_size: PART,
821        data_cache_dirty_max_flush_interval: 3_600_000,
822        ..HyperFileRuntimeConfig::default()
823    }
824}
825
826/// The caller's runtime configuration, or the default, with the one field a
827/// compaction cannot leave to the caller.
828///
829/// Nothing else needs forcing. A pass never publishes before its flush — since
830/// `hyperfile 0.10.4`, `fs_relocate` answers the dirty-data limits with a partial
831/// or not at all, never with a publish — so the limits can be whatever the
832/// caller's writer uses.
833fn compaction_runtime(given: Option<&HyperFileRuntimeConfig>) -> HyperFileRuntimeConfig {
834    let mut runtime = given.cloned().unwrap_or_else(compaction_runtime_default);
835    // A compactor writes bytes it read earlier. Refreshing and re-publishing on a
836    // conflict, which `RetryLastWriterWins` does, would republish a stale copy
837    // over another writer's newer one.
838    runtime.flush_conflict_policy = FlushConflictPolicy::FailFast;
839    runtime
840}
841
842fn compaction_config(root_uri: &str, runtime: &HyperFileRuntimeConfig) -> HyperFileConfig {
843    let staging = StagingConfig::new_s3_uri(root_uri, None);
844    HyperFileConfigBuilder::new()
845        .with_staging_config(&staging)
846        .with_runtime_config(runtime)
847        .build()
848}
849
850#[cfg(test)]
851mod tests {
852    #[test]
853    fn max_age_must_be_below_the_prune_grace() {
854        use std::time::Duration;
855        let at = |max_age: u64, grace: Option<u64>, beside: bool| super::check_prune_grace(&CompactOptions {
856            beside_writer: beside, max_age: Duration::from_secs(max_age), prune_grace: grace.map(Duration::from_secs),
857            ..Default::default() }).map_err(|e| e.kind());
858        assert_eq!(at(600, None, true), Ok(()));
859        assert_eq!(at(25, Some(30), true), Ok(()));
860        assert_eq!(at(26, Some(30), true), Err(std::io::ErrorKind::InvalidInput));
861        assert_eq!(at(600, Some(30), true), Err(std::io::ErrorKind::InvalidInput));
862        assert_eq!(at(600, Some(30), false), Ok(()), "offline, max_age does not apply");
863    }
864
865    use super::*;
866
867    fn usage(segid: SegmentId, bytes: u64, data: usize, meta: usize) -> ObjectUsage {
868        ObjectUsage {
869            segid,
870            bytes,
871            live_data_blocks: data,
872            live_meta_blocks: meta,
873            live_bytes: (data * 4096 + meta * 4096) as u64,
874            meta_moves_with_data: false,
875            extra_blocks: 0,
876            unfreeable_nodes: 0,
877            rewrite_bytes: (data * 4096 + meta * 4096) as u64,
878        }
879    }
880
881    #[test]
882    fn a_dead_object_is_pruned_not_compacted() {
883        let o = usage(SegmentId::new(1), 1 << 20, 0, 0);
884        assert!(o.is_dead());
885        assert!(!is_candidate(&o, 1.0), "nothing to rewrite frees nothing");
886    }
887
888    /// An object a live node sits in is a candidate: its node is rewritten by
889    /// relocating a block under it, counted in what freeing it costs.
890    #[test]
891    fn an_object_holding_metadata_is_a_candidate_at_its_cost() {
892        let o = usage(SegmentId::with_part(3, 0), 1 << 20, 1, 1);
893        assert!(o.holds_metadata());
894        assert!(is_candidate(&o, 1.0));
895        // 100 extra blocks for nodes over data elsewhere: 0.4 of 1 MiB over the
896        // live data's.
897        let costly = ObjectUsage { extra_blocks: 100, rewrite_bytes: o.rewrite_bytes + 100 * 4096, ..o.clone() };
898        assert!(costly.cost_ratio() > 0.39 && costly.live_ratio() < 0.01);
899        assert!(!is_candidate(&costly, 0.3), "the extra blocks are in its cost");
900        assert!(is_candidate(&costly, 0.5));
901    }
902
903    /// A node with no block on storage under it cannot be rewritten by a
904    /// compaction: its object is not a candidate.
905    #[test]
906    fn a_node_over_nothing_on_storage_keeps_its_object_out() {
907        let o = ObjectUsage { unfreeable_nodes: 1, ..usage(SegmentId::with_part(3, 0), 1 << 20, 1, 1) };
908        assert!(!is_candidate(&o, 1.0));
909    }
910
911    #[test]
912    fn the_ratio_is_a_ceiling() {
913        let low = usage(SegmentId::new(1), 4096 * 100, 5, 0);   // 5% live
914        let high = usage(SegmentId::new(2), 4096 * 100, 90, 0); // 90% live
915        assert!(is_candidate(&low, 0.5));
916        assert!(!is_candidate(&high, 0.5));
917        assert!(is_candidate(&high, 0.9));
918    }
919
920    /// Cheapest first, and the bigger object first among equals: the budget is
921    /// finite and the point is how much it buys.
922    #[test]
923    fn candidates_come_cheapest_first() {
924        let objects = vec![
925            usage(SegmentId::new(1), 4096 * 100, 40, 0), // 40%
926            usage(SegmentId::new(2), 4096 * 100, 5, 0),  // 5%
927            usage(SegmentId::new(3), 4096 * 200, 10, 0), // 5%, larger
928        ];
929        let picked = select_candidates(&objects, 0.5);
930        let order: Vec<SegmentId> = picked.iter().map(|o| o.segid).collect();
931        assert_eq!(order, vec![SegmentId::new(3), SegmentId::new(2), SegmentId::new(1)]);
932    }
933
934    #[test]
935    fn runs_are_maximal() {
936        assert_eq!(into_runs(&[]), vec![]);
937        assert_eq!(into_runs(&[7]), vec![(7, 1)]);
938        assert_eq!(into_runs(&[0, 1, 2, 5, 6, 9]), vec![(0, 3), (5, 2), (9, 1)]);
939    }
940
941    /// A pass takes objects whole and cheapest first, and stops at the first one
942    /// that does not fit rather than skipping to a smaller one: the cheapest work
943    /// is done first, and the pass says there is more.
944    #[test]
945    fn a_pass_takes_whole_objects_until_the_budget() {
946        let objects = vec![
947            usage(SegmentId::new(1), 4096 * 100, 10, 0), // 10%, 40 KiB live
948            usage(SegmentId::new(2), 4096 * 100, 20, 0), // 20%, 80 KiB live
949            usage(SegmentId::new(3), 4096 * 100, 1, 0),  //  1%,  4 KiB live
950        ];
951        let (picked, live, stored, more) = plan_pass(&objects, 0.5, 4096 * 15);
952        assert_eq!(picked.into_iter().collect::<Vec<_>>(),
953            vec![SegmentId::new(1), SegmentId::new(3)]);
954        assert_eq!(live, 4096 * 11);
955        assert_eq!(stored, 4096 * 200);
956        assert!(more, "object 2 did not fit and is still a candidate");
957
958        let (picked, _, _, more) = plan_pass(&objects, 0.5, u64::MAX);
959        assert_eq!(picked.len(), 3);
960        assert!(!more);
961    }
962
963    /// Where partials can be written, memory is bounded by the dirty-data limits
964    /// and only the caller's budget applies. Where they cannot, the pass is held
965    /// in memory whole and is capped; and a container that is not parted also has
966    /// to fit its pass in one object, as `hyperfile` reckons one — the caller's
967    /// `segment_max_object_bytes` included.
968    #[test]
969    fn the_pass_cap_follows_what_can_write_it_out() {
970        let big = u64::MAX;
971        let parts_on = compaction_runtime(None);
972        assert!(parts_on.parted_segment_enabled);
973        assert_eq!(pass_cap(big, &BlockPtrFormat::PartedSegment, &parts_on), big);
974
975        let parts_off = HyperFileRuntimeConfig { parted_segment_enabled: false, ..parts_on.clone() };
976        assert_eq!(pass_cap(big, &BlockPtrFormat::PartedSegment, &parts_off), UNBOUNDED_PASS_BYTES);
977
978        let mg = BlockPtrFormat::MicroGroup.max_object_bytes() as u64;
979        let cap = pass_cap(big, &BlockPtrFormat::MicroGroup, &parts_on);
980        assert!(cap < mg && cap <= UNBOUNDED_PASS_BYTES);
981
982        let small_objects = HyperFileRuntimeConfig {
983            segment_max_object_bytes: 1024 * 1024, ..parts_on.clone()
984        };
985        assert_eq!(pass_cap(big, &BlockPtrFormat::MicroGroup, &small_objects), 1024 * 1024 / 4 * 3,
986            "the caller's object size is what hyperfile refuses past");
987        assert_eq!(pass_cap(4096, &BlockPtrFormat::MicroGroup, &parts_on), 4096,
988            "a smaller budget is kept as given");
989    }
990
991    /// The caller's configuration is used as given, except for the conflict
992    /// policy, which a compactor cannot leave at retry-and-overwrite.
993    #[test]
994    fn a_given_runtime_is_kept_but_for_the_conflict_policy() {
995        use hyperfile::config::FlushConflictPolicy;
996        let given = HyperFileRuntimeConfig {
997            data_cache_dirty_min_bytes_to_part: 16 * 1024 * 1024,
998            data_cache_dirty_max_bytes_threshold: 16 * 1024 * 1024,
999            segment_mpu_chunk_size: 16 * 1024 * 1024,
1000            flush_conflict_policy: FlushConflictPolicy::RetryLastWriterWins,
1001            ..HyperFileRuntimeConfig::default()
1002        };
1003        let used = compaction_runtime(Some(&given));
1004        assert_eq!(used.flush_conflict_policy, FlushConflictPolicy::FailFast);
1005        assert_eq!(HyperFileRuntimeConfig {
1006            flush_conflict_policy: FlushConflictPolicy::RetryLastWriterWins, ..used
1007        }, given);
1008        assert_eq!(compaction_runtime(None).flush_conflict_policy, FlushConflictPolicy::FailFast);
1009    }
1010
1011    /// An object whose live data alone is over the budget is never taken, and
1012    /// the pass reports that it left work behind instead of doing nothing quietly.
1013    #[test]
1014    fn an_object_larger_than_the_budget_is_reported_not_split() {
1015        let objects = vec![usage(SegmentId::new(1), 4096 * 1000, 100, 0)];
1016        let (picked, live, _, more) = plan_pass(&objects, 0.5, 4096 * 10);
1017        assert!(picked.is_empty());
1018        assert_eq!(live, 0);
1019        assert!(more);
1020    }
1021
1022    /// `compactable` must answer from the same rule the pass selects by,
1023    /// otherwise a dry run and the pass disagree about what will happen.
1024    #[test]
1025    fn the_estimate_agrees_with_the_selection() {
1026        let report = Report {
1027            high_cno: 9,
1028            latest_compacted: false,
1029            attached: Default::default(),
1030            data_block_size: 4096,
1031            meta_block_size: 4096,
1032            objects: vec![
1033                usage(SegmentId::new(1), 4096 * 100, 5, 0),
1034                usage(SegmentId::new(2), 4096 * 100, 80, 0),
1035                usage(SegmentId::new(3), 4096 * 100, 0, 0),
1036                usage(SegmentId::new(4), 4096 * 100, 2, 3),
1037            ],
1038            out_of_range: 0,
1039            foreign_keys: 0,
1040            foreign_sample: None,
1041        };
1042        let (n, rewrite, freed) = report.compactable(0.5);
1043        assert_eq!(n, 2, "the 5% object and the 5% one holding nodes qualify");
1044        assert_eq!(rewrite, (5 + 2 + 3) * 4096);
1045        assert_eq!(freed, 2 * 4096 * 100);
1046        assert_eq!(report.dead(), (1, 4096 * 100));
1047        let picked = select_candidates(&report.objects, CompactOptions::default().max_live_ratio);
1048        assert_eq!(picked.len(), n);
1049    }
1050}