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