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