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