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. A pass is one checkpoint, so this is
187 /// also what it holds dirty in memory until the flush — `fs_relocate` does not
188 /// write anything out on its own. Objects are taken whole and cheapest first
189 /// until the next would pass this; what is left waits for the next pass.
190 ///
191 /// On a container that is not in the parted format a checkpoint is one object,
192 /// so a pass is further capped at what one object can hold.
193 pub max_pass_bytes: u64,
194 /// How many bytes of blocks to hand `fs_relocate` at once. It holds what it
195 /// reads in a buffer of its own before the dirty cache takes it, so this bounds
196 /// that second copy.
197 pub relocate_chunk_bytes: usize,
198 /// Select and report, write nothing. No file is opened.
199 pub dry_run: bool,
200 /// Run even though the newest checkpoint is already a compaction. The flag that
201 /// keeps `content_cno` still holds for one checkpoint only, so a second pass in
202 /// a row is seen by consumers as a change of content. Set this when that is
203 /// acceptable, for example to finish a container larger than one pass.
204 pub allow_consecutive: bool,
205 /// Run even though the prefix holds keys this crate does not recognize. Only
206 /// set this having established that they are not a WAL.
207 pub allow_foreign_keys: bool,
208}
209
210impl Default for CompactOptions {
211 fn default() -> Self {
212 Self {
213 max_live_ratio: 0.5,
214 max_pass_bytes: 512 * 1024 * 1024,
215 relocate_chunk_bytes: 64 * 1024 * 1024,
216 dry_run: false,
217 allow_consecutive: false,
218 allow_foreign_keys: false,
219 }
220 }
221}
222
223/// What a compaction pass did.
224#[derive(Clone, Debug, Default)]
225pub struct CompactOutcome {
226 /// The objects whose live blocks were rewritten, ascending.
227 pub selected: Vec<SegmentId>,
228 /// Of those, the ones a walk taken afterwards still finds referenced. Empty
229 /// on a pass that did what it set out to; anything here is an object that was
230 /// not freed, and is reported rather than assumed away.
231 pub still_referenced: Vec<SegmentId>,
232 /// Blocks `fs_relocate` marked: what was done, not what was planned. A hole,
233 /// an explicit zero block or a block already dirty is not counted.
234 pub blocks_rewritten: usize,
235 pub bytes_rewritten: u64,
236 /// The selected objects' stored bytes — what `prune` can now reclaim.
237 pub bytes_freed: u64,
238 /// Checkpoints published: one for a pass that rewrote anything, none
239 /// otherwise. That is how far `last_cno` advanced.
240 pub checkpoints: usize,
241 /// `fs_content_cno` before and after the pass. Equal when consumers will not
242 /// see the pass as a change of content, which is the ordinary case. They
243 /// differ when the publish could not be marked: its number did not follow the
244 /// previous one — an earlier flush failed and gave its number up — or the
245 /// newest checkpoint was already a compaction and the pass ran anyway.
246 pub content_cno_before: Cno,
247 pub content_cno_after: Cno,
248 /// Whether the candidates outlasted the pass budget. Another pass would find
249 /// more to do, at the cost of `content_cno` moving once (see
250 /// [`CompactOptions::allow_consecutive`]).
251 pub more_remaining: bool,
252 pub dry_run: bool,
253}
254
255impl CompactOutcome {
256 /// Whether a consumer comparing `content_cno` will see this pass as a change.
257 pub fn content_moved(&self) -> bool {
258 self.content_cno_before != self.content_cno_after
259 }
260}
261
262impl S3Cleaner {
263 /// What the container's storage is made of: per-object liveness for every
264 /// object whose checkpoint falls in `[low, high]`.
265 ///
266 /// Read-only, and the same walk `collect` does plus one `ListObjectsV2` for
267 /// sizes. `high == 0` means the latest published checkpoint.
268 pub async fn report(&self, low: Cno, high: Cno) -> Result<Report> {
269 let view = self.view(low, high).await?;
270 Ok(build_report(&view))
271 }
272
273 /// Rewrite the live blocks of mostly-dead objects so `prune` can reclaim
274 /// them.
275 ///
276 /// The caller must be the container's only writer for the duration; see the
277 /// [module docs](self) for why that is not a nicety. Nothing is deleted here
278 /// — a compaction makes objects reclaimable and `prune` reclaims them, which
279 /// keeps the destructive step in one place.
280 pub async fn compact(
281 &self,
282 low: Cno,
283 high: Cno,
284 opts: &CompactOptions,
285 ) -> Result<CompactOutcome> {
286 let view = self.view(low, high).await?;
287 if view.listing.foreign > 0 && !opts.allow_foreign_keys {
288 return Err(Error::new(
289 ErrorKind::InvalidInput,
290 format!(
291 "{} key(s) under the container's prefix are neither the inode nor \
292 segment objects (for example {:?}); a WAL is the usual reason, and \
293 compacting past a log this pass does not read would publish over \
294 entries recovery has not replayed. Set allow_foreign_keys once you \
295 have established otherwise",
296 view.listing.foreign,
297 view.listing.foreign_sample.as_deref().unwrap_or("?"),
298 ),
299 ));
300 }
301
302 if view.latest_compacted && !opts.allow_consecutive && !opts.dry_run {
303 return Err(Error::new(
304 ErrorKind::InvalidInput,
305 format!(
306 "checkpoint {} is already a compaction, and the flag that keeps \
307 content_cno still holds for one checkpoint only: a second pass in a \
308 row would be seen by consumers as a change of content. Write to the \
309 file first, or set allow_consecutive",
310 view.high_cno,
311 ),
312 ));
313 }
314
315 let report = build_report(&view);
316 let pass_cap = pass_cap(opts.max_pass_bytes, &view.fmt);
317 let (selected, bytes_planned, bytes_freed, more_remaining) =
318 plan_pass(&report.objects, opts.max_live_ratio, pass_cap);
319 debug!("compact: {} object(s) selected of {} in range, {} live bytes (cap {})",
320 selected.len(), report.objects.len(), bytes_planned, pass_cap);
321
322 let mut outcome = CompactOutcome {
323 selected: selected.iter().copied().collect(),
324 bytes_freed,
325 more_remaining,
326 dry_run: opts.dry_run,
327 ..Default::default()
328 };
329 if opts.dry_run {
330 // The plan's own numbers, which is all a dry run can report: nothing
331 // is opened, so nothing can be counted as done.
332 outcome.blocks_rewritten =
333 (bytes_planned / view.data_block_size.max(1) as u64) as usize;
334 outcome.bytes_rewritten = bytes_planned;
335 return Ok(outcome);
336 }
337
338 let config = compaction_config(&self.root_uri(), bytes_planned, &view);
339 let mut file = Hyper::open(
340 self.client().clone(), config, HyperFileFlags::from_flags(FileFlags::rdwr()),
341 ).await?;
342 let result = self.relocate_and_publish(&mut file, &view, &selected, opts,
343 &mut outcome).await;
344 let _ = file.fs_release().await;
345 result?;
346 if outcome.checkpoints == 0 {
347 return Ok(outcome);
348 }
349
350 // Say what was actually freed rather than what should have been. A
351 // selected object that is still referenced means a block was not
352 // relocated, which is worth reporting where it can be seen.
353 let after = self.view(low, 0).await?;
354 let referenced = after.referenced_objects();
355 outcome.still_referenced = outcome.selected.iter()
356 .filter(|segid| referenced.contains(segid))
357 .copied()
358 .collect();
359 if !outcome.still_referenced.is_empty() {
360 warn!("compact: {} of {} selected object(s) are still referenced: {:?}",
361 outcome.still_referenced.len(), outcome.selected.len(),
362 outcome.still_referenced);
363 }
364 if outcome.content_moved() {
365 warn!("compact: content_cno moved {} -> {}; consumers will see this pass \
366 as a change of content", outcome.content_cno_before,
367 outcome.content_cno_after);
368 }
369 info!("compact: rewrote {} block(s) ({} bytes) in {} checkpoint(s), freeing {} bytes \
370 across {} object(s)", outcome.blocks_rewritten, outcome.bytes_rewritten,
371 outcome.checkpoints, outcome.bytes_freed, outcome.selected.len());
372 Ok(outcome)
373 }
374
375 /// Mark every block of the selected objects for relocation, then publish once.
376 async fn relocate_and_publish(
377 &self,
378 file: &mut Hyper<'static>,
379 view: &ContainerView,
380 selected: &BTreeSet<SegmentId>,
381 opts: &CompactOptions,
382 outcome: &mut CompactOutcome,
383 ) -> Result<()> {
384 outcome.content_cno_before = file.fs_content_cno()?;
385 outcome.content_cno_after = outcome.content_cno_before;
386 if selected.is_empty() {
387 return Ok(());
388 }
389 let bs = view.data_block_size;
390 let chunk_blocks = (opts.relocate_chunk_bytes / bs.max(1)).max(1);
391
392 // Which blocks are in the selected objects. `block_placement` answers
393 // exactly that, per index, from the live map — so it needs no agreement
394 // with a second reading of the container's layout. It is asked only about
395 // the windows the walk found mapped blocks in, never about the holes
396 // between them. Runs go to `fs_relocate` in index order, which is also
397 // the order the flush writes them in.
398 let mut pending: Vec<BlockIndex> = Vec::new();
399 for (start, n) in view.live.windows.iter().copied() {
400 let places = file.fs_block_placement(start, n).await?;
401 for (i, place) in places.iter().enumerate() {
402 if let Some((segid, _)) = place
403 && selected.contains(segid)
404 {
405 pending.push(start + i as BlockIndex);
406 if pending.len() >= chunk_blocks {
407 outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
408 pending.clear();
409 }
410 }
411 }
412 }
413 if !pending.is_empty() {
414 outcome.blocks_rewritten += relocate_runs(file, &pending).await?;
415 }
416 outcome.bytes_rewritten = (outcome.blocks_rewritten * bs) as u64;
417 if outcome.blocks_rewritten == 0 {
418 return Ok(());
419 }
420
421 let cno = file.fs_flush().await?;
422 outcome.checkpoints = 1;
423 outcome.content_cno_after = file.fs_content_cno()?;
424 debug!("compact: published checkpoint {} with {} relocated block(s); content_cno \
425 {} -> {}", cno, outcome.blocks_rewritten, outcome.content_cno_before,
426 outcome.content_cno_after);
427 Ok(())
428 }
429}
430
431/// Hand `indices` to `fs_relocate` as runs of consecutive blocks.
432async fn relocate_runs(file: &mut Hyper<'static>, indices: &[BlockIndex]) -> Result<usize> {
433 let runs = into_runs(indices);
434 let marked = file.fs_relocate(&runs).await?;
435 debug!("compact: relocate {} block(s) in {} run(s) marked {}",
436 indices.len(), runs.len(), marked);
437 Ok(marked)
438}
439
440/// What one pass may rewrite: the caller's budget, and on a container that is not
441/// parted, what one object can hold. Under any other format a checkpoint is one
442/// object, and `hyperfile` refuses a flush larger than that. Room is left for the
443/// summary and the index nodes the same object carries.
444fn pass_cap(max_pass_bytes: u64, fmt: &BlockPtrFormat) -> u64 {
445 if fmt.is_parted() {
446 return max_pass_bytes;
447 }
448 let one_object = fmt.max_object_bytes() as u64;
449 max_pass_bytes.min(one_object / 4 * 3)
450}
451
452/// Candidates, cheapest first, taken whole while they fit `cap`.
453///
454/// Returns `(selected, live_bytes, stored_bytes, more_remaining)`. An object is
455/// never split across passes: one that does not fit ends the selection, so the
456/// cheapest work is done first and nothing is half-moved.
457fn plan_pass(
458 objects: &[ObjectUsage],
459 max_live_ratio: f64,
460 cap: u64,
461) -> (BTreeSet<SegmentId>, u64, u64, bool) {
462 let mut selected = BTreeSet::new();
463 let mut live = 0u64;
464 let mut stored = 0u64;
465 let candidates = select_candidates(objects, max_live_ratio);
466 let total = candidates.len();
467 for usage in candidates {
468 if live.saturating_add(usage.live_bytes) > cap {
469 break;
470 }
471 live += usage.live_bytes;
472 stored += usage.bytes;
473 selected.insert(usage.segid);
474 }
475 let more = selected.len() < total;
476 (selected, live, stored, more)
477}
478
479/// Per-object liveness, from one view.
480///
481/// A location's size depends on what it holds, and a pointer does not say: a
482/// metadata node is `meta_block_size` and a data block is `data_block_size`. The
483/// metadata subset of the walk is what separates them.
484pub(crate) fn build_report(view: &ContainerView) -> Report {
485 let mut live_data: BTreeMap<SegmentId, usize> = BTreeMap::new();
486 let mut live_meta: BTreeMap<SegmentId, usize> = BTreeMap::new();
487 for blkptr in &view.live.all {
488 let segid = view.object_of(blkptr);
489 if view.live.meta.contains(blkptr) {
490 *live_meta.entry(segid).or_default() += 1;
491 } else {
492 *live_data.entry(segid).or_default() += 1;
493 }
494 }
495
496 let mut objects = Vec::new();
497 let mut out_of_range = 0;
498 for (segid, bytes) in &view.listing.objects {
499 let cno = segid.as_cno();
500 if cno < view.low || cno > view.high_cno {
501 out_of_range += 1;
502 continue;
503 }
504 let live_data_blocks = live_data.get(segid).copied().unwrap_or(0);
505 let live_meta_blocks = live_meta.get(segid).copied().unwrap_or(0);
506 objects.push(ObjectUsage {
507 segid: *segid,
508 bytes: *bytes,
509 live_data_blocks,
510 live_meta_blocks,
511 live_bytes: (live_data_blocks * view.data_block_size
512 + live_meta_blocks * view.meta_block_size) as u64,
513 });
514 }
515
516 Report {
517 high_cno: view.high_cno,
518 latest_compacted: view.latest_compacted,
519 data_block_size: view.data_block_size,
520 meta_block_size: view.meta_block_size,
521 objects,
522 out_of_range,
523 foreign_keys: view.listing.foreign,
524 foreign_sample: view.listing.foreign_sample.clone(),
525 }
526}
527
528/// Whether rewriting this object's live data would free it.
529///
530/// Three exclusions, each for its own reason: a dead object is `prune`'s work and
531/// rewriting nothing frees nothing; an object holding a live metadata node cannot
532/// be freed by rewriting data blocks, so its data would be rewritten for no
533/// return; and one above the ratio costs more to rewrite than the policy accepts.
534fn is_candidate(usage: &ObjectUsage, max_live_ratio: f64) -> bool {
535 !usage.is_dead()
536 && !usage.holds_metadata()
537 && usage.live_ratio() <= max_live_ratio
538}
539
540/// Candidates, cheapest first.
541///
542/// Ordered by live ratio ascending, which is the same as bytes freed per byte
543/// rewritten descending, with the larger object first among equals so a budget
544/// spent early buys more.
545fn select_candidates(
546 objects: &[ObjectUsage],
547 max_live_ratio: f64,
548) -> Vec<&ObjectUsage> {
549 let mut picked: Vec<&ObjectUsage> = objects.iter()
550 .filter(|o| is_candidate(o, max_live_ratio))
551 .collect();
552 picked.sort_by(|a, b| {
553 a.live_ratio().total_cmp(&b.live_ratio())
554 .then(b.bytes.cmp(&a.bytes))
555 .then(a.segid.cmp(&b.segid))
556 });
557 picked
558}
559
560/// Consecutive indices, as `(first, count)`.
561///
562/// What `read_ahead` wants: it takes a byte range and plans it the way a read of
563/// the same range would, so one call per run of adjacent blocks turns into a few
564/// large requests. Asking per block instead would be one request per block, which
565/// for scattered blocks it will be anyway.
566fn into_runs(indices: &[BlockIndex]) -> Vec<(BlockIndex, usize)> {
567 let mut runs: Vec<(BlockIndex, usize)> = Vec::new();
568 for idx in indices {
569 match runs.last_mut() {
570 Some((start, count)) if *start + *count as BlockIndex == *idx => *count += 1,
571 _ => runs.push((*idx, 1)),
572 }
573 }
574 runs
575}
576
577/// The configuration a compacting handle needs, and why each field is not the
578/// default.
579fn compaction_config(root_uri: &str, pass_bytes: u64, view: &ContainerView) -> HyperFileConfig {
580 let staging = StagingConfig::new_s3_uri(root_uri, None);
581 // Nothing may publish before the pass is complete. `fs_relocate` does not
582 // check the thresholds itself, but the flush interval is checked on the
583 // flush path, and a pass that crossed a threshold would be cut in two —
584 // which moves `last_cno` twice and leaves `content_cno` marked for only the
585 // second. Both thresholds and the segment buffer go above the pass.
586 let room = (pass_bytes as usize)
587 .saturating_add(view.data_block_size)
588 .saturating_mul(2)
589 .max(16 * 1024 * 1024);
590 let runtime = HyperFileRuntimeConfig {
591 data_cache_dirty_max_bytes_threshold: room,
592 data_cache_dirty_max_blocks_threshold: room / view.data_block_size.max(1),
593 segment_buffer_size: room,
594 data_cache_dirty_max_flush_interval: 3_600_000,
595 // A compactor writes bytes it read earlier. Refreshing and re-publishing
596 // on a conflict, which is what the default does, would republish a stale
597 // copy over another writer's newer one.
598 flush_conflict_policy: FlushConflictPolicy::FailFast,
599 ..HyperFileRuntimeConfig::default()
600 };
601 HyperFileConfigBuilder::new()
602 .with_staging_config(&staging)
603 .with_runtime_config(&runtime)
604 .build()
605}
606
607#[cfg(test)]
608mod tests {
609 use super::*;
610
611 fn usage(segid: SegmentId, bytes: u64, data: usize, meta: usize) -> ObjectUsage {
612 ObjectUsage {
613 segid,
614 bytes,
615 live_data_blocks: data,
616 live_meta_blocks: meta,
617 live_bytes: (data * 4096 + meta * 4096) as u64,
618 }
619 }
620
621 #[test]
622 fn a_dead_object_is_pruned_not_compacted() {
623 let o = usage(SegmentId::new(1), 1 << 20, 0, 0);
624 assert!(o.is_dead());
625 assert!(!is_candidate(&o, 1.0), "nothing to rewrite frees nothing");
626 }
627
628 /// An object a live metadata node sits in cannot be freed by rewriting data
629 /// blocks: which keys that node covers is not visible from out here, so
630 /// nothing this crate can do will relocate it.
631 #[test]
632 fn an_object_holding_metadata_is_not_a_candidate() {
633 let o = usage(SegmentId::with_part(3, 0), 1 << 20, 1, 1);
634 assert!(o.holds_metadata());
635 assert!(!is_candidate(&o, 1.0));
636 }
637
638 #[test]
639 fn the_ratio_is_a_ceiling() {
640 let low = usage(SegmentId::new(1), 4096 * 100, 5, 0); // 5% live
641 let high = usage(SegmentId::new(2), 4096 * 100, 90, 0); // 90% live
642 assert!(is_candidate(&low, 0.5));
643 assert!(!is_candidate(&high, 0.5));
644 assert!(is_candidate(&high, 0.9));
645 }
646
647 /// Cheapest first, and the bigger object first among equals: the budget is
648 /// finite and the point is how much it buys.
649 #[test]
650 fn candidates_come_cheapest_first() {
651 let objects = vec![
652 usage(SegmentId::new(1), 4096 * 100, 40, 0), // 40%
653 usage(SegmentId::new(2), 4096 * 100, 5, 0), // 5%
654 usage(SegmentId::new(3), 4096 * 200, 10, 0), // 5%, larger
655 ];
656 let picked = select_candidates(&objects, 0.5);
657 let order: Vec<SegmentId> = picked.iter().map(|o| o.segid).collect();
658 assert_eq!(order, vec![SegmentId::new(3), SegmentId::new(2), SegmentId::new(1)]);
659 }
660
661 #[test]
662 fn runs_are_maximal() {
663 assert_eq!(into_runs(&[]), vec![]);
664 assert_eq!(into_runs(&[7]), vec![(7, 1)]);
665 assert_eq!(into_runs(&[0, 1, 2, 5, 6, 9]), vec![(0, 3), (5, 2), (9, 1)]);
666 }
667
668 /// A pass takes objects whole and cheapest first, and stops at the first one
669 /// that does not fit rather than skipping to a smaller one: the cheapest work
670 /// is done first, and the pass says there is more.
671 #[test]
672 fn a_pass_takes_whole_objects_until_the_budget() {
673 let objects = vec![
674 usage(SegmentId::new(1), 4096 * 100, 10, 0), // 10%, 40 KiB live
675 usage(SegmentId::new(2), 4096 * 100, 20, 0), // 20%, 80 KiB live
676 usage(SegmentId::new(3), 4096 * 100, 1, 0), // 1%, 4 KiB live
677 ];
678 let (picked, live, stored, more) = plan_pass(&objects, 0.5, 4096 * 15);
679 assert_eq!(picked.into_iter().collect::<Vec<_>>(),
680 vec![SegmentId::new(1), SegmentId::new(3)]);
681 assert_eq!(live, 4096 * 11);
682 assert_eq!(stored, 4096 * 200);
683 assert!(more, "object 2 did not fit and is still a candidate");
684
685 let (picked, _, _, more) = plan_pass(&objects, 0.5, u64::MAX);
686 assert_eq!(picked.len(), 3);
687 assert!(!more);
688 }
689
690 /// A parted container splits a large checkpoint into several objects, so only
691 /// the caller's budget applies. Any other format writes a checkpoint as one
692 /// object and refuses a flush past it, so the pass has to fit one, with room
693 /// for what else that object carries.
694 #[test]
695 fn an_unparted_pass_fits_one_object() {
696 let big = u64::MAX;
697 assert_eq!(pass_cap(big, &BlockPtrFormat::PartedSegment), big);
698 let mg = BlockPtrFormat::MicroGroup.max_object_bytes() as u64;
699 assert!(pass_cap(big, &BlockPtrFormat::MicroGroup) < mg);
700 assert!(pass_cap(big, &BlockPtrFormat::MicroGroup) >= mg / 2);
701 assert_eq!(pass_cap(4096, &BlockPtrFormat::MicroGroup), 4096,
702 "a smaller budget is kept as given");
703 }
704
705 /// An object whose live data alone is over the budget is never taken, and
706 /// the pass reports that it left work behind instead of doing nothing quietly.
707 #[test]
708 fn an_object_larger_than_the_budget_is_reported_not_split() {
709 let objects = vec![usage(SegmentId::new(1), 4096 * 1000, 100, 0)];
710 let (picked, live, _, more) = plan_pass(&objects, 0.5, 4096 * 10);
711 assert!(picked.is_empty());
712 assert_eq!(live, 0);
713 assert!(more);
714 }
715
716 /// `compactable` must answer from the same rule the pass selects by,
717 /// otherwise a dry run and the pass disagree about what will happen.
718 #[test]
719 fn the_estimate_agrees_with_the_selection() {
720 let report = Report {
721 high_cno: 9,
722 latest_compacted: false,
723 data_block_size: 4096,
724 meta_block_size: 4096,
725 objects: vec![
726 usage(SegmentId::new(1), 4096 * 100, 5, 0),
727 usage(SegmentId::new(2), 4096 * 100, 80, 0),
728 usage(SegmentId::new(3), 4096 * 100, 0, 0),
729 usage(SegmentId::new(4), 4096 * 100, 2, 3),
730 ],
731 out_of_range: 0,
732 foreign_keys: 0,
733 foreign_sample: None,
734 };
735 let (n, rewrite, freed) = report.compactable(0.5);
736 assert_eq!(n, 1, "only the 5% object qualifies");
737 assert_eq!(rewrite, 5 * 4096);
738 assert_eq!(freed, 4096 * 100);
739 assert_eq!(report.dead(), (1, 4096 * 100));
740 let picked = select_candidates(&report.objects, CompactOptions::default().max_live_ratio);
741 assert_eq!(picked.len(), n);
742 }
743}