Line data Source code
1 : //! New compaction implementation. The algorithm itself is implemented in the
2 : //! compaction crate. This file implements the callbacks and structs that allow
3 : //! the algorithm to drive the process.
4 : //!
5 : //! The old legacy algorithm is implemented directly in `timeline.rs`.
6 :
7 : use std::cmp::min;
8 : use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
9 : use std::ops::{Deref, Range};
10 : use std::sync::Arc;
11 : use std::time::{Duration, Instant};
12 :
13 : use super::layer_manager::LayerManagerLockHolder;
14 : use super::{
15 : CompactFlags, CompactOptions, CompactionError, CreateImageLayersError, DurationRecorder,
16 : GetVectoredError, ImageLayerCreationMode, LastImageLayerCreationStatus, RecordedDuration,
17 : Timeline,
18 : };
19 :
20 : use crate::pgdatadir_mapping::CollectKeySpaceError;
21 : use crate::tenant::timeline::{DeltaEntry, RepartitionError};
22 : use crate::walredo::RedoAttemptType;
23 : use anyhow::{Context, anyhow};
24 : use bytes::Bytes;
25 : use enumset::EnumSet;
26 : use fail::fail_point;
27 : use futures::FutureExt;
28 : use itertools::Itertools;
29 : use once_cell::sync::Lazy;
30 : use pageserver_api::config::tenant_conf_defaults::DEFAULT_CHECKPOINT_DISTANCE;
31 : use pageserver_api::key::{KEY_SIZE, Key};
32 : use pageserver_api::keyspace::{KeySpace, ShardedRange};
33 : use pageserver_api::models::{CompactInfoResponse, CompactKeyRange};
34 : use pageserver_api::shard::{ShardCount, ShardIdentity, TenantShardId};
35 : use pageserver_compaction::helpers::{fully_contains, overlaps_with};
36 : use pageserver_compaction::interface::*;
37 : use serde::Serialize;
38 : use tokio::sync::{OwnedSemaphorePermit, Semaphore};
39 : use tokio_util::sync::CancellationToken;
40 : use tracing::{Instrument, debug, error, info, info_span, trace, warn};
41 : use utils::critical_timeline;
42 : use utils::id::TimelineId;
43 : use utils::lsn::Lsn;
44 : use wal_decoder::models::record::NeonWalRecord;
45 : use wal_decoder::models::value::Value;
46 :
47 : use crate::context::{AccessStatsBehavior, RequestContext, RequestContextBuilder};
48 : use crate::page_cache;
49 : use crate::statvfs::Statvfs;
50 : use crate::tenant::checks::check_valid_layermap;
51 : use crate::tenant::gc_block::GcBlock;
52 : use crate::tenant::layer_map::LayerMap;
53 : use crate::tenant::remote_timeline_client::WaitCompletionError;
54 : use crate::tenant::remote_timeline_client::index::GcCompactionState;
55 : use crate::tenant::storage_layer::batch_split_writer::{
56 : BatchWriterResult, SplitDeltaLayerWriter, SplitImageLayerWriter,
57 : };
58 : use crate::tenant::storage_layer::filter_iterator::FilterIterator;
59 : use crate::tenant::storage_layer::merge_iterator::MergeIterator;
60 : use crate::tenant::storage_layer::{
61 : AsLayerDesc, LayerVisibilityHint, PersistentLayerDesc, PersistentLayerKey,
62 : ValueReconstructState,
63 : };
64 : use crate::tenant::tasks::log_compaction_error;
65 : use crate::tenant::timeline::{
66 : DeltaLayerWriter, ImageLayerCreationOutcome, ImageLayerWriter, IoConcurrency, Layer,
67 : ResidentLayer, drop_layer_manager_rlock,
68 : };
69 : use crate::tenant::{DeltaLayer, MaybeOffloaded, PageReconstructError};
70 : use crate::virtual_file::{MaybeFatalIo, VirtualFile};
71 :
72 : /// Maximum number of deltas before generating an image layer in bottom-most compaction.
73 : const COMPACTION_DELTA_THRESHOLD: usize = 5;
74 :
75 : /// Ratio of shard-local pages below which we trigger shard ancestor layer rewrites. 0.3 means that
76 : /// <= 30% of layer pages must belong to the descendant shard to rewrite the layer.
77 : ///
78 : /// We choose a value < 0.5 to avoid rewriting all visible layers every time we do a power-of-two
79 : /// shard split, which gets expensive for large tenants.
80 : const ANCESTOR_COMPACTION_REWRITE_THRESHOLD: f64 = 0.3;
81 :
82 : #[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize)]
83 : pub struct GcCompactionJobId(pub usize);
84 :
85 : impl std::fmt::Display for GcCompactionJobId {
86 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 0 : write!(f, "{}", self.0)
88 0 : }
89 : }
90 :
91 : pub struct GcCompactionCombinedSettings {
92 : pub gc_compaction_enabled: bool,
93 : pub gc_compaction_verification: bool,
94 : pub gc_compaction_initial_threshold_kb: u64,
95 : pub gc_compaction_ratio_percent: u64,
96 : }
97 :
98 : #[derive(Debug, Clone)]
99 : pub enum GcCompactionQueueItem {
100 : MetaJob {
101 : /// Compaction options
102 : options: CompactOptions,
103 : /// Whether the compaction is triggered automatically (determines whether we need to update L2 LSN)
104 : auto: bool,
105 : },
106 : SubCompactionJob {
107 : i: usize,
108 : total: usize,
109 : options: CompactOptions,
110 : },
111 : Notify(GcCompactionJobId, Option<Lsn>),
112 : }
113 :
114 : /// Statistics for gc-compaction meta jobs, which contains several sub compaction jobs.
115 : #[derive(Debug, Clone, Serialize, Default)]
116 : pub struct GcCompactionMetaStatistics {
117 : /// The total number of sub compaction jobs.
118 : pub total_sub_compaction_jobs: usize,
119 : /// The total number of sub compaction jobs that failed.
120 : pub failed_sub_compaction_jobs: usize,
121 : /// The total number of sub compaction jobs that succeeded.
122 : pub succeeded_sub_compaction_jobs: usize,
123 : /// The layer size before compaction.
124 : pub before_compaction_layer_size: u64,
125 : /// The layer size after compaction.
126 : pub after_compaction_layer_size: u64,
127 : /// The start time of the meta job.
128 : pub start_time: Option<chrono::DateTime<chrono::Utc>>,
129 : /// The end time of the meta job.
130 : pub end_time: Option<chrono::DateTime<chrono::Utc>>,
131 : /// The duration of the meta job.
132 : pub duration_secs: f64,
133 : /// The id of the meta job.
134 : pub meta_job_id: GcCompactionJobId,
135 : /// The LSN below which the layers are compacted, used to compute the statistics.
136 : pub below_lsn: Lsn,
137 : /// The retention ratio of the meta job (after_compaction_layer_size / before_compaction_layer_size)
138 : pub retention_ratio: f64,
139 : }
140 :
141 : impl GcCompactionMetaStatistics {
142 0 : fn finalize(&mut self) {
143 0 : let end_time = chrono::Utc::now();
144 0 : if let Some(start_time) = self.start_time {
145 0 : if end_time > start_time {
146 0 : let delta = end_time - start_time;
147 0 : if let Ok(std_dur) = delta.to_std() {
148 0 : self.duration_secs = std_dur.as_secs_f64();
149 0 : }
150 0 : }
151 0 : }
152 0 : self.retention_ratio = self.after_compaction_layer_size as f64
153 0 : / (self.before_compaction_layer_size as f64 + 1.0);
154 0 : self.end_time = Some(end_time);
155 0 : }
156 : }
157 :
158 : impl GcCompactionQueueItem {
159 0 : pub fn into_compact_info_resp(
160 0 : self,
161 0 : id: GcCompactionJobId,
162 0 : running: bool,
163 0 : ) -> Option<CompactInfoResponse> {
164 0 : match self {
165 0 : GcCompactionQueueItem::MetaJob { options, .. } => Some(CompactInfoResponse {
166 0 : compact_key_range: options.compact_key_range,
167 0 : compact_lsn_range: options.compact_lsn_range,
168 0 : sub_compaction: options.sub_compaction,
169 0 : running,
170 0 : job_id: id.0,
171 0 : }),
172 0 : GcCompactionQueueItem::SubCompactionJob { options, .. } => Some(CompactInfoResponse {
173 0 : compact_key_range: options.compact_key_range,
174 0 : compact_lsn_range: options.compact_lsn_range,
175 0 : sub_compaction: options.sub_compaction,
176 0 : running,
177 0 : job_id: id.0,
178 0 : }),
179 0 : GcCompactionQueueItem::Notify(_, _) => None,
180 : }
181 0 : }
182 : }
183 :
184 : #[derive(Default)]
185 : struct GcCompactionGuardItems {
186 : notify: Option<tokio::sync::oneshot::Sender<()>>,
187 : permit: Option<OwnedSemaphorePermit>,
188 : }
189 :
190 : struct GcCompactionQueueInner {
191 : running: Option<(GcCompactionJobId, GcCompactionQueueItem)>,
192 : queued: VecDeque<(GcCompactionJobId, GcCompactionQueueItem)>,
193 : guards: HashMap<GcCompactionJobId, GcCompactionGuardItems>,
194 : last_id: GcCompactionJobId,
195 : meta_statistics: Option<GcCompactionMetaStatistics>,
196 : }
197 :
198 : impl GcCompactionQueueInner {
199 0 : fn next_id(&mut self) -> GcCompactionJobId {
200 0 : let id = self.last_id;
201 0 : self.last_id = GcCompactionJobId(id.0 + 1);
202 0 : id
203 0 : }
204 : }
205 :
206 : /// A structure to store gc_compaction jobs.
207 : pub struct GcCompactionQueue {
208 : /// All items in the queue, and the currently-running job.
209 : inner: std::sync::Mutex<GcCompactionQueueInner>,
210 : /// Ensure only one thread is consuming the queue.
211 : consumer_lock: tokio::sync::Mutex<()>,
212 : }
213 :
214 0 : static CONCURRENT_GC_COMPACTION_TASKS: Lazy<Arc<Semaphore>> = Lazy::new(|| {
215 : // Only allow one timeline on one pageserver to run gc compaction at a time.
216 0 : Arc::new(Semaphore::new(1))
217 0 : });
218 :
219 : impl GcCompactionQueue {
220 0 : pub fn new() -> Self {
221 0 : GcCompactionQueue {
222 0 : inner: std::sync::Mutex::new(GcCompactionQueueInner {
223 0 : running: None,
224 0 : queued: VecDeque::new(),
225 0 : guards: HashMap::new(),
226 0 : last_id: GcCompactionJobId(0),
227 0 : meta_statistics: None,
228 0 : }),
229 0 : consumer_lock: tokio::sync::Mutex::new(()),
230 0 : }
231 0 : }
232 :
233 0 : pub fn cancel_scheduled(&self) {
234 0 : let mut guard = self.inner.lock().unwrap();
235 0 : guard.queued.clear();
236 : // TODO: if there is a running job, we should keep the gc guard. However, currently, the cancel
237 : // API is only used for testing purposes, so we can drop everything here.
238 0 : guard.guards.clear();
239 0 : }
240 :
241 : /// Schedule a manual compaction job.
242 0 : pub fn schedule_manual_compaction(
243 0 : &self,
244 0 : options: CompactOptions,
245 0 : notify: Option<tokio::sync::oneshot::Sender<()>>,
246 0 : ) -> GcCompactionJobId {
247 0 : let mut guard = self.inner.lock().unwrap();
248 0 : let id = guard.next_id();
249 0 : guard.queued.push_back((
250 0 : id,
251 0 : GcCompactionQueueItem::MetaJob {
252 0 : options,
253 0 : auto: false,
254 0 : },
255 0 : ));
256 0 : guard.guards.entry(id).or_default().notify = notify;
257 0 : info!("scheduled compaction job id={}", id);
258 0 : id
259 0 : }
260 :
261 : /// Schedule an auto compaction job.
262 0 : fn schedule_auto_compaction(
263 0 : &self,
264 0 : options: CompactOptions,
265 0 : permit: OwnedSemaphorePermit,
266 0 : ) -> GcCompactionJobId {
267 0 : let mut guard = self.inner.lock().unwrap();
268 0 : let id = guard.next_id();
269 0 : guard.queued.push_back((
270 0 : id,
271 0 : GcCompactionQueueItem::MetaJob {
272 0 : options,
273 0 : auto: true,
274 0 : },
275 0 : ));
276 0 : guard.guards.entry(id).or_default().permit = Some(permit);
277 0 : id
278 0 : }
279 :
280 : /// Trigger an auto compaction.
281 0 : pub async fn trigger_auto_compaction(
282 0 : &self,
283 0 : timeline: &Arc<Timeline>,
284 0 : ) -> Result<(), CompactionError> {
285 : let GcCompactionCombinedSettings {
286 0 : gc_compaction_enabled,
287 0 : gc_compaction_initial_threshold_kb,
288 0 : gc_compaction_ratio_percent,
289 : ..
290 0 : } = timeline.get_gc_compaction_settings();
291 0 : if !gc_compaction_enabled {
292 0 : return Ok(());
293 0 : }
294 0 : if self.remaining_jobs_num() > 0 {
295 : // Only schedule auto compaction when the queue is empty
296 0 : return Ok(());
297 0 : }
298 0 : if timeline.ancestor_timeline().is_some() {
299 : // Do not trigger auto compaction for child timelines. We haven't tested
300 : // it enough in staging yet.
301 0 : return Ok(());
302 0 : }
303 0 : if timeline.get_gc_compaction_watermark() == Lsn::INVALID {
304 : // If the gc watermark is not set, we don't need to trigger auto compaction.
305 : // This check is the same as in `gc_compaction_split_jobs` but we don't log
306 : // here and we can also skip the computation of the trigger condition earlier.
307 0 : return Ok(());
308 0 : }
309 :
310 0 : let Ok(permit) = CONCURRENT_GC_COMPACTION_TASKS.clone().try_acquire_owned() else {
311 : // Only allow one compaction run at a time. TODO: As we do `try_acquire_owned`, we cannot ensure
312 : // the fairness of the lock across timelines. We should listen for both `acquire` and `l0_compaction_trigger`
313 : // to ensure the fairness while avoid starving other tasks.
314 0 : return Ok(());
315 : };
316 :
317 0 : let gc_compaction_state = timeline.get_gc_compaction_state();
318 0 : let l2_lsn = gc_compaction_state
319 0 : .map(|x| x.last_completed_lsn)
320 0 : .unwrap_or(Lsn::INVALID);
321 :
322 0 : let layers = {
323 0 : let guard = timeline
324 0 : .layers
325 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
326 0 : .await;
327 0 : let layer_map = guard.layer_map()?;
328 0 : layer_map.iter_historic_layers().collect_vec()
329 : };
330 0 : let mut l2_size: u64 = 0;
331 0 : let mut l1_size = 0;
332 0 : let gc_cutoff = *timeline.get_applied_gc_cutoff_lsn();
333 0 : for layer in layers {
334 0 : if layer.lsn_range.start <= l2_lsn {
335 0 : l2_size += layer.file_size();
336 0 : } else if layer.lsn_range.start <= gc_cutoff {
337 0 : l1_size += layer.file_size();
338 0 : }
339 : }
340 :
341 0 : fn trigger_compaction(
342 0 : l1_size: u64,
343 0 : l2_size: u64,
344 0 : gc_compaction_initial_threshold_kb: u64,
345 0 : gc_compaction_ratio_percent: u64,
346 0 : ) -> bool {
347 : const AUTO_TRIGGER_LIMIT: u64 = 150 * 1024 * 1024 * 1024; // 150GB
348 0 : if l1_size + l2_size >= AUTO_TRIGGER_LIMIT {
349 : // Do not auto-trigger when physical size >= 150GB
350 0 : return false;
351 0 : }
352 : // initial trigger
353 0 : if l2_size == 0 && l1_size >= gc_compaction_initial_threshold_kb * 1024 {
354 0 : info!(
355 0 : "trigger auto-compaction because l1_size={} >= gc_compaction_initial_threshold_kb={}",
356 : l1_size, gc_compaction_initial_threshold_kb
357 : );
358 0 : return true;
359 0 : }
360 : // size ratio trigger
361 0 : if l2_size == 0 {
362 0 : return false;
363 0 : }
364 0 : if l1_size as f64 / l2_size as f64 >= (gc_compaction_ratio_percent as f64 / 100.0) {
365 0 : info!(
366 0 : "trigger auto-compaction because l1_size={} / l2_size={} > gc_compaction_ratio_percent={}",
367 : l1_size, l2_size, gc_compaction_ratio_percent
368 : );
369 0 : return true;
370 0 : }
371 0 : false
372 0 : }
373 :
374 0 : if trigger_compaction(
375 0 : l1_size,
376 0 : l2_size,
377 0 : gc_compaction_initial_threshold_kb,
378 0 : gc_compaction_ratio_percent,
379 : ) {
380 0 : self.schedule_auto_compaction(
381 : CompactOptions {
382 : flags: {
383 0 : let mut flags = EnumSet::new();
384 0 : flags |= CompactFlags::EnhancedGcBottomMostCompaction;
385 0 : if timeline.get_compaction_l0_first() {
386 0 : flags |= CompactFlags::YieldForL0;
387 0 : }
388 0 : flags
389 : },
390 : sub_compaction: true,
391 : // Only auto-trigger gc-compaction over the data keyspace due to concerns in
392 : // https://github.com/neondatabase/neon/issues/11318.
393 0 : compact_key_range: Some(CompactKeyRange {
394 0 : start: Key::MIN,
395 0 : end: Key::metadata_key_range().start,
396 0 : }),
397 0 : compact_lsn_range: None,
398 0 : sub_compaction_max_job_size_mb: None,
399 : gc_compaction_do_metadata_compaction: false,
400 : },
401 0 : permit,
402 : );
403 0 : info!(
404 0 : "scheduled auto gc-compaction: l1_size={}, l2_size={}, l2_lsn={}, gc_cutoff={}",
405 : l1_size, l2_size, l2_lsn, gc_cutoff
406 : );
407 : } else {
408 0 : debug!(
409 0 : "did not trigger auto gc-compaction: l1_size={}, l2_size={}, l2_lsn={}, gc_cutoff={}",
410 : l1_size, l2_size, l2_lsn, gc_cutoff
411 : );
412 : }
413 0 : Ok(())
414 0 : }
415 :
416 0 : async fn collect_layer_below_lsn(
417 0 : &self,
418 0 : timeline: &Arc<Timeline>,
419 0 : lsn: Lsn,
420 0 : ) -> Result<u64, CompactionError> {
421 0 : let guard = timeline
422 0 : .layers
423 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
424 0 : .await;
425 0 : let layer_map = guard.layer_map()?;
426 0 : let layers = layer_map.iter_historic_layers().collect_vec();
427 0 : let mut size = 0;
428 0 : for layer in layers {
429 0 : if layer.lsn_range.start <= lsn {
430 0 : size += layer.file_size();
431 0 : }
432 : }
433 0 : Ok(size)
434 0 : }
435 :
436 : /// Notify the caller the job has finished and unblock GC.
437 0 : fn notify_and_unblock(&self, id: GcCompactionJobId) {
438 0 : info!("compaction job id={} finished", id);
439 0 : let mut guard = self.inner.lock().unwrap();
440 0 : if let Some(items) = guard.guards.remove(&id) {
441 0 : if let Some(tx) = items.notify {
442 0 : let _ = tx.send(());
443 0 : }
444 0 : }
445 0 : if let Some(ref meta_statistics) = guard.meta_statistics {
446 0 : if meta_statistics.meta_job_id == id {
447 0 : if let Ok(stats) = serde_json::to_string(&meta_statistics) {
448 0 : info!(
449 0 : "gc-compaction meta statistics for job id = {}: {}",
450 : id, stats
451 : );
452 0 : }
453 0 : }
454 0 : }
455 0 : }
456 :
457 0 : fn clear_running_job(&self) {
458 0 : let mut guard = self.inner.lock().unwrap();
459 0 : guard.running = None;
460 0 : }
461 :
462 0 : async fn handle_sub_compaction(
463 0 : &self,
464 0 : id: GcCompactionJobId,
465 0 : options: CompactOptions,
466 0 : timeline: &Arc<Timeline>,
467 0 : auto: bool,
468 0 : ) -> Result<(), CompactionError> {
469 0 : info!(
470 0 : "running scheduled enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs"
471 : );
472 0 : let res = timeline
473 0 : .gc_compaction_split_jobs(
474 0 : GcCompactJob::from_compact_options(options.clone()),
475 0 : options.sub_compaction_max_job_size_mb,
476 0 : )
477 0 : .await;
478 0 : let jobs = match res {
479 0 : Ok(jobs) => jobs,
480 0 : Err(err) => {
481 0 : warn!("cannot split gc-compaction jobs: {}, unblocked gc", err);
482 0 : self.notify_and_unblock(id);
483 0 : return Err(err);
484 : }
485 : };
486 0 : if jobs.is_empty() {
487 0 : info!("no jobs to run, skipping scheduled compaction task");
488 0 : self.notify_and_unblock(id);
489 : } else {
490 0 : let jobs_len = jobs.len();
491 0 : let mut pending_tasks = Vec::new();
492 : // gc-compaction might pick more layers or fewer layers to compact. The L2 LSN does not need to be accurate.
493 : // And therefore, we simply assume the maximum LSN of all jobs is the expected L2 LSN.
494 0 : let expected_l2_lsn = jobs
495 0 : .iter()
496 0 : .map(|job| job.compact_lsn_range.end)
497 0 : .max()
498 0 : .unwrap();
499 0 : for (i, job) in jobs.into_iter().enumerate() {
500 : // Unfortunately we need to convert the `GcCompactJob` back to `CompactionOptions`
501 : // until we do further refactors to allow directly call `compact_with_gc`.
502 0 : let mut flags: EnumSet<CompactFlags> = EnumSet::default();
503 0 : flags |= CompactFlags::EnhancedGcBottomMostCompaction;
504 0 : if job.dry_run {
505 0 : flags |= CompactFlags::DryRun;
506 0 : }
507 0 : if options.flags.contains(CompactFlags::YieldForL0) {
508 0 : flags |= CompactFlags::YieldForL0;
509 0 : }
510 0 : let options = CompactOptions {
511 0 : flags,
512 0 : sub_compaction: false,
513 0 : compact_key_range: Some(job.compact_key_range.into()),
514 0 : compact_lsn_range: Some(job.compact_lsn_range.into()),
515 0 : sub_compaction_max_job_size_mb: None,
516 0 : gc_compaction_do_metadata_compaction: false,
517 0 : };
518 0 : pending_tasks.push(GcCompactionQueueItem::SubCompactionJob {
519 0 : options,
520 0 : i,
521 0 : total: jobs_len,
522 0 : });
523 : }
524 :
525 0 : if !auto {
526 0 : pending_tasks.push(GcCompactionQueueItem::Notify(id, None));
527 0 : } else {
528 0 : pending_tasks.push(GcCompactionQueueItem::Notify(id, Some(expected_l2_lsn)));
529 0 : }
530 :
531 0 : let layer_size = self
532 0 : .collect_layer_below_lsn(timeline, expected_l2_lsn)
533 0 : .await?;
534 :
535 : {
536 0 : let mut guard = self.inner.lock().unwrap();
537 0 : let mut tasks = Vec::new();
538 0 : for task in pending_tasks {
539 0 : let id = guard.next_id();
540 0 : tasks.push((id, task));
541 0 : }
542 0 : tasks.reverse();
543 0 : for item in tasks {
544 0 : guard.queued.push_front(item);
545 0 : }
546 0 : guard.meta_statistics = Some(GcCompactionMetaStatistics {
547 0 : meta_job_id: id,
548 0 : start_time: Some(chrono::Utc::now()),
549 0 : before_compaction_layer_size: layer_size,
550 0 : below_lsn: expected_l2_lsn,
551 0 : total_sub_compaction_jobs: jobs_len,
552 0 : ..Default::default()
553 0 : });
554 : }
555 :
556 0 : info!(
557 0 : "scheduled enhanced gc bottom-most compaction with sub-compaction, split into {} jobs",
558 : jobs_len
559 : );
560 : }
561 0 : Ok(())
562 0 : }
563 :
564 : /// Take a job from the queue and process it. Returns if there are still pending tasks.
565 0 : pub async fn iteration(
566 0 : &self,
567 0 : cancel: &CancellationToken,
568 0 : ctx: &RequestContext,
569 0 : gc_block: &GcBlock,
570 0 : timeline: &Arc<Timeline>,
571 0 : ) -> Result<CompactionOutcome, CompactionError> {
572 0 : let res = self.iteration_inner(cancel, ctx, gc_block, timeline).await;
573 0 : if let Err(err) = &res {
574 0 : log_compaction_error(err, None, cancel.is_cancelled(), true);
575 0 : }
576 0 : match res {
577 0 : Ok(res) => Ok(res),
578 0 : Err(e) if e.is_cancel() => Err(e),
579 : Err(_) => {
580 : // There are some cases where traditional gc might collect some layer
581 : // files causing gc-compaction cannot read the full history of the key.
582 : // This needs to be resolved in the long-term by improving the compaction
583 : // process. For now, let's simply avoid such errors triggering the
584 : // circuit breaker.
585 0 : Ok(CompactionOutcome::Skipped)
586 : }
587 : }
588 0 : }
589 :
590 0 : async fn iteration_inner(
591 0 : &self,
592 0 : cancel: &CancellationToken,
593 0 : ctx: &RequestContext,
594 0 : gc_block: &GcBlock,
595 0 : timeline: &Arc<Timeline>,
596 0 : ) -> Result<CompactionOutcome, CompactionError> {
597 0 : let Ok(_one_op_at_a_time_guard) = self.consumer_lock.try_lock() else {
598 0 : return Err(CompactionError::Other(anyhow::anyhow!(
599 0 : "cannot run gc-compaction because another gc-compaction is running. This should not happen because we only call this function from the gc-compaction queue."
600 0 : )));
601 : };
602 : let has_pending_tasks;
603 0 : let mut yield_for_l0 = false;
604 0 : let Some((id, item)) = ({
605 0 : let mut guard = self.inner.lock().unwrap();
606 0 : if let Some((id, item)) = guard.queued.pop_front() {
607 0 : guard.running = Some((id, item.clone()));
608 0 : has_pending_tasks = !guard.queued.is_empty();
609 0 : Some((id, item))
610 : } else {
611 0 : has_pending_tasks = false;
612 0 : None
613 : }
614 : }) else {
615 0 : self.trigger_auto_compaction(timeline).await?;
616 : // Always yield after triggering auto-compaction. Gc-compaction is a low-priority task and we
617 : // have not implemented preemption mechanism yet. We always want to yield it to more important
618 : // tasks if there is one.
619 0 : return Ok(CompactionOutcome::Done);
620 : };
621 0 : match item {
622 0 : GcCompactionQueueItem::MetaJob { options, auto } => {
623 0 : if !options
624 0 : .flags
625 0 : .contains(CompactFlags::EnhancedGcBottomMostCompaction)
626 : {
627 0 : warn!(
628 0 : "ignoring scheduled compaction task: scheduled task must be gc compaction: {:?}",
629 : options
630 : );
631 0 : } else if options.sub_compaction {
632 0 : info!(
633 0 : "running scheduled enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs"
634 : );
635 0 : self.handle_sub_compaction(id, options, timeline, auto)
636 0 : .await?;
637 : } else {
638 : // Auto compaction always enables sub-compaction so we don't need to handle update_l2_lsn
639 : // in this branch.
640 0 : let _gc_guard = match gc_block.start().await {
641 0 : Ok(guard) => guard,
642 0 : Err(e) => {
643 0 : self.notify_and_unblock(id);
644 0 : self.clear_running_job();
645 0 : return Err(CompactionError::Other(anyhow!(
646 0 : "cannot run gc-compaction because gc is blocked: {}",
647 0 : e
648 0 : )));
649 : }
650 : };
651 0 : let res = timeline.compact_with_options(cancel, options, ctx).await;
652 0 : let compaction_result = match res {
653 0 : Ok(res) => res,
654 0 : Err(err) => {
655 0 : warn!(%err, "failed to run gc-compaction");
656 0 : self.notify_and_unblock(id);
657 0 : self.clear_running_job();
658 0 : return Err(err);
659 : }
660 : };
661 0 : if compaction_result == CompactionOutcome::YieldForL0 {
662 0 : yield_for_l0 = true;
663 0 : }
664 : }
665 : }
666 0 : GcCompactionQueueItem::SubCompactionJob { options, i, total } => {
667 : // TODO: error handling, clear the queue if any task fails?
668 0 : let _gc_guard = match gc_block.start().await {
669 0 : Ok(guard) => guard,
670 0 : Err(e) => {
671 0 : self.clear_running_job();
672 0 : return Err(CompactionError::Other(anyhow!(
673 0 : "cannot run gc-compaction because gc is blocked: {}",
674 0 : e
675 0 : )));
676 : }
677 : };
678 0 : info!("running gc-compaction subcompaction job {}/{}", i, total);
679 0 : let res = timeline.compact_with_options(cancel, options, ctx).await;
680 0 : let compaction_result = match res {
681 0 : Ok(res) => res,
682 0 : Err(err) => {
683 0 : warn!(%err, "failed to run gc-compaction subcompaction job");
684 0 : self.clear_running_job();
685 0 : let mut guard = self.inner.lock().unwrap();
686 0 : if let Some(ref mut meta_statistics) = guard.meta_statistics {
687 0 : meta_statistics.failed_sub_compaction_jobs += 1;
688 0 : }
689 0 : return Err(err);
690 : }
691 : };
692 0 : if compaction_result == CompactionOutcome::YieldForL0 {
693 0 : // We will permenantly give up a task if we yield for L0 compaction: the preempted subcompaction job won't be running
694 0 : // again. This ensures that we don't keep doing duplicated work within gc-compaction. Not directly returning here because
695 0 : // we need to clean things up before returning from the function.
696 0 : yield_for_l0 = true;
697 0 : }
698 : {
699 0 : let mut guard = self.inner.lock().unwrap();
700 0 : if let Some(ref mut meta_statistics) = guard.meta_statistics {
701 0 : meta_statistics.succeeded_sub_compaction_jobs += 1;
702 0 : }
703 : }
704 : }
705 0 : GcCompactionQueueItem::Notify(id, l2_lsn) => {
706 0 : let below_lsn = {
707 0 : let mut guard = self.inner.lock().unwrap();
708 0 : if let Some(ref mut meta_statistics) = guard.meta_statistics {
709 0 : meta_statistics.below_lsn
710 : } else {
711 0 : Lsn::INVALID
712 : }
713 : };
714 0 : let layer_size = if below_lsn != Lsn::INVALID {
715 0 : self.collect_layer_below_lsn(timeline, below_lsn).await?
716 : } else {
717 0 : 0
718 : };
719 : {
720 0 : let mut guard = self.inner.lock().unwrap();
721 0 : if let Some(ref mut meta_statistics) = guard.meta_statistics {
722 0 : meta_statistics.after_compaction_layer_size = layer_size;
723 0 : meta_statistics.finalize();
724 0 : }
725 : }
726 0 : self.notify_and_unblock(id);
727 0 : if let Some(l2_lsn) = l2_lsn {
728 0 : let current_l2_lsn = timeline
729 0 : .get_gc_compaction_state()
730 0 : .map(|x| x.last_completed_lsn)
731 0 : .unwrap_or(Lsn::INVALID);
732 0 : if l2_lsn >= current_l2_lsn {
733 0 : info!("l2_lsn updated to {}", l2_lsn);
734 0 : timeline
735 0 : .update_gc_compaction_state(GcCompactionState {
736 0 : last_completed_lsn: l2_lsn,
737 0 : })
738 0 : .map_err(CompactionError::Other)?;
739 : } else {
740 0 : warn!(
741 0 : "l2_lsn updated to {} but it is less than the current l2_lsn {}",
742 : l2_lsn, current_l2_lsn
743 : );
744 : }
745 0 : }
746 : }
747 : }
748 0 : self.clear_running_job();
749 0 : Ok(if yield_for_l0 {
750 0 : tracing::info!("give up gc-compaction: yield for L0 compaction");
751 0 : CompactionOutcome::YieldForL0
752 0 : } else if has_pending_tasks {
753 0 : CompactionOutcome::Pending
754 : } else {
755 0 : CompactionOutcome::Done
756 : })
757 0 : }
758 :
759 : #[allow(clippy::type_complexity)]
760 0 : pub fn remaining_jobs(
761 0 : &self,
762 0 : ) -> (
763 0 : Option<(GcCompactionJobId, GcCompactionQueueItem)>,
764 0 : VecDeque<(GcCompactionJobId, GcCompactionQueueItem)>,
765 0 : ) {
766 0 : let guard = self.inner.lock().unwrap();
767 0 : (guard.running.clone(), guard.queued.clone())
768 0 : }
769 :
770 0 : pub fn remaining_jobs_num(&self) -> usize {
771 0 : let guard = self.inner.lock().unwrap();
772 0 : guard.queued.len() + if guard.running.is_some() { 1 } else { 0 }
773 0 : }
774 : }
775 :
776 : /// A job description for the gc-compaction job. This structure describes the rectangle range that the job will
777 : /// process. The exact layers that need to be compacted/rewritten will be generated when `compact_with_gc` gets
778 : /// called.
779 : #[derive(Debug, Clone)]
780 : pub(crate) struct GcCompactJob {
781 : pub dry_run: bool,
782 : /// The key range to be compacted. The compaction algorithm will only regenerate key-value pairs within this range
783 : /// [left inclusive, right exclusive), and other pairs will be rewritten into new files if necessary.
784 : pub compact_key_range: Range<Key>,
785 : /// The LSN range to be compacted. The compaction algorithm will use this range to determine the layers to be
786 : /// selected for the compaction, and it does not guarantee the generated layers will have exactly the same LSN range
787 : /// as specified here. The true range being compacted is `min_lsn/max_lsn` in [`GcCompactionJobDescription`].
788 : /// min_lsn will always <= the lower bound specified here, and max_lsn will always >= the upper bound specified here.
789 : pub compact_lsn_range: Range<Lsn>,
790 : /// See [`CompactOptions::gc_compaction_do_metadata_compaction`].
791 : pub do_metadata_compaction: bool,
792 : }
793 :
794 : impl GcCompactJob {
795 28 : pub fn from_compact_options(options: CompactOptions) -> Self {
796 : GcCompactJob {
797 28 : dry_run: options.flags.contains(CompactFlags::DryRun),
798 28 : compact_key_range: options
799 28 : .compact_key_range
800 28 : .map(|x| x.into())
801 28 : .unwrap_or(Key::MIN..Key::MAX),
802 28 : compact_lsn_range: options
803 28 : .compact_lsn_range
804 28 : .map(|x| x.into())
805 28 : .unwrap_or(Lsn::INVALID..Lsn::MAX),
806 28 : do_metadata_compaction: options.gc_compaction_do_metadata_compaction,
807 : }
808 28 : }
809 : }
810 :
811 : /// A job description for the gc-compaction job. This structure is generated when `compact_with_gc` is called
812 : /// and contains the exact layers we want to compact.
813 : pub struct GcCompactionJobDescription {
814 : /// All layers to read in the compaction job
815 : selected_layers: Vec<Layer>,
816 : /// GC cutoff of the job. This is the lowest LSN that will be accessed by the read/GC path and we need to
817 : /// keep all deltas <= this LSN or generate an image == this LSN.
818 : gc_cutoff: Lsn,
819 : /// LSNs to retain for the job. Read path will use this LSN so we need to keep deltas <= this LSN or
820 : /// generate an image == this LSN.
821 : retain_lsns_below_horizon: Vec<Lsn>,
822 : /// Maximum layer LSN processed in this compaction, that is max(end_lsn of layers). Exclusive. All data
823 : /// \>= this LSN will be kept and will not be rewritten.
824 : max_layer_lsn: Lsn,
825 : /// Minimum layer LSN processed in this compaction, that is min(start_lsn of layers). Inclusive.
826 : /// All access below (strict lower than `<`) this LSN will be routed through the normal read path instead of
827 : /// k-merge within gc-compaction.
828 : min_layer_lsn: Lsn,
829 : /// Only compact layers overlapping with this range.
830 : compaction_key_range: Range<Key>,
831 : /// When partial compaction is enabled, these layers need to be rewritten to ensure no overlap.
832 : /// This field is here solely for debugging. The field will not be read once the compaction
833 : /// description is generated.
834 : rewrite_layers: Vec<Arc<PersistentLayerDesc>>,
835 : }
836 :
837 : /// The result of bottom-most compaction for a single key at each LSN.
838 : #[derive(Debug)]
839 : #[cfg_attr(test, derive(PartialEq))]
840 : pub struct KeyLogAtLsn(pub Vec<(Lsn, Value)>);
841 :
842 : /// The result of bottom-most compaction.
843 : #[derive(Debug)]
844 : #[cfg_attr(test, derive(PartialEq))]
845 : pub(crate) struct KeyHistoryRetention {
846 : /// Stores logs to reconstruct the value at the given LSN, that is to say, logs <= LSN or image == LSN.
847 : pub(crate) below_horizon: Vec<(Lsn, KeyLogAtLsn)>,
848 : /// Stores logs to reconstruct the value at any LSN above the horizon, that is to say, log > LSN.
849 : pub(crate) above_horizon: KeyLogAtLsn,
850 : }
851 :
852 : impl KeyHistoryRetention {
853 : /// Hack: skip delta layer if we need to produce a layer of a same key-lsn.
854 : ///
855 : /// This can happen if we have removed some deltas in "the middle" of some existing layer's key-lsn-range.
856 : /// For example, consider the case where a single delta with range [0x10,0x50) exists.
857 : /// And we have branches at LSN 0x10, 0x20, 0x30.
858 : /// Then we delete branch @ 0x20.
859 : /// Bottom-most compaction may now delete the delta [0x20,0x30).
860 : /// And that wouldnt' change the shape of the layer.
861 : ///
862 : /// Note that bottom-most-gc-compaction never _adds_ new data in that case, only removes.
863 : ///
864 : /// `discard_key` will only be called when the writer reaches its target (instead of for every key), so it's fine to grab a lock inside.
865 37 : async fn discard_key(key: &PersistentLayerKey, tline: &Arc<Timeline>, dry_run: bool) -> bool {
866 37 : if dry_run {
867 0 : return true;
868 37 : }
869 37 : if LayerMap::is_l0(&key.key_range, key.is_delta) {
870 : // gc-compaction should not produce L0 deltas, otherwise it will break the layer order.
871 : // We should ignore such layers.
872 0 : return true;
873 37 : }
874 : let layer_generation;
875 : {
876 37 : let guard = tline.layers.read(LayerManagerLockHolder::Compaction).await;
877 37 : if !guard.contains_key(key) {
878 26 : return false;
879 11 : }
880 11 : layer_generation = guard.get_from_key(key).metadata().generation;
881 : }
882 11 : if layer_generation == tline.generation {
883 11 : info!(
884 : key=%key,
885 : ?layer_generation,
886 0 : "discard layer due to duplicated layer key in the same generation",
887 : );
888 11 : true
889 : } else {
890 0 : false
891 : }
892 37 : }
893 :
894 : /// Pipe a history of a single key to the writers.
895 : ///
896 : /// If `image_writer` is none, the images will be placed into the delta layers.
897 : /// The delta writer will contain all images and deltas (below and above the horizon) except the bottom-most images.
898 : #[allow(clippy::too_many_arguments)]
899 319 : async fn pipe_to(
900 319 : self,
901 319 : key: Key,
902 319 : delta_writer: &mut SplitDeltaLayerWriter<'_>,
903 319 : mut image_writer: Option<&mut SplitImageLayerWriter<'_>>,
904 319 : stat: &mut CompactionStatistics,
905 319 : ctx: &RequestContext,
906 319 : ) -> anyhow::Result<()> {
907 319 : let mut first_batch = true;
908 1022 : for (cutoff_lsn, KeyLogAtLsn(logs)) in self.below_horizon {
909 703 : if first_batch {
910 319 : if logs.len() == 1 && logs[0].1.is_image() {
911 300 : let Value::Image(img) = &logs[0].1 else {
912 0 : unreachable!()
913 : };
914 300 : stat.produce_image_key(img);
915 300 : if let Some(image_writer) = image_writer.as_mut() {
916 300 : image_writer.put_image(key, img.clone(), ctx).await?;
917 : } else {
918 0 : delta_writer
919 0 : .put_value(key, cutoff_lsn, Value::Image(img.clone()), ctx)
920 0 : .await?;
921 : }
922 : } else {
923 33 : for (lsn, val) in logs {
924 14 : stat.produce_key(&val);
925 14 : delta_writer.put_value(key, lsn, val, ctx).await?;
926 : }
927 : }
928 319 : first_batch = false;
929 : } else {
930 442 : for (lsn, val) in logs {
931 58 : stat.produce_key(&val);
932 58 : delta_writer.put_value(key, lsn, val, ctx).await?;
933 : }
934 : }
935 : }
936 319 : let KeyLogAtLsn(above_horizon_logs) = self.above_horizon;
937 348 : for (lsn, val) in above_horizon_logs {
938 29 : stat.produce_key(&val);
939 29 : delta_writer.put_value(key, lsn, val, ctx).await?;
940 : }
941 319 : Ok(())
942 319 : }
943 :
944 : /// Verify if every key in the retention is readable by replaying the logs.
945 323 : async fn verify(
946 323 : &self,
947 323 : key: Key,
948 323 : base_img_from_ancestor: &Option<(Key, Lsn, Bytes)>,
949 323 : full_history: &[(Key, Lsn, Value)],
950 323 : tline: &Arc<Timeline>,
951 323 : ) -> anyhow::Result<()> {
952 : // Usually the min_lsn should be the first record but we do a full iteration to be safe.
953 323 : let Some(min_lsn) = full_history.iter().map(|(_, lsn, _)| *lsn).min() else {
954 : // This should never happen b/c if we don't have any history of a key, we won't even do `generate_key_retention`.
955 0 : return Ok(());
956 : };
957 323 : let Some(max_lsn) = full_history.iter().map(|(_, lsn, _)| *lsn).max() else {
958 : // This should never happen b/c if we don't have any history of a key, we won't even do `generate_key_retention`.
959 0 : return Ok(());
960 : };
961 323 : let mut base_img = base_img_from_ancestor
962 323 : .as_ref()
963 323 : .map(|(_, lsn, img)| (*lsn, img));
964 323 : let mut history = Vec::new();
965 :
966 1027 : async fn collect_and_verify(
967 1027 : key: Key,
968 1027 : lsn: Lsn,
969 1027 : base_img: &Option<(Lsn, &Bytes)>,
970 1027 : history: &[(Lsn, &NeonWalRecord)],
971 1027 : tline: &Arc<Timeline>,
972 1027 : skip_empty: bool,
973 1027 : ) -> anyhow::Result<()> {
974 1027 : if base_img.is_none() && history.is_empty() {
975 0 : if skip_empty {
976 0 : return Ok(());
977 0 : }
978 0 : anyhow::bail!("verification failed: key {} has no history at {}", key, lsn);
979 1027 : };
980 :
981 1027 : let mut records = history
982 1027 : .iter()
983 1027 : .map(|(lsn, val)| (*lsn, (*val).clone()))
984 1027 : .collect::<Vec<_>>();
985 :
986 : // WAL redo requires records in the reverse LSN order
987 1027 : records.reverse();
988 1027 : let data = ValueReconstructState {
989 1027 : img: base_img.as_ref().map(|(lsn, img)| (*lsn, (*img).clone())),
990 1027 : records,
991 : };
992 :
993 1027 : tline
994 1027 : .reconstruct_value(key, lsn, data, RedoAttemptType::GcCompaction)
995 1027 : .await
996 1027 : .with_context(|| format!("verification failed for key {key} at lsn {lsn}"))?;
997 :
998 1027 : Ok(())
999 1027 : }
1000 :
1001 1036 : for (retain_lsn, KeyLogAtLsn(logs)) in &self.below_horizon {
1002 1096 : for (lsn, val) in logs {
1003 76 : match val {
1004 307 : Value::Image(img) => {
1005 307 : base_img = Some((*lsn, img));
1006 307 : history.clear();
1007 307 : }
1008 76 : Value::WalRecord(rec) if val.will_init() => {
1009 0 : base_img = None;
1010 0 : history.clear();
1011 0 : history.push((*lsn, rec));
1012 0 : }
1013 76 : Value::WalRecord(rec) => {
1014 76 : history.push((*lsn, rec));
1015 76 : }
1016 : }
1017 : }
1018 713 : if *retain_lsn >= min_lsn {
1019 : // Only verify after the key appears in the full history for the first time.
1020 :
1021 : // We don't modify history: in theory, we could replace the history with a single
1022 : // image as in `generate_key_retention` to make redos at later LSNs faster. But we
1023 : // want to verify everything as if they are read from the real layer map.
1024 699 : collect_and_verify(key, *retain_lsn, &base_img, &history, tline, false)
1025 699 : .await
1026 699 : .context("below horizon retain_lsn")?;
1027 14 : }
1028 : }
1029 :
1030 360 : for (lsn, val) in &self.above_horizon.0 {
1031 32 : match val {
1032 5 : Value::Image(img) => {
1033 : // Above the GC horizon, we verify every time we see an image.
1034 5 : collect_and_verify(key, *lsn, &base_img, &history, tline, true)
1035 5 : .await
1036 5 : .context("above horizon full image")?;
1037 5 : base_img = Some((*lsn, img));
1038 5 : history.clear();
1039 : }
1040 32 : Value::WalRecord(rec) if val.will_init() => {
1041 : // Above the GC horizon, we verify every time we see an init record.
1042 0 : collect_and_verify(key, *lsn, &base_img, &history, tline, true)
1043 0 : .await
1044 0 : .context("above horizon init record")?;
1045 0 : base_img = None;
1046 0 : history.clear();
1047 0 : history.push((*lsn, rec));
1048 : }
1049 32 : Value::WalRecord(rec) => {
1050 32 : history.push((*lsn, rec));
1051 32 : }
1052 : }
1053 : }
1054 : // Ensure the latest record is readable.
1055 323 : collect_and_verify(key, max_lsn, &base_img, &history, tline, false)
1056 323 : .await
1057 323 : .context("latest record")?;
1058 323 : Ok(())
1059 323 : }
1060 : }
1061 :
1062 : #[derive(Debug, Serialize, Default)]
1063 : struct CompactionStatisticsNumSize {
1064 : num: u64,
1065 : size: u64,
1066 : }
1067 :
1068 : #[derive(Debug, Serialize, Default)]
1069 : pub struct CompactionStatistics {
1070 : /// Delta layer visited (maybe compressed, physical size)
1071 : delta_layer_visited: CompactionStatisticsNumSize,
1072 : /// Image layer visited (maybe compressed, physical size)
1073 : image_layer_visited: CompactionStatisticsNumSize,
1074 : /// Delta layer produced (maybe compressed, physical size)
1075 : delta_layer_produced: CompactionStatisticsNumSize,
1076 : /// Image layer produced (maybe compressed, physical size)
1077 : image_layer_produced: CompactionStatisticsNumSize,
1078 : /// Delta layer discarded (maybe compressed, physical size of the layer being discarded instead of the original layer)
1079 : delta_layer_discarded: CompactionStatisticsNumSize,
1080 : /// Image layer discarded (maybe compressed, physical size of the layer being discarded instead of the original layer)
1081 : image_layer_discarded: CompactionStatisticsNumSize,
1082 : num_unique_keys_visited: usize,
1083 : /// Delta visited (uncompressed, original size)
1084 : wal_keys_visited: CompactionStatisticsNumSize,
1085 : /// Image visited (uncompressed, original size)
1086 : image_keys_visited: CompactionStatisticsNumSize,
1087 : /// Delta produced (uncompressed, original size)
1088 : wal_produced: CompactionStatisticsNumSize,
1089 : /// Image produced (uncompressed, original size)
1090 : image_produced: CompactionStatisticsNumSize,
1091 :
1092 : // Time spent in each phase
1093 : time_acquire_lock_secs: f64,
1094 : time_analyze_secs: f64,
1095 : time_download_layer_secs: f64,
1096 : time_to_first_kv_pair_secs: f64,
1097 : time_main_loop_secs: f64,
1098 : time_final_phase_secs: f64,
1099 : time_total_secs: f64,
1100 :
1101 : // Summary
1102 : /// Ratio of the key-value size after/before gc-compaction.
1103 : uncompressed_retention_ratio: f64,
1104 : /// Ratio of the physical size after/before gc-compaction.
1105 : compressed_retention_ratio: f64,
1106 : }
1107 :
1108 : impl CompactionStatistics {
1109 534 : fn estimated_size_of_value(val: &Value) -> usize {
1110 219 : match val {
1111 315 : Value::Image(img) => img.len(),
1112 0 : Value::WalRecord(NeonWalRecord::Postgres { rec, .. }) => rec.len(),
1113 219 : _ => std::mem::size_of::<NeonWalRecord>(),
1114 : }
1115 534 : }
1116 839 : fn estimated_size_of_key() -> usize {
1117 839 : KEY_SIZE // TODO: distinguish image layer and delta layer (count LSN in delta layer)
1118 839 : }
1119 44 : fn visit_delta_layer(&mut self, size: u64) {
1120 44 : self.delta_layer_visited.num += 1;
1121 44 : self.delta_layer_visited.size += size;
1122 44 : }
1123 35 : fn visit_image_layer(&mut self, size: u64) {
1124 35 : self.image_layer_visited.num += 1;
1125 35 : self.image_layer_visited.size += size;
1126 35 : }
1127 320 : fn on_unique_key_visited(&mut self) {
1128 320 : self.num_unique_keys_visited += 1;
1129 320 : }
1130 123 : fn visit_wal_key(&mut self, val: &Value) {
1131 123 : self.wal_keys_visited.num += 1;
1132 123 : self.wal_keys_visited.size +=
1133 123 : Self::estimated_size_of_value(val) as u64 + Self::estimated_size_of_key() as u64;
1134 123 : }
1135 315 : fn visit_image_key(&mut self, val: &Value) {
1136 315 : self.image_keys_visited.num += 1;
1137 315 : self.image_keys_visited.size +=
1138 315 : Self::estimated_size_of_value(val) as u64 + Self::estimated_size_of_key() as u64;
1139 315 : }
1140 101 : fn produce_key(&mut self, val: &Value) {
1141 101 : match val {
1142 5 : Value::Image(img) => self.produce_image_key(img),
1143 96 : Value::WalRecord(_) => self.produce_wal_key(val),
1144 : }
1145 101 : }
1146 96 : fn produce_wal_key(&mut self, val: &Value) {
1147 96 : self.wal_produced.num += 1;
1148 96 : self.wal_produced.size +=
1149 96 : Self::estimated_size_of_value(val) as u64 + Self::estimated_size_of_key() as u64;
1150 96 : }
1151 305 : fn produce_image_key(&mut self, val: &Bytes) {
1152 305 : self.image_produced.num += 1;
1153 305 : self.image_produced.size += val.len() as u64 + Self::estimated_size_of_key() as u64;
1154 305 : }
1155 7 : fn discard_delta_layer(&mut self, original_size: u64) {
1156 7 : self.delta_layer_discarded.num += 1;
1157 7 : self.delta_layer_discarded.size += original_size;
1158 7 : }
1159 4 : fn discard_image_layer(&mut self, original_size: u64) {
1160 4 : self.image_layer_discarded.num += 1;
1161 4 : self.image_layer_discarded.size += original_size;
1162 4 : }
1163 12 : fn produce_delta_layer(&mut self, size: u64) {
1164 12 : self.delta_layer_produced.num += 1;
1165 12 : self.delta_layer_produced.size += size;
1166 12 : }
1167 15 : fn produce_image_layer(&mut self, size: u64) {
1168 15 : self.image_layer_produced.num += 1;
1169 15 : self.image_layer_produced.size += size;
1170 15 : }
1171 26 : fn finalize(&mut self) {
1172 26 : let original_key_value_size = self.image_keys_visited.size + self.wal_keys_visited.size;
1173 26 : let produced_key_value_size = self.image_produced.size + self.wal_produced.size;
1174 26 : self.uncompressed_retention_ratio =
1175 26 : produced_key_value_size as f64 / (original_key_value_size as f64 + 1.0); // avoid div by 0
1176 26 : let original_physical_size = self.image_layer_visited.size + self.delta_layer_visited.size;
1177 26 : let produced_physical_size = self.image_layer_produced.size
1178 26 : + self.delta_layer_produced.size
1179 26 : + self.image_layer_discarded.size
1180 26 : + self.delta_layer_discarded.size; // Also include the discarded layers to make the ratio accurate
1181 26 : self.compressed_retention_ratio =
1182 26 : produced_physical_size as f64 / (original_physical_size as f64 + 1.0); // avoid div by 0
1183 26 : }
1184 : }
1185 :
1186 : #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1187 : pub enum CompactionOutcome {
1188 : #[default]
1189 : /// No layers need to be compacted after this round. Compaction doesn't need
1190 : /// to be immediately scheduled.
1191 : Done,
1192 : /// Still has pending layers to be compacted after this round. Ideally, the scheduler
1193 : /// should immediately schedule another compaction.
1194 : Pending,
1195 : /// A timeline needs L0 compaction. Yield and schedule an immediate L0 compaction pass (only
1196 : /// guaranteed when `compaction_l0_first` is enabled).
1197 : YieldForL0,
1198 : /// Compaction was skipped, because the timeline is ineligible for compaction.
1199 : Skipped,
1200 : }
1201 :
1202 : impl Timeline {
1203 : /// TODO: cancellation
1204 : ///
1205 : /// Returns whether the compaction has pending tasks.
1206 192 : pub(crate) async fn compact_legacy(
1207 192 : self: &Arc<Self>,
1208 192 : cancel: &CancellationToken,
1209 192 : options: CompactOptions,
1210 192 : ctx: &RequestContext,
1211 192 : ) -> Result<CompactionOutcome, CompactionError> {
1212 192 : if options
1213 192 : .flags
1214 192 : .contains(CompactFlags::EnhancedGcBottomMostCompaction)
1215 : {
1216 0 : self.compact_with_gc(cancel, options, ctx).await?;
1217 0 : return Ok(CompactionOutcome::Done);
1218 192 : }
1219 :
1220 192 : if options.flags.contains(CompactFlags::DryRun) {
1221 0 : return Err(CompactionError::Other(anyhow!(
1222 0 : "dry-run mode is not supported for legacy compaction for now"
1223 0 : )));
1224 192 : }
1225 :
1226 192 : if options.compact_key_range.is_some() || options.compact_lsn_range.is_some() {
1227 : // maybe useful in the future? could implement this at some point
1228 0 : return Err(CompactionError::Other(anyhow!(
1229 0 : "compaction range is not supported for legacy compaction for now"
1230 0 : )));
1231 192 : }
1232 :
1233 : // High level strategy for compaction / image creation:
1234 : //
1235 : // 1. First, do a L0 compaction to ensure we move the L0
1236 : // layers into the historic layer map get flat levels of
1237 : // layers. If we did not compact all L0 layers, we will
1238 : // prioritize compacting the timeline again and not do
1239 : // any of the compactions below.
1240 : //
1241 : // 2. Then, calculate the desired "partitioning" of the
1242 : // currently in-use key space. The goal is to partition the
1243 : // key space into roughly fixed-size chunks, but also take into
1244 : // account any existing image layers, and try to align the
1245 : // chunk boundaries with the existing image layers to avoid
1246 : // too much churn. Also try to align chunk boundaries with
1247 : // relation boundaries. In principle, we don't know about
1248 : // relation boundaries here, we just deal with key-value
1249 : // pairs, and the code in pgdatadir_mapping.rs knows how to
1250 : // map relations into key-value pairs. But in practice we know
1251 : // that 'field6' is the block number, and the fields 1-5
1252 : // identify a relation. This is just an optimization,
1253 : // though.
1254 : //
1255 : // 3. Once we know the partitioning, for each partition,
1256 : // decide if it's time to create a new image layer. The
1257 : // criteria is: there has been too much "churn" since the last
1258 : // image layer? The "churn" is fuzzy concept, it's a
1259 : // combination of too many delta files, or too much WAL in
1260 : // total in the delta file. Or perhaps: if creating an image
1261 : // file would allow to delete some older files.
1262 : //
1263 : // 4. In the end, if the tenant gets auto-sharded, we will run
1264 : // a shard-ancestor compaction.
1265 :
1266 : // Is the timeline being deleted?
1267 192 : if self.is_stopping() {
1268 0 : trace!("Dropping out of compaction on timeline shutdown");
1269 0 : return Err(CompactionError::new_cancelled());
1270 192 : }
1271 :
1272 192 : let target_file_size = self.get_checkpoint_distance();
1273 :
1274 : // Define partitioning schema if needed
1275 :
1276 : // HADRON
1277 192 : let force_image_creation_lsn = self.get_force_image_creation_lsn();
1278 :
1279 : // 1. L0 Compact
1280 192 : let l0_outcome = {
1281 192 : let timer = self.metrics.compact_time_histo.start_timer();
1282 192 : let l0_outcome = self
1283 192 : .compact_level0(
1284 192 : target_file_size,
1285 192 : options.flags.contains(CompactFlags::ForceL0Compaction),
1286 192 : force_image_creation_lsn,
1287 192 : ctx,
1288 192 : )
1289 192 : .await?;
1290 192 : timer.stop_and_record();
1291 192 : l0_outcome
1292 : };
1293 :
1294 192 : if options.flags.contains(CompactFlags::OnlyL0Compaction) {
1295 0 : return Ok(l0_outcome);
1296 192 : }
1297 :
1298 : // Yield if we have pending L0 compaction. The scheduler will do another pass.
1299 192 : if (l0_outcome == CompactionOutcome::Pending || l0_outcome == CompactionOutcome::YieldForL0)
1300 0 : && options.flags.contains(CompactFlags::YieldForL0)
1301 : {
1302 0 : info!("image/ancestor compaction yielding for L0 compaction");
1303 0 : return Ok(CompactionOutcome::YieldForL0);
1304 192 : }
1305 :
1306 192 : let gc_cutoff = *self.applied_gc_cutoff_lsn.read();
1307 192 : let l0_l1_boundary_lsn = {
1308 : // We do the repartition on the L0-L1 boundary. All data below the boundary
1309 : // are compacted by L0 with low read amplification, thus making the `repartition`
1310 : // function run fast.
1311 192 : let guard = self
1312 192 : .layers
1313 192 : .read(LayerManagerLockHolder::GetLayerMapInfo)
1314 192 : .await;
1315 192 : guard
1316 192 : .all_persistent_layers()
1317 192 : .iter()
1318 1219 : .map(|x| {
1319 : // Use the end LSN of delta layers OR the start LSN of image layers.
1320 1219 : if x.is_delta {
1321 1035 : x.lsn_range.end
1322 : } else {
1323 184 : x.lsn_range.start
1324 : }
1325 1219 : })
1326 192 : .max()
1327 : };
1328 :
1329 192 : let (partition_mode, partition_lsn) = {
1330 192 : let last_repartition_lsn = self.partitioning.read().1;
1331 192 : let lsn = match l0_l1_boundary_lsn {
1332 192 : Some(boundary) => gc_cutoff
1333 192 : .max(boundary)
1334 192 : .max(last_repartition_lsn)
1335 192 : .max(self.initdb_lsn)
1336 192 : .max(self.ancestor_lsn),
1337 0 : None => self.get_last_record_lsn(),
1338 : };
1339 192 : if lsn <= self.initdb_lsn || lsn <= self.ancestor_lsn {
1340 : // Do not attempt to create image layers below the initdb or ancestor LSN -- no data below it
1341 0 : ("l0_l1_boundary", self.get_last_record_lsn())
1342 : } else {
1343 192 : ("l0_l1_boundary", lsn)
1344 : }
1345 : };
1346 :
1347 : // 2. Repartition and create image layers if necessary
1348 192 : match self
1349 192 : .repartition(
1350 192 : partition_lsn,
1351 192 : self.get_compaction_target_size(),
1352 192 : options.flags,
1353 192 : ctx,
1354 192 : )
1355 192 : .await
1356 : {
1357 192 : Ok(((dense_partitioning, sparse_partitioning), lsn)) if lsn >= gc_cutoff => {
1358 : // Disables access_stats updates, so that the files we read remain candidates for eviction after we're done with them
1359 80 : let image_ctx = RequestContextBuilder::from(ctx)
1360 80 : .access_stats_behavior(AccessStatsBehavior::Skip)
1361 80 : .attached_child();
1362 :
1363 80 : let mut partitioning = dense_partitioning;
1364 80 : partitioning
1365 80 : .parts
1366 80 : .extend(sparse_partitioning.into_dense().parts);
1367 :
1368 : // 3. Create new image layers for partitions that have been modified "enough".
1369 80 : let mode = if options
1370 80 : .flags
1371 80 : .contains(CompactFlags::ForceImageLayerCreation)
1372 : {
1373 7 : ImageLayerCreationMode::Force
1374 : } else {
1375 73 : ImageLayerCreationMode::Try
1376 : };
1377 80 : let (image_layers, outcome) = self
1378 80 : .create_image_layers(
1379 80 : &partitioning,
1380 80 : lsn,
1381 80 : force_image_creation_lsn,
1382 80 : mode,
1383 80 : &image_ctx,
1384 80 : self.last_image_layer_creation_status
1385 80 : .load()
1386 80 : .as_ref()
1387 80 : .clone(),
1388 80 : options.flags.contains(CompactFlags::YieldForL0),
1389 : )
1390 80 : .instrument(info_span!("create_image_layers", mode = %mode, partition_mode = %partition_mode, lsn = %lsn))
1391 80 : .await
1392 80 : .inspect_err(|err| {
1393 : if let CreateImageLayersError::GetVectoredError(
1394 : GetVectoredError::MissingKey(_),
1395 0 : ) = err
1396 : {
1397 0 : critical_timeline!(
1398 0 : self.tenant_shard_id,
1399 0 : self.timeline_id,
1400 0 : Some(&self.corruption_detected),
1401 0 : "missing key during compaction: {err:?}"
1402 : );
1403 0 : }
1404 0 : })?;
1405 :
1406 80 : self.last_image_layer_creation_status
1407 80 : .store(Arc::new(outcome.clone()));
1408 :
1409 80 : self.upload_new_image_layers(image_layers)?;
1410 80 : if let LastImageLayerCreationStatus::Incomplete { .. } = outcome {
1411 : // Yield and do not do any other kind of compaction.
1412 0 : info!(
1413 0 : "skipping shard ancestor compaction due to pending image layer generation tasks (preempted by L0 compaction)."
1414 : );
1415 0 : return Ok(CompactionOutcome::YieldForL0);
1416 80 : }
1417 : }
1418 :
1419 : Ok(_) => {
1420 : // This happens very frequently so we don't want to log it.
1421 112 : debug!("skipping repartitioning due to image compaction LSN being below GC cutoff");
1422 : }
1423 :
1424 : // Suppress errors when cancelled.
1425 : //
1426 : // Log other errors but continue. Failure to repartition is normal, if the timeline was just created
1427 : // as an empty timeline. Also in unit tests, when we use the timeline as a simple
1428 : // key-value store, ignoring the datadir layout. Log the error but continue.
1429 : //
1430 : // TODO:
1431 : // 1. shouldn't we return early here if we observe cancellation
1432 : // 2. Experiment: can we stop checking self.cancel here?
1433 0 : Err(_) if self.cancel.is_cancelled() => {} // TODO: try how we fare removing this branch
1434 0 : Err(err) if err.is_cancel() => {}
1435 : Err(RepartitionError::CollectKeyspace(
1436 0 : e @ CollectKeySpaceError::Decode(_)
1437 0 : | e @ CollectKeySpaceError::PageRead(
1438 : PageReconstructError::MissingKey(_) | PageReconstructError::WalRedo(_),
1439 : ),
1440 : )) => {
1441 : // Alert on critical errors that indicate data corruption.
1442 0 : critical_timeline!(
1443 0 : self.tenant_shard_id,
1444 0 : self.timeline_id,
1445 0 : Some(&self.corruption_detected),
1446 0 : "could not compact, repartitioning keyspace failed: {e:?}"
1447 : );
1448 : }
1449 0 : Err(e) => error!(
1450 0 : "could not compact, repartitioning keyspace failed: {:?}",
1451 0 : e.into_anyhow()
1452 : ),
1453 : };
1454 :
1455 192 : let partition_count = self.partitioning.read().0.0.parts.len();
1456 :
1457 : // 4. Shard ancestor compaction
1458 192 : if self.get_compaction_shard_ancestor() && self.shard_identity.count >= ShardCount::new(2) {
1459 : // Limit the number of layer rewrites to the number of partitions: this means its
1460 : // runtime should be comparable to a full round of image layer creations, rather than
1461 : // being potentially much longer.
1462 0 : let rewrite_max = partition_count;
1463 :
1464 0 : let outcome = self
1465 0 : .compact_shard_ancestors(
1466 0 : rewrite_max,
1467 0 : options.flags.contains(CompactFlags::YieldForL0),
1468 0 : ctx,
1469 0 : )
1470 0 : .await?;
1471 0 : match outcome {
1472 0 : CompactionOutcome::Pending | CompactionOutcome::YieldForL0 => return Ok(outcome),
1473 0 : CompactionOutcome::Done | CompactionOutcome::Skipped => {}
1474 : }
1475 192 : }
1476 :
1477 192 : Ok(CompactionOutcome::Done)
1478 192 : }
1479 :
1480 : /* BEGIN_HADRON */
1481 : // Get the force image creation LSN based on gc_cutoff_lsn.
1482 : // Note that this is an estimation and the workload rate may suddenly change. When that happens,
1483 : // the force image creation may be too early or too late, but eventually it should be able to catch up.
1484 193 : pub(crate) fn get_force_image_creation_lsn(self: &Arc<Self>) -> Option<Lsn> {
1485 193 : let image_creation_period = self.get_image_layer_force_creation_period()?;
1486 1 : let current_lsn = self.get_last_record_lsn();
1487 1 : let pitr_lsn = self.gc_info.read().unwrap().cutoffs.time?;
1488 1 : let pitr_interval = self.get_pitr_interval();
1489 1 : if pitr_lsn == Lsn::INVALID || pitr_interval.is_zero() {
1490 0 : tracing::warn!(
1491 0 : "pitr LSN/interval not found, skipping force image creation LSN calculation"
1492 : );
1493 0 : return None;
1494 1 : }
1495 :
1496 1 : let delta_lsn = current_lsn.checked_sub(pitr_lsn).unwrap().0
1497 1 : * image_creation_period.as_secs()
1498 1 : / pitr_interval.as_secs();
1499 1 : let force_image_creation_lsn = current_lsn.checked_sub(delta_lsn).unwrap_or(Lsn(0));
1500 :
1501 1 : tracing::info!(
1502 0 : "Tenant shard {} computed force_image_creation_lsn: {}. Current lsn: {}, image_layer_force_creation_period: {:?}, GC cutoff: {}, PITR interval: {:?}",
1503 0 : self.tenant_shard_id,
1504 : force_image_creation_lsn,
1505 : current_lsn,
1506 : image_creation_period,
1507 : pitr_lsn,
1508 : pitr_interval
1509 : );
1510 :
1511 1 : Some(force_image_creation_lsn)
1512 193 : }
1513 : /* END_HADRON */
1514 :
1515 : /// Check for layers that are elegible to be rewritten:
1516 : /// - Shard splitting: After a shard split, ancestor layers beyond pitr_interval, so that
1517 : /// we don't indefinitely retain keys in this shard that aren't needed.
1518 : /// - For future use: layers beyond pitr_interval that are in formats we would
1519 : /// rather not maintain compatibility with indefinitely.
1520 : ///
1521 : /// Note: this phase may read and write many gigabytes of data: use rewrite_max to bound
1522 : /// how much work it will try to do in each compaction pass.
1523 0 : async fn compact_shard_ancestors(
1524 0 : self: &Arc<Self>,
1525 0 : rewrite_max: usize,
1526 0 : yield_for_l0: bool,
1527 0 : ctx: &RequestContext,
1528 0 : ) -> Result<CompactionOutcome, CompactionError> {
1529 0 : let mut outcome = CompactionOutcome::Done;
1530 0 : let mut drop_layers = Vec::new();
1531 0 : let mut layers_to_rewrite: Vec<Layer> = Vec::new();
1532 :
1533 : // We will use the Lsn cutoff of the last GC as a threshold for rewriting layers: if a
1534 : // layer is behind this Lsn, it indicates that the layer is being retained beyond the
1535 : // pitr_interval, for example because a branchpoint references it.
1536 : //
1537 : // Holding this read guard also blocks [`Self::gc_timeline`] from entering while we
1538 : // are rewriting layers.
1539 0 : let latest_gc_cutoff = self.get_applied_gc_cutoff_lsn();
1540 0 : let pitr_cutoff = self.gc_info.read().unwrap().cutoffs.time;
1541 :
1542 0 : let layers = self.layers.read(LayerManagerLockHolder::Compaction).await;
1543 0 : let layers_iter = layers.layer_map()?.iter_historic_layers();
1544 0 : let (layers_total, mut layers_checked) = (layers_iter.len(), 0);
1545 0 : for layer_desc in layers_iter {
1546 0 : layers_checked += 1;
1547 0 : let layer = layers.get_from_desc(&layer_desc);
1548 0 : if layer.metadata().shard.shard_count == self.shard_identity.count {
1549 : // This layer does not belong to a historic ancestor, no need to re-image it.
1550 0 : continue;
1551 0 : }
1552 :
1553 : // This layer was created on an ancestor shard: check if it contains any data for this shard.
1554 0 : let sharded_range = ShardedRange::new(layer_desc.get_key_range(), &self.shard_identity);
1555 0 : let layer_local_page_count = sharded_range.page_count();
1556 0 : let layer_raw_page_count = ShardedRange::raw_size(&layer_desc.get_key_range());
1557 0 : if layer_local_page_count == 0 {
1558 : // This ancestral layer only covers keys that belong to other shards.
1559 : // We include the full metadata in the log: if we had some critical bug that caused
1560 : // us to incorrectly drop layers, this would simplify manually debugging + reinstating those layers.
1561 0 : debug!(%layer, old_metadata=?layer.metadata(),
1562 0 : "dropping layer after shard split, contains no keys for this shard",
1563 : );
1564 :
1565 0 : if cfg!(debug_assertions) {
1566 : // Expensive, exhaustive check of keys in this layer: this guards against ShardedRange's calculations being
1567 : // wrong. If ShardedRange claims the local page count is zero, then no keys in this layer
1568 : // should be !is_key_disposable()
1569 : // TODO: exclude sparse keyspace from this check, otherwise it will infinitely loop.
1570 0 : let range = layer_desc.get_key_range();
1571 0 : let mut key = range.start;
1572 0 : while key < range.end {
1573 0 : debug_assert!(self.shard_identity.is_key_disposable(&key));
1574 0 : key = key.next();
1575 : }
1576 0 : }
1577 :
1578 0 : drop_layers.push(layer);
1579 0 : continue;
1580 0 : } else if layer_local_page_count != u32::MAX
1581 0 : && layer_local_page_count == layer_raw_page_count
1582 : {
1583 0 : debug!(%layer,
1584 0 : "layer is entirely shard local ({} keys), no need to filter it",
1585 : layer_local_page_count
1586 : );
1587 0 : continue;
1588 0 : }
1589 :
1590 : // Only rewrite a layer if we can reclaim significant space.
1591 0 : if layer_local_page_count != u32::MAX
1592 0 : && layer_local_page_count as f64 / layer_raw_page_count as f64
1593 0 : <= ANCESTOR_COMPACTION_REWRITE_THRESHOLD
1594 : {
1595 0 : debug!(%layer,
1596 0 : "layer has a large share of local pages \
1597 0 : ({layer_local_page_count}/{layer_raw_page_count} > \
1598 0 : {ANCESTOR_COMPACTION_REWRITE_THRESHOLD}), not rewriting",
1599 : );
1600 0 : }
1601 :
1602 : // Don't bother re-writing a layer if it is within the PITR window: it will age-out eventually
1603 : // without incurring the I/O cost of a rewrite.
1604 0 : if layer_desc.get_lsn_range().end >= *latest_gc_cutoff {
1605 0 : debug!(%layer, "Skipping rewrite of layer still in GC window ({} >= {})",
1606 0 : layer_desc.get_lsn_range().end, *latest_gc_cutoff);
1607 0 : continue;
1608 0 : }
1609 :
1610 : // We do not yet implement rewrite of delta layers.
1611 0 : if layer_desc.is_delta() {
1612 0 : debug!(%layer, "Skipping rewrite of delta layer");
1613 0 : continue;
1614 0 : }
1615 :
1616 : // We don't bother rewriting layers that aren't visible, since these won't be needed by
1617 : // reads and will likely be garbage collected soon.
1618 0 : if layer.visibility() != LayerVisibilityHint::Visible {
1619 0 : debug!(%layer, "Skipping rewrite of invisible layer");
1620 0 : continue;
1621 0 : }
1622 :
1623 : // Only rewrite layers if their generations differ. This guarantees:
1624 : // - that local rewrite is safe, as local layer paths will differ between existing layer and rewritten one
1625 : // - that the layer is persistent in remote storage, as we only see old-generation'd layer via loading from remote storage
1626 0 : if layer.metadata().generation == self.generation {
1627 0 : debug!(%layer, "Skipping rewrite, is not from old generation");
1628 0 : continue;
1629 0 : }
1630 :
1631 0 : if layers_to_rewrite.len() >= rewrite_max {
1632 0 : debug!(%layer, "Will rewrite layer on a future compaction, already rewrote {}",
1633 0 : layers_to_rewrite.len()
1634 : );
1635 0 : outcome = CompactionOutcome::Pending;
1636 0 : break;
1637 0 : }
1638 :
1639 : // Fall through: all our conditions for doing a rewrite passed.
1640 0 : layers_to_rewrite.push(layer);
1641 : }
1642 :
1643 : // Drop read lock on layer map before we start doing time-consuming I/O.
1644 0 : drop(layers);
1645 :
1646 : // Drop out early if there's nothing to do.
1647 0 : if layers_to_rewrite.is_empty() && drop_layers.is_empty() {
1648 0 : return Ok(CompactionOutcome::Done);
1649 0 : }
1650 :
1651 0 : info!(
1652 0 : "starting shard ancestor compaction, rewriting {} layers and dropping {} layers, \
1653 0 : checked {layers_checked}/{layers_total} layers \
1654 0 : (latest_gc_cutoff={} pitr_cutoff={:?})",
1655 0 : layers_to_rewrite.len(),
1656 0 : drop_layers.len(),
1657 0 : *latest_gc_cutoff,
1658 : pitr_cutoff,
1659 : );
1660 0 : let started = Instant::now();
1661 :
1662 0 : let mut replace_image_layers = Vec::new();
1663 0 : let total = layers_to_rewrite.len();
1664 :
1665 0 : for (i, layer) in layers_to_rewrite.into_iter().enumerate() {
1666 0 : if self.cancel.is_cancelled() {
1667 0 : return Err(CompactionError::new_cancelled());
1668 0 : }
1669 :
1670 0 : info!(layer=%layer, "rewriting layer after shard split: {}/{}", i, total);
1671 :
1672 0 : let mut image_layer_writer = ImageLayerWriter::new(
1673 0 : self.conf,
1674 0 : self.timeline_id,
1675 0 : self.tenant_shard_id,
1676 0 : &layer.layer_desc().key_range,
1677 0 : layer.layer_desc().image_layer_lsn(),
1678 0 : &self.gate,
1679 0 : self.cancel.clone(),
1680 0 : ctx,
1681 0 : )
1682 0 : .await
1683 0 : .map_err(CompactionError::Other)?;
1684 :
1685 : // Safety of layer rewrites:
1686 : // - We are writing to a different local file path than we are reading from, so the old Layer
1687 : // cannot interfere with the new one.
1688 : // - In the page cache, contents for a particular VirtualFile are stored with a file_id that
1689 : // is different for two layers with the same name (in `ImageLayerInner::new` we always
1690 : // acquire a fresh id from [`crate::page_cache::next_file_id`]. So readers do not risk
1691 : // reading the index from one layer file, and then data blocks from the rewritten layer file.
1692 : // - Any readers that have a reference to the old layer will keep it alive until they are done
1693 : // with it. If they are trying to promote from remote storage, that will fail, but this is the same
1694 : // as for compaction generally: compaction is allowed to delete layers that readers might be trying to use.
1695 : // - We do not run concurrently with other kinds of compaction, so the only layer map writes we race with are:
1696 : // - GC, which at worst witnesses us "undelete" a layer that they just deleted.
1697 : // - ingestion, which only inserts layers, therefore cannot collide with us.
1698 0 : let resident = layer.download_and_keep_resident(ctx).await?;
1699 :
1700 0 : let keys_written = resident
1701 0 : .filter(&self.shard_identity, &mut image_layer_writer, ctx)
1702 0 : .await?;
1703 :
1704 0 : if keys_written > 0 {
1705 0 : let (desc, path) = image_layer_writer
1706 0 : .finish(ctx)
1707 0 : .await
1708 0 : .map_err(CompactionError::Other)?;
1709 0 : let new_layer = Layer::finish_creating(self.conf, self, desc, &path)
1710 0 : .map_err(CompactionError::Other)?;
1711 0 : info!(layer=%new_layer, "rewrote layer, {} -> {} bytes",
1712 0 : layer.metadata().file_size,
1713 0 : new_layer.metadata().file_size);
1714 :
1715 0 : replace_image_layers.push((layer, new_layer));
1716 0 : } else {
1717 0 : // Drop the old layer. Usually for this case we would already have noticed that
1718 0 : // the layer has no data for us with the ShardedRange check above, but
1719 0 : drop_layers.push(layer);
1720 0 : }
1721 :
1722 : // Yield for L0 compaction if necessary, but make sure we update the layer map below
1723 : // with the work we've already done.
1724 0 : if yield_for_l0
1725 0 : && self
1726 0 : .l0_compaction_trigger
1727 0 : .notified()
1728 0 : .now_or_never()
1729 0 : .is_some()
1730 : {
1731 0 : info!("shard ancestor compaction yielding for L0 compaction");
1732 0 : outcome = CompactionOutcome::YieldForL0;
1733 0 : break;
1734 0 : }
1735 : }
1736 :
1737 0 : for layer in &drop_layers {
1738 0 : info!(%layer, old_metadata=?layer.metadata(),
1739 0 : "dropping layer after shard split (no keys for this shard)",
1740 : );
1741 : }
1742 :
1743 : // At this point, we have replaced local layer files with their rewritten form, but not yet uploaded
1744 : // metadata to reflect that. If we restart here, the replaced layer files will look invalid (size mismatch
1745 : // to remote index) and be removed. This is inefficient but safe.
1746 0 : fail::fail_point!("compact-shard-ancestors-localonly");
1747 :
1748 : // Update the LayerMap so that readers will use the new layers, and enqueue it for writing to remote storage
1749 0 : self.rewrite_layers(replace_image_layers, drop_layers)
1750 0 : .await?;
1751 :
1752 0 : fail::fail_point!("compact-shard-ancestors-enqueued");
1753 :
1754 : // We wait for all uploads to complete before finishing this compaction stage. This is not
1755 : // necessary for correctness, but it simplifies testing, and avoids proceeding with another
1756 : // Timeline's compaction while this timeline's uploads may be generating lots of disk I/O
1757 : // load.
1758 0 : if outcome != CompactionOutcome::YieldForL0 {
1759 0 : info!("shard ancestor compaction waiting for uploads");
1760 0 : tokio::select! {
1761 0 : result = self.remote_client.wait_completion() => match result {
1762 0 : Ok(()) => {},
1763 0 : Err(WaitCompletionError::NotInitialized(ni)) => return Err(CompactionError::from(ni)),
1764 : Err(WaitCompletionError::UploadQueueShutDownOrStopped) => {
1765 0 : return Err(CompactionError::new_cancelled());
1766 : }
1767 : },
1768 : // Don't wait if there's L0 compaction to do. We don't need to update the outcome
1769 : // here, because we've already done the actual work.
1770 0 : _ = self.l0_compaction_trigger.notified(), if yield_for_l0 => {},
1771 : }
1772 0 : }
1773 :
1774 0 : info!(
1775 0 : "shard ancestor compaction done in {:.3}s{}",
1776 0 : started.elapsed().as_secs_f64(),
1777 0 : match outcome {
1778 : CompactionOutcome::Pending =>
1779 0 : format!(", with pending work (rewrite_max={rewrite_max})"),
1780 0 : CompactionOutcome::YieldForL0 => String::from(", yielding for L0 compaction"),
1781 0 : CompactionOutcome::Skipped | CompactionOutcome::Done => String::new(),
1782 : }
1783 : );
1784 :
1785 0 : fail::fail_point!("compact-shard-ancestors-persistent");
1786 :
1787 0 : Ok(outcome)
1788 0 : }
1789 :
1790 : /// Update the LayerVisibilityHint of layers covered by image layers, based on whether there is
1791 : /// an image layer between them and the most recent readable LSN (branch point or tip of timeline). The
1792 : /// purpose of the visibility hint is to record which layers need to be available to service reads.
1793 : ///
1794 : /// The result may be used as an input to eviction and secondary downloads to de-prioritize layers
1795 : /// that we know won't be needed for reads.
1796 123 : pub(crate) async fn update_layer_visibility(
1797 123 : &self,
1798 123 : ) -> Result<(), super::layer_manager::Shutdown> {
1799 123 : let head_lsn = self.get_last_record_lsn();
1800 :
1801 : // We will sweep through layers in reverse-LSN order. We only do historic layers. L0 deltas
1802 : // are implicitly left visible, because LayerVisibilityHint's default is Visible, and we never modify it here.
1803 : // Note that L0 deltas _can_ be covered by image layers, but we consider them 'visible' because we anticipate that
1804 : // they will be subject to L0->L1 compaction in the near future.
1805 123 : let layer_manager = self
1806 123 : .layers
1807 123 : .read(LayerManagerLockHolder::GetLayerMapInfo)
1808 123 : .await;
1809 123 : let layer_map = layer_manager.layer_map()?;
1810 :
1811 123 : let readable_points = {
1812 123 : let children = self.gc_info.read().unwrap().retain_lsns.clone();
1813 :
1814 123 : let mut readable_points = Vec::with_capacity(children.len() + 1);
1815 124 : for (child_lsn, _child_timeline_id, is_offloaded) in &children {
1816 1 : if *is_offloaded == MaybeOffloaded::Yes {
1817 0 : continue;
1818 1 : }
1819 1 : readable_points.push(*child_lsn);
1820 : }
1821 123 : readable_points.push(head_lsn);
1822 123 : readable_points
1823 : };
1824 :
1825 123 : let (layer_visibility, covered) = layer_map.get_visibility(readable_points);
1826 313 : for (layer_desc, visibility) in layer_visibility {
1827 190 : // FIXME: a more efficiency bulk zip() through the layers rather than NlogN getting each one
1828 190 : let layer = layer_manager.get_from_desc(&layer_desc);
1829 190 : layer.set_visibility(visibility);
1830 190 : }
1831 :
1832 : // TODO: publish our covered KeySpace to our parent, so that when they update their visibility, they can
1833 : // avoid assuming that everything at a branch point is visible.
1834 123 : drop(covered);
1835 123 : Ok(())
1836 123 : }
1837 :
1838 : /// Collect a bunch of Level 0 layer files, and compact and reshuffle them as
1839 : /// as Level 1 files. Returns whether the L0 layers are fully compacted.
1840 192 : async fn compact_level0(
1841 192 : self: &Arc<Self>,
1842 192 : target_file_size: u64,
1843 192 : force_compaction_ignore_threshold: bool,
1844 192 : force_compaction_lsn: Option<Lsn>,
1845 192 : ctx: &RequestContext,
1846 192 : ) -> Result<CompactionOutcome, CompactionError> {
1847 : let CompactLevel0Phase1Result {
1848 192 : new_layers,
1849 192 : deltas_to_compact,
1850 192 : outcome,
1851 : } = {
1852 192 : let phase1_span = info_span!("compact_level0_phase1");
1853 192 : let ctx = ctx.attached_child();
1854 192 : let stats = CompactLevel0Phase1StatsBuilder {
1855 192 : version: Some(2),
1856 192 : tenant_id: Some(self.tenant_shard_id),
1857 192 : timeline_id: Some(self.timeline_id),
1858 192 : ..Default::default()
1859 192 : };
1860 :
1861 192 : self.compact_level0_phase1(
1862 192 : stats,
1863 192 : target_file_size,
1864 192 : force_compaction_ignore_threshold,
1865 192 : force_compaction_lsn,
1866 192 : &ctx,
1867 192 : )
1868 192 : .instrument(phase1_span)
1869 192 : .await?
1870 : };
1871 :
1872 192 : if new_layers.is_empty() && deltas_to_compact.is_empty() {
1873 : // nothing to do
1874 169 : return Ok(CompactionOutcome::Done);
1875 23 : }
1876 :
1877 23 : self.finish_compact_batch(&new_layers, &Vec::new(), &deltas_to_compact)
1878 23 : .await?;
1879 23 : Ok(outcome)
1880 192 : }
1881 :
1882 : /// Level0 files first phase of compaction, explained in the [`Self::compact_legacy`] comment.
1883 192 : async fn compact_level0_phase1(
1884 192 : self: &Arc<Self>,
1885 192 : mut stats: CompactLevel0Phase1StatsBuilder,
1886 192 : target_file_size: u64,
1887 192 : force_compaction_ignore_threshold: bool,
1888 192 : force_compaction_lsn: Option<Lsn>,
1889 192 : ctx: &RequestContext,
1890 192 : ) -> Result<CompactLevel0Phase1Result, CompactionError> {
1891 192 : let begin = tokio::time::Instant::now();
1892 192 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
1893 192 : let now = tokio::time::Instant::now();
1894 192 : stats.read_lock_acquisition_micros =
1895 192 : DurationRecorder::Recorded(RecordedDuration(now - begin), now);
1896 :
1897 192 : let layers = guard.layer_map()?;
1898 192 : let level0_deltas = layers.level0_deltas();
1899 192 : stats.level0_deltas_count = Some(level0_deltas.len());
1900 :
1901 : // Only compact if enough layers have accumulated.
1902 192 : let threshold = self.get_compaction_threshold();
1903 192 : if level0_deltas.is_empty() || level0_deltas.len() < threshold {
1904 179 : if force_compaction_ignore_threshold {
1905 12 : if !level0_deltas.is_empty() {
1906 10 : info!(
1907 0 : level0_deltas = level0_deltas.len(),
1908 0 : threshold, "too few deltas to compact, but forcing compaction"
1909 : );
1910 : } else {
1911 2 : info!(
1912 0 : level0_deltas = level0_deltas.len(),
1913 0 : threshold, "too few deltas to compact, cannot force compaction"
1914 : );
1915 2 : return Ok(CompactLevel0Phase1Result::default());
1916 : }
1917 : } else {
1918 : // HADRON
1919 167 : let min_lsn = level0_deltas
1920 167 : .iter()
1921 602 : .map(|a| a.get_lsn_range().start)
1922 167 : .reduce(min);
1923 167 : if force_compaction_lsn.is_some()
1924 0 : && min_lsn.is_some()
1925 0 : && min_lsn.unwrap() < force_compaction_lsn.unwrap()
1926 : {
1927 0 : info!(
1928 0 : "forcing L0 compaction of {} L0 deltas. Min lsn: {}, force compaction lsn: {}",
1929 0 : level0_deltas.len(),
1930 0 : min_lsn.unwrap(),
1931 0 : force_compaction_lsn.unwrap()
1932 : );
1933 : } else {
1934 167 : debug!(
1935 0 : level0_deltas = level0_deltas.len(),
1936 0 : threshold, "too few deltas to compact"
1937 : );
1938 167 : return Ok(CompactLevel0Phase1Result::default());
1939 : }
1940 : }
1941 13 : }
1942 :
1943 23 : let mut level0_deltas = level0_deltas
1944 23 : .iter()
1945 201 : .map(|x| guard.get_from_desc(x))
1946 23 : .collect::<Vec<_>>();
1947 :
1948 23 : drop_layer_manager_rlock(guard);
1949 :
1950 : // The is the last LSN that we have seen for L0 compaction in the timeline. This LSN might be updated
1951 : // by the time we finish the compaction. So we need to get it here.
1952 23 : let l0_last_record_lsn = self.get_last_record_lsn();
1953 :
1954 : // Gather the files to compact in this iteration.
1955 : //
1956 : // Start with the oldest Level 0 delta file, and collect any other
1957 : // level 0 files that form a contiguous sequence, such that the end
1958 : // LSN of previous file matches the start LSN of the next file.
1959 : //
1960 : // Note that if the files don't form such a sequence, we might
1961 : // "compact" just a single file. That's a bit pointless, but it allows
1962 : // us to get rid of the level 0 file, and compact the other files on
1963 : // the next iteration. This could probably made smarter, but such
1964 : // "gaps" in the sequence of level 0 files should only happen in case
1965 : // of a crash, partial download from cloud storage, or something like
1966 : // that, so it's not a big deal in practice.
1967 356 : level0_deltas.sort_by_key(|l| l.layer_desc().lsn_range.start);
1968 23 : let mut level0_deltas_iter = level0_deltas.iter();
1969 :
1970 23 : let first_level0_delta = level0_deltas_iter.next().unwrap();
1971 23 : let mut prev_lsn_end = first_level0_delta.layer_desc().lsn_range.end;
1972 23 : let mut deltas_to_compact = Vec::with_capacity(level0_deltas.len());
1973 :
1974 : // Accumulate the size of layers in `deltas_to_compact`
1975 23 : let mut deltas_to_compact_bytes = 0;
1976 :
1977 : // Under normal circumstances, we will accumulate up to compaction_upper_limit L0s of size
1978 : // checkpoint_distance each. To avoid edge cases using extra system resources, bound our
1979 : // work in this function to only operate on this much delta data at once.
1980 : //
1981 : // In general, compaction_threshold should be <= compaction_upper_limit, but in case that
1982 : // the constraint is not respected, we use the larger of the two.
1983 23 : let delta_size_limit = std::cmp::max(
1984 23 : self.get_compaction_upper_limit(),
1985 23 : self.get_compaction_threshold(),
1986 23 : ) as u64
1987 23 : * std::cmp::max(self.get_checkpoint_distance(), DEFAULT_CHECKPOINT_DISTANCE);
1988 :
1989 23 : let mut fully_compacted = true;
1990 :
1991 23 : deltas_to_compact.push(first_level0_delta.download_and_keep_resident(ctx).await?);
1992 201 : for l in level0_deltas_iter {
1993 178 : let lsn_range = &l.layer_desc().lsn_range;
1994 :
1995 178 : if lsn_range.start != prev_lsn_end {
1996 0 : break;
1997 178 : }
1998 178 : deltas_to_compact.push(l.download_and_keep_resident(ctx).await?);
1999 178 : deltas_to_compact_bytes += l.metadata().file_size;
2000 178 : prev_lsn_end = lsn_range.end;
2001 :
2002 178 : if deltas_to_compact_bytes >= delta_size_limit {
2003 0 : info!(
2004 0 : l0_deltas_selected = deltas_to_compact.len(),
2005 0 : l0_deltas_total = level0_deltas.len(),
2006 0 : "L0 compaction picker hit max delta layer size limit: {}",
2007 : delta_size_limit
2008 : );
2009 0 : fully_compacted = false;
2010 :
2011 : // Proceed with compaction, but only a subset of L0s
2012 0 : break;
2013 178 : }
2014 : }
2015 23 : let lsn_range = Range {
2016 23 : start: deltas_to_compact
2017 23 : .first()
2018 23 : .unwrap()
2019 23 : .layer_desc()
2020 23 : .lsn_range
2021 23 : .start,
2022 23 : end: deltas_to_compact.last().unwrap().layer_desc().lsn_range.end,
2023 23 : };
2024 :
2025 23 : info!(
2026 0 : "Starting Level0 compaction in LSN range {}-{} for {} layers ({} deltas in total)",
2027 : lsn_range.start,
2028 : lsn_range.end,
2029 0 : deltas_to_compact.len(),
2030 0 : level0_deltas.len()
2031 : );
2032 :
2033 201 : for l in deltas_to_compact.iter() {
2034 201 : info!("compact includes {l}");
2035 : }
2036 :
2037 : // We don't need the original list of layers anymore. Drop it so that
2038 : // we don't accidentally use it later in the function.
2039 23 : drop(level0_deltas);
2040 :
2041 23 : stats.compaction_prerequisites_micros = stats.read_lock_acquisition_micros.till_now();
2042 :
2043 : // TODO: replace with streaming k-merge
2044 23 : let all_keys = {
2045 23 : let mut all_keys = Vec::new();
2046 201 : for l in deltas_to_compact.iter() {
2047 201 : if self.cancel.is_cancelled() {
2048 0 : return Err(CompactionError::new_cancelled());
2049 201 : }
2050 201 : let delta = l.get_as_delta(ctx).await.map_err(CompactionError::Other)?;
2051 201 : let keys = delta
2052 201 : .index_entries(ctx)
2053 201 : .await
2054 201 : .map_err(CompactionError::Other)?;
2055 201 : all_keys.extend(keys);
2056 : }
2057 : // The current stdlib sorting implementation is designed in a way where it is
2058 : // particularly fast where the slice is made up of sorted sub-ranges.
2059 2137926 : all_keys.sort_by_key(|DeltaEntry { key, lsn, .. }| (*key, *lsn));
2060 23 : all_keys
2061 : };
2062 :
2063 23 : stats.read_lock_held_key_sort_micros = stats.compaction_prerequisites_micros.till_now();
2064 :
2065 : // Determine N largest holes where N is number of compacted layers. The vec is sorted by key range start.
2066 : //
2067 : // A hole is a key range for which this compaction doesn't have any WAL records.
2068 : // Our goal in this compaction iteration is to avoid creating L1s that, in terms of their key range,
2069 : // cover the hole, but actually don't contain any WAL records for that key range.
2070 : // The reason is that the mere stack of L1s (`count_deltas`) triggers image layer creation (`create_image_layers`).
2071 : // That image layer creation would be useless for a hole range covered by L1s that don't contain any WAL records.
2072 : //
2073 : // The algorithm chooses holes as follows.
2074 : // - Slide a 2-window over the keys in key orde to get the hole range (=distance between two keys).
2075 : // - Filter: min threshold on range length
2076 : // - Rank: by coverage size (=number of image layers required to reconstruct each key in the range for which we have any data)
2077 : //
2078 : // For more details, intuition, and some ASCII art see https://github.com/neondatabase/neon/pull/3597#discussion_r1112704451
2079 : #[derive(PartialEq, Eq)]
2080 : struct Hole {
2081 : key_range: Range<Key>,
2082 : coverage_size: usize,
2083 : }
2084 23 : let holes: Vec<Hole> = {
2085 : use std::cmp::Ordering;
2086 : impl Ord for Hole {
2087 0 : fn cmp(&self, other: &Self) -> Ordering {
2088 0 : self.coverage_size.cmp(&other.coverage_size).reverse()
2089 0 : }
2090 : }
2091 : impl PartialOrd for Hole {
2092 0 : fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2093 0 : Some(self.cmp(other))
2094 0 : }
2095 : }
2096 23 : let max_holes = deltas_to_compact.len();
2097 23 : let min_hole_range = (target_file_size / page_cache::PAGE_SZ as u64) as i128;
2098 23 : let min_hole_coverage_size = 3; // TODO: something more flexible?
2099 : // min-heap (reserve space for one more element added before eviction)
2100 23 : let mut heap: BinaryHeap<Hole> = BinaryHeap::with_capacity(max_holes + 1);
2101 23 : let mut prev: Option<Key> = None;
2102 :
2103 1032019 : for &DeltaEntry { key: next_key, .. } in all_keys.iter() {
2104 1032019 : if let Some(prev_key) = prev {
2105 : // just first fast filter, do not create hole entries for metadata keys. The last hole in the
2106 : // compaction is the gap between data key and metadata keys.
2107 1031996 : if next_key.to_i128() - prev_key.to_i128() >= min_hole_range
2108 268 : && !Key::is_metadata_key(&prev_key)
2109 : {
2110 0 : let key_range = prev_key..next_key;
2111 : // Measuring hole by just subtraction of i128 representation of key range boundaries
2112 : // has not so much sense, because largest holes will corresponds field1/field2 changes.
2113 : // But we are mostly interested to eliminate holes which cause generation of excessive image layers.
2114 : // That is why it is better to measure size of hole as number of covering image layers.
2115 0 : let coverage_size = {
2116 : // TODO: optimize this with copy-on-write layer map.
2117 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
2118 0 : let layers = guard.layer_map()?;
2119 0 : layers.image_coverage(&key_range, l0_last_record_lsn).len()
2120 : };
2121 0 : if coverage_size >= min_hole_coverage_size {
2122 0 : heap.push(Hole {
2123 0 : key_range,
2124 0 : coverage_size,
2125 0 : });
2126 0 : if heap.len() > max_holes {
2127 0 : heap.pop(); // remove smallest hole
2128 0 : }
2129 0 : }
2130 1031996 : }
2131 23 : }
2132 1032019 : prev = Some(next_key.next());
2133 : }
2134 23 : let mut holes = heap.into_vec();
2135 23 : holes.sort_unstable_by_key(|hole| hole.key_range.start);
2136 23 : holes
2137 : };
2138 23 : stats.read_lock_held_compute_holes_micros = stats.read_lock_held_key_sort_micros.till_now();
2139 :
2140 23 : if self.cancel.is_cancelled() {
2141 0 : return Err(CompactionError::new_cancelled());
2142 23 : }
2143 :
2144 23 : stats.read_lock_drop_micros = stats.read_lock_held_compute_holes_micros.till_now();
2145 :
2146 : // This iterator walks through all key-value pairs from all the layers
2147 : // we're compacting, in key, LSN order.
2148 : // If there's both a Value::Image and Value::WalRecord for the same (key,lsn),
2149 : // then the Value::Image is ordered before Value::WalRecord.
2150 23 : let mut all_values_iter = {
2151 23 : let mut deltas = Vec::with_capacity(deltas_to_compact.len());
2152 201 : for l in deltas_to_compact.iter() {
2153 201 : let l = l.get_as_delta(ctx).await.map_err(CompactionError::Other)?;
2154 201 : deltas.push(l);
2155 : }
2156 23 : MergeIterator::create_with_options(
2157 23 : &deltas,
2158 23 : &[],
2159 23 : ctx,
2160 23 : 1024 * 8192, /* 8 MiB buffer per layer iterator */
2161 : 1024,
2162 : )
2163 : };
2164 :
2165 : // This iterator walks through all keys and is needed to calculate size used by each key
2166 23 : let mut all_keys_iter = all_keys
2167 23 : .iter()
2168 1032019 : .map(|DeltaEntry { key, lsn, size, .. }| (*key, *lsn, *size))
2169 1031996 : .coalesce(|mut prev, cur| {
2170 : // Coalesce keys that belong to the same key pair.
2171 : // This ensures that compaction doesn't put them
2172 : // into different layer files.
2173 : // Still limit this by the target file size,
2174 : // so that we keep the size of the files in
2175 : // check.
2176 1031996 : if prev.0 == cur.0 && prev.2 < target_file_size {
2177 14352 : prev.2 += cur.2;
2178 14352 : Ok(prev)
2179 : } else {
2180 1017644 : Err((prev, cur))
2181 : }
2182 1031996 : });
2183 :
2184 : // Merge the contents of all the input delta layers into a new set
2185 : // of delta layers, based on the current partitioning.
2186 : //
2187 : // We split the new delta layers on the key dimension. We iterate through the key space, and for each key, check if including the next key to the current output layer we're building would cause the layer to become too large. If so, dump the current output layer and start new one.
2188 : // It's possible that there is a single key with so many page versions that storing all of them in a single layer file
2189 : // would be too large. In that case, we also split on the LSN dimension.
2190 : //
2191 : // LSN
2192 : // ^
2193 : // |
2194 : // | +-----------+ +--+--+--+--+
2195 : // | | | | | | | |
2196 : // | +-----------+ | | | | |
2197 : // | | | | | | | |
2198 : // | +-----------+ ==> | | | | |
2199 : // | | | | | | | |
2200 : // | +-----------+ | | | | |
2201 : // | | | | | | | |
2202 : // | +-----------+ +--+--+--+--+
2203 : // |
2204 : // +--------------> key
2205 : //
2206 : //
2207 : // If one key (X) has a lot of page versions:
2208 : //
2209 : // LSN
2210 : // ^
2211 : // | (X)
2212 : // | +-----------+ +--+--+--+--+
2213 : // | | | | | | | |
2214 : // | +-----------+ | | +--+ |
2215 : // | | | | | | | |
2216 : // | +-----------+ ==> | | | | |
2217 : // | | | | | +--+ |
2218 : // | +-----------+ | | | | |
2219 : // | | | | | | | |
2220 : // | +-----------+ +--+--+--+--+
2221 : // |
2222 : // +--------------> key
2223 : // TODO: this actually divides the layers into fixed-size chunks, not
2224 : // based on the partitioning.
2225 : //
2226 : // TODO: we should also opportunistically materialize and
2227 : // garbage collect what we can.
2228 23 : let mut new_layers = Vec::new();
2229 23 : let mut prev_key: Option<Key> = None;
2230 23 : let mut writer: Option<DeltaLayerWriter> = None;
2231 23 : let mut key_values_total_size = 0u64;
2232 23 : let mut dup_start_lsn: Lsn = Lsn::INVALID; // start LSN of layer containing values of the single key
2233 23 : let mut dup_end_lsn: Lsn = Lsn::INVALID; // end LSN of layer containing values of the single key
2234 23 : let mut next_hole = 0; // index of next hole in holes vector
2235 :
2236 23 : let mut keys = 0;
2237 :
2238 1032042 : while let Some((key, lsn, value)) = all_values_iter
2239 1032042 : .next()
2240 1032042 : .await
2241 1032042 : .map_err(CompactionError::Other)?
2242 : {
2243 1032019 : keys += 1;
2244 :
2245 1032019 : if keys % 32_768 == 0 && self.cancel.is_cancelled() {
2246 : // avoid hitting the cancellation token on every key. in benches, we end up
2247 : // shuffling an order of million keys per layer, this means we'll check it
2248 : // around tens of times per layer.
2249 0 : return Err(CompactionError::new_cancelled());
2250 1032019 : }
2251 :
2252 1032019 : let same_key = prev_key == Some(key);
2253 : // We need to check key boundaries once we reach next key or end of layer with the same key
2254 1032019 : if !same_key || lsn == dup_end_lsn {
2255 1017667 : let mut next_key_size = 0u64;
2256 1017667 : let is_dup_layer = dup_end_lsn.is_valid();
2257 1017667 : dup_start_lsn = Lsn::INVALID;
2258 1017667 : if !same_key {
2259 1017667 : dup_end_lsn = Lsn::INVALID;
2260 1017667 : }
2261 : // Determine size occupied by this key. We stop at next key or when size becomes larger than target_file_size
2262 1017667 : for (next_key, next_lsn, next_size) in all_keys_iter.by_ref() {
2263 1017667 : next_key_size = next_size;
2264 1017667 : if key != next_key {
2265 1017644 : if dup_end_lsn.is_valid() {
2266 0 : // We are writting segment with duplicates:
2267 0 : // place all remaining values of this key in separate segment
2268 0 : dup_start_lsn = dup_end_lsn; // new segments starts where old stops
2269 0 : dup_end_lsn = lsn_range.end; // there are no more values of this key till end of LSN range
2270 1017644 : }
2271 1017644 : break;
2272 23 : }
2273 23 : key_values_total_size += next_size;
2274 : // Check if it is time to split segment: if total keys size is larger than target file size.
2275 : // We need to avoid generation of empty segments if next_size > target_file_size.
2276 23 : if key_values_total_size > target_file_size && lsn != next_lsn {
2277 : // Split key between multiple layers: such layer can contain only single key
2278 0 : dup_start_lsn = if dup_end_lsn.is_valid() {
2279 0 : dup_end_lsn // new segment with duplicates starts where old one stops
2280 : } else {
2281 0 : lsn // start with the first LSN for this key
2282 : };
2283 0 : dup_end_lsn = next_lsn; // upper LSN boundary is exclusive
2284 0 : break;
2285 23 : }
2286 : }
2287 : // handle case when loop reaches last key: in this case dup_end is non-zero but dup_start is not set.
2288 1017667 : if dup_end_lsn.is_valid() && !dup_start_lsn.is_valid() {
2289 0 : dup_start_lsn = dup_end_lsn;
2290 0 : dup_end_lsn = lsn_range.end;
2291 1017667 : }
2292 1017667 : if writer.is_some() {
2293 1017644 : let written_size = writer.as_mut().unwrap().size();
2294 1017644 : let contains_hole =
2295 1017644 : next_hole < holes.len() && key >= holes[next_hole].key_range.end;
2296 : // check if key cause layer overflow or contains hole...
2297 1017644 : if is_dup_layer
2298 1017644 : || dup_end_lsn.is_valid()
2299 1017644 : || written_size + key_values_total_size > target_file_size
2300 1017504 : || contains_hole
2301 : {
2302 : // ... if so, flush previous layer and prepare to write new one
2303 140 : let (desc, path) = writer
2304 140 : .take()
2305 140 : .unwrap()
2306 140 : .finish(prev_key.unwrap().next(), ctx)
2307 140 : .await
2308 140 : .map_err(CompactionError::Other)?;
2309 140 : let new_delta = Layer::finish_creating(self.conf, self, desc, &path)
2310 140 : .map_err(CompactionError::Other)?;
2311 :
2312 140 : new_layers.push(new_delta);
2313 140 : writer = None;
2314 :
2315 140 : if contains_hole {
2316 0 : // skip hole
2317 0 : next_hole += 1;
2318 140 : }
2319 1017504 : }
2320 23 : }
2321 : // Remember size of key value because at next iteration we will access next item
2322 1017667 : key_values_total_size = next_key_size;
2323 14352 : }
2324 1032019 : fail_point!("delta-layer-writer-fail-before-finish", |_| {
2325 0 : Err(CompactionError::Other(anyhow::anyhow!(
2326 0 : "failpoint delta-layer-writer-fail-before-finish"
2327 0 : )))
2328 0 : });
2329 :
2330 1032019 : if !self.shard_identity.is_key_disposable(&key) {
2331 1032019 : if writer.is_none() {
2332 163 : if self.cancel.is_cancelled() {
2333 : // to be somewhat responsive to cancellation, check for each new layer
2334 0 : return Err(CompactionError::new_cancelled());
2335 163 : }
2336 : // Create writer if not initiaized yet
2337 163 : writer = Some(
2338 163 : DeltaLayerWriter::new(
2339 163 : self.conf,
2340 163 : self.timeline_id,
2341 163 : self.tenant_shard_id,
2342 163 : key,
2343 163 : if dup_end_lsn.is_valid() {
2344 : // this is a layer containing slice of values of the same key
2345 0 : debug!("Create new dup layer {}..{}", dup_start_lsn, dup_end_lsn);
2346 0 : dup_start_lsn..dup_end_lsn
2347 : } else {
2348 163 : debug!("Create new layer {}..{}", lsn_range.start, lsn_range.end);
2349 163 : lsn_range.clone()
2350 : },
2351 163 : &self.gate,
2352 163 : self.cancel.clone(),
2353 163 : ctx,
2354 : )
2355 163 : .await
2356 163 : .map_err(CompactionError::Other)?,
2357 : );
2358 :
2359 163 : keys = 0;
2360 1031856 : }
2361 :
2362 1032019 : writer
2363 1032019 : .as_mut()
2364 1032019 : .unwrap()
2365 1032019 : .put_value(key, lsn, value, ctx)
2366 1032019 : .await?;
2367 : } else {
2368 0 : let owner = self.shard_identity.get_shard_number(&key);
2369 :
2370 : // This happens after a shard split, when we're compacting an L0 created by our parent shard
2371 0 : debug!("dropping key {key} during compaction (it belongs on shard {owner})");
2372 : }
2373 :
2374 1032019 : if !new_layers.is_empty() {
2375 9893 : fail_point!("after-timeline-compacted-first-L1");
2376 1022126 : }
2377 :
2378 1032019 : prev_key = Some(key);
2379 : }
2380 23 : if let Some(writer) = writer {
2381 23 : let (desc, path) = writer
2382 23 : .finish(prev_key.unwrap().next(), ctx)
2383 23 : .await
2384 23 : .map_err(CompactionError::Other)?;
2385 23 : let new_delta = Layer::finish_creating(self.conf, self, desc, &path)
2386 23 : .map_err(CompactionError::Other)?;
2387 23 : new_layers.push(new_delta);
2388 0 : }
2389 :
2390 : // Sync layers
2391 23 : if !new_layers.is_empty() {
2392 : // Print a warning if the created layer is larger than double the target size
2393 : // Add two pages for potential overhead. This should in theory be already
2394 : // accounted for in the target calculation, but for very small targets,
2395 : // we still might easily hit the limit otherwise.
2396 23 : let warn_limit = target_file_size * 2 + page_cache::PAGE_SZ as u64 * 2;
2397 163 : for layer in new_layers.iter() {
2398 163 : if layer.layer_desc().file_size > warn_limit {
2399 0 : warn!(
2400 : %layer,
2401 0 : "created delta file of size {} larger than double of target of {target_file_size}", layer.layer_desc().file_size
2402 : );
2403 163 : }
2404 : }
2405 :
2406 : // The writer.finish() above already did the fsync of the inodes.
2407 : // We just need to fsync the directory in which these inodes are linked,
2408 : // which we know to be the timeline directory.
2409 : //
2410 : // We use fatal_err() below because the after writer.finish() returns with success,
2411 : // the in-memory state of the filesystem already has the layer file in its final place,
2412 : // and subsequent pageserver code could think it's durable while it really isn't.
2413 23 : let timeline_dir = VirtualFile::open(
2414 23 : &self
2415 23 : .conf
2416 23 : .timeline_path(&self.tenant_shard_id, &self.timeline_id),
2417 23 : ctx,
2418 23 : )
2419 23 : .await
2420 23 : .fatal_err("VirtualFile::open for timeline dir fsync");
2421 23 : timeline_dir
2422 23 : .sync_all()
2423 23 : .await
2424 23 : .fatal_err("VirtualFile::sync_all timeline dir");
2425 0 : }
2426 :
2427 23 : stats.write_layer_files_micros = stats.read_lock_drop_micros.till_now();
2428 23 : stats.new_deltas_count = Some(new_layers.len());
2429 163 : stats.new_deltas_size = Some(new_layers.iter().map(|l| l.layer_desc().file_size).sum());
2430 :
2431 23 : match TryInto::<CompactLevel0Phase1Stats>::try_into(stats)
2432 23 : .and_then(|stats| serde_json::to_string(&stats).context("serde_json::to_string"))
2433 : {
2434 23 : Ok(stats_json) => {
2435 23 : info!(
2436 0 : stats_json = stats_json.as_str(),
2437 0 : "compact_level0_phase1 stats available"
2438 : )
2439 : }
2440 0 : Err(e) => {
2441 0 : warn!("compact_level0_phase1 stats failed to serialize: {:#}", e);
2442 : }
2443 : }
2444 :
2445 : // Without this, rustc complains about deltas_to_compact still
2446 : // being borrowed when we `.into_iter()` below.
2447 23 : drop(all_values_iter);
2448 :
2449 : Ok(CompactLevel0Phase1Result {
2450 23 : new_layers,
2451 23 : deltas_to_compact: deltas_to_compact
2452 23 : .into_iter()
2453 201 : .map(|x| x.drop_eviction_guard())
2454 23 : .collect::<Vec<_>>(),
2455 23 : outcome: if fully_compacted {
2456 23 : CompactionOutcome::Done
2457 : } else {
2458 0 : CompactionOutcome::Pending
2459 : },
2460 : })
2461 192 : }
2462 : }
2463 :
2464 : #[derive(Default)]
2465 : struct CompactLevel0Phase1Result {
2466 : new_layers: Vec<ResidentLayer>,
2467 : deltas_to_compact: Vec<Layer>,
2468 : // Whether we have included all L0 layers, or selected only part of them due to the
2469 : // L0 compaction size limit.
2470 : outcome: CompactionOutcome,
2471 : }
2472 :
2473 : #[derive(Default)]
2474 : struct CompactLevel0Phase1StatsBuilder {
2475 : version: Option<u64>,
2476 : tenant_id: Option<TenantShardId>,
2477 : timeline_id: Option<TimelineId>,
2478 : read_lock_acquisition_micros: DurationRecorder,
2479 : read_lock_held_key_sort_micros: DurationRecorder,
2480 : compaction_prerequisites_micros: DurationRecorder,
2481 : read_lock_held_compute_holes_micros: DurationRecorder,
2482 : read_lock_drop_micros: DurationRecorder,
2483 : write_layer_files_micros: DurationRecorder,
2484 : level0_deltas_count: Option<usize>,
2485 : new_deltas_count: Option<usize>,
2486 : new_deltas_size: Option<u64>,
2487 : }
2488 :
2489 : #[derive(serde::Serialize)]
2490 : struct CompactLevel0Phase1Stats {
2491 : version: u64,
2492 : tenant_id: TenantShardId,
2493 : timeline_id: TimelineId,
2494 : read_lock_acquisition_micros: RecordedDuration,
2495 : read_lock_held_key_sort_micros: RecordedDuration,
2496 : compaction_prerequisites_micros: RecordedDuration,
2497 : read_lock_held_compute_holes_micros: RecordedDuration,
2498 : read_lock_drop_micros: RecordedDuration,
2499 : write_layer_files_micros: RecordedDuration,
2500 : level0_deltas_count: usize,
2501 : new_deltas_count: usize,
2502 : new_deltas_size: u64,
2503 : }
2504 :
2505 : impl TryFrom<CompactLevel0Phase1StatsBuilder> for CompactLevel0Phase1Stats {
2506 : type Error = anyhow::Error;
2507 :
2508 23 : fn try_from(value: CompactLevel0Phase1StatsBuilder) -> Result<Self, Self::Error> {
2509 : Ok(Self {
2510 23 : version: value.version.ok_or_else(|| anyhow!("version not set"))?,
2511 23 : tenant_id: value
2512 23 : .tenant_id
2513 23 : .ok_or_else(|| anyhow!("tenant_id not set"))?,
2514 23 : timeline_id: value
2515 23 : .timeline_id
2516 23 : .ok_or_else(|| anyhow!("timeline_id not set"))?,
2517 23 : read_lock_acquisition_micros: value
2518 23 : .read_lock_acquisition_micros
2519 23 : .into_recorded()
2520 23 : .ok_or_else(|| anyhow!("read_lock_acquisition_micros not set"))?,
2521 23 : read_lock_held_key_sort_micros: value
2522 23 : .read_lock_held_key_sort_micros
2523 23 : .into_recorded()
2524 23 : .ok_or_else(|| anyhow!("read_lock_held_key_sort_micros not set"))?,
2525 23 : compaction_prerequisites_micros: value
2526 23 : .compaction_prerequisites_micros
2527 23 : .into_recorded()
2528 23 : .ok_or_else(|| anyhow!("read_lock_held_prerequisites_micros not set"))?,
2529 23 : read_lock_held_compute_holes_micros: value
2530 23 : .read_lock_held_compute_holes_micros
2531 23 : .into_recorded()
2532 23 : .ok_or_else(|| anyhow!("read_lock_held_compute_holes_micros not set"))?,
2533 23 : read_lock_drop_micros: value
2534 23 : .read_lock_drop_micros
2535 23 : .into_recorded()
2536 23 : .ok_or_else(|| anyhow!("read_lock_drop_micros not set"))?,
2537 23 : write_layer_files_micros: value
2538 23 : .write_layer_files_micros
2539 23 : .into_recorded()
2540 23 : .ok_or_else(|| anyhow!("write_layer_files_micros not set"))?,
2541 23 : level0_deltas_count: value
2542 23 : .level0_deltas_count
2543 23 : .ok_or_else(|| anyhow!("level0_deltas_count not set"))?,
2544 23 : new_deltas_count: value
2545 23 : .new_deltas_count
2546 23 : .ok_or_else(|| anyhow!("new_deltas_count not set"))?,
2547 23 : new_deltas_size: value
2548 23 : .new_deltas_size
2549 23 : .ok_or_else(|| anyhow!("new_deltas_size not set"))?,
2550 : })
2551 23 : }
2552 : }
2553 :
2554 : impl Timeline {
2555 : /// Entry point for new tiered compaction algorithm.
2556 : ///
2557 : /// All the real work is in the implementation in the pageserver_compaction
2558 : /// crate. The code here would apply to any algorithm implemented by the
2559 : /// same interface, but tiered is the only one at the moment.
2560 : ///
2561 : /// TODO: cancellation
2562 0 : pub(crate) async fn compact_tiered(
2563 0 : self: &Arc<Self>,
2564 0 : _cancel: &CancellationToken,
2565 0 : ctx: &RequestContext,
2566 0 : ) -> Result<(), CompactionError> {
2567 0 : let fanout = self.get_compaction_threshold() as u64;
2568 0 : let target_file_size = self.get_checkpoint_distance();
2569 :
2570 : // Find the top of the historical layers
2571 0 : let end_lsn = {
2572 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
2573 0 : let layers = guard.layer_map()?;
2574 :
2575 0 : let l0_deltas = layers.level0_deltas();
2576 :
2577 : // As an optimization, if we find that there are too few L0 layers,
2578 : // bail out early. We know that the compaction algorithm would do
2579 : // nothing in that case.
2580 0 : if l0_deltas.len() < fanout as usize {
2581 : // doesn't need compacting
2582 0 : return Ok(());
2583 0 : }
2584 0 : l0_deltas.iter().map(|l| l.lsn_range.end).max().unwrap()
2585 : };
2586 :
2587 : // Is the timeline being deleted?
2588 0 : if self.is_stopping() {
2589 0 : trace!("Dropping out of compaction on timeline shutdown");
2590 0 : return Err(CompactionError::new_cancelled());
2591 0 : }
2592 :
2593 0 : let (dense_ks, _sparse_ks) = self
2594 0 : .collect_keyspace(end_lsn, ctx)
2595 0 : .await
2596 0 : .map_err(CompactionError::from_collect_keyspace)?;
2597 : // TODO(chi): ignore sparse_keyspace for now, compact it in the future.
2598 0 : let mut adaptor = TimelineAdaptor::new(self, (end_lsn, dense_ks));
2599 :
2600 0 : pageserver_compaction::compact_tiered::compact_tiered(
2601 0 : &mut adaptor,
2602 0 : end_lsn,
2603 0 : target_file_size,
2604 0 : fanout,
2605 0 : ctx,
2606 0 : )
2607 0 : .await
2608 : // TODO: compact_tiered needs to return CompactionError
2609 0 : .map_err(CompactionError::Other)?;
2610 :
2611 0 : adaptor.flush_updates().await?;
2612 0 : Ok(())
2613 0 : }
2614 :
2615 : /// Take a list of images and deltas, produce images and deltas according to GC horizon and retain_lsns.
2616 : ///
2617 : /// It takes a key, the values of the key within the compaction process, a GC horizon, and all retain_lsns below the horizon.
2618 : /// For now, it requires the `accumulated_values` contains the full history of the key (i.e., the key with the lowest LSN is
2619 : /// an image or a WAL not requiring a base image). This restriction will be removed once we implement gc-compaction on branch.
2620 : ///
2621 : /// The function returns the deltas and the base image that need to be placed at each of the retain LSN. For example, we have:
2622 : ///
2623 : /// A@0x10, +B@0x20, +C@0x30, +D@0x40, +E@0x50, +F@0x60
2624 : /// horizon = 0x50, retain_lsn = 0x20, 0x40, delta_threshold=3
2625 : ///
2626 : /// The function will produce:
2627 : ///
2628 : /// ```plain
2629 : /// 0x20(retain_lsn) -> img=AB@0x20 always produce a single image below the lowest retain LSN
2630 : /// 0x40(retain_lsn) -> deltas=[+C@0x30, +D@0x40] two deltas since the last base image, keeping the deltas
2631 : /// 0x50(horizon) -> deltas=[ABCDE@0x50] three deltas since the last base image, generate an image but put it in the delta
2632 : /// above_horizon -> deltas=[+F@0x60] full history above the horizon
2633 : /// ```
2634 : ///
2635 : /// Note that `accumulated_values` must be sorted by LSN and should belong to a single key.
2636 : #[allow(clippy::too_many_arguments)]
2637 324 : pub(crate) async fn generate_key_retention(
2638 324 : self: &Arc<Timeline>,
2639 324 : key: Key,
2640 324 : full_history: &[(Key, Lsn, Value)],
2641 324 : horizon: Lsn,
2642 324 : retain_lsn_below_horizon: &[Lsn],
2643 324 : delta_threshold_cnt: usize,
2644 324 : base_img_from_ancestor: Option<(Key, Lsn, Bytes)>,
2645 324 : verification: bool,
2646 324 : ) -> anyhow::Result<KeyHistoryRetention> {
2647 : // Pre-checks for the invariants
2648 :
2649 324 : let debug_mode = cfg!(debug_assertions) || cfg!(feature = "testing");
2650 :
2651 324 : if debug_mode {
2652 786 : for (log_key, _, _) in full_history {
2653 462 : assert_eq!(log_key, &key, "mismatched key");
2654 : }
2655 324 : for i in 1..full_history.len() {
2656 138 : assert!(full_history[i - 1].1 <= full_history[i].1, "unordered LSN");
2657 138 : if full_history[i - 1].1 == full_history[i].1 {
2658 0 : assert!(
2659 0 : matches!(full_history[i - 1].2, Value::Image(_)),
2660 0 : "unordered delta/image, or duplicated delta"
2661 : );
2662 138 : }
2663 : }
2664 : // There was an assertion for no base image that checks if the first
2665 : // record in the history is `will_init` before, but it was removed.
2666 : // This is explained in the test cases for generate_key_retention.
2667 : // Search "incomplete history" for more information.
2668 714 : for lsn in retain_lsn_below_horizon {
2669 390 : assert!(lsn < &horizon, "retain lsn must be below horizon")
2670 : }
2671 324 : for i in 1..retain_lsn_below_horizon.len() {
2672 178 : assert!(
2673 178 : retain_lsn_below_horizon[i - 1] <= retain_lsn_below_horizon[i],
2674 0 : "unordered LSN"
2675 : );
2676 : }
2677 0 : }
2678 324 : let has_ancestor = base_img_from_ancestor.is_some();
2679 : // Step 1: split history into len(retain_lsn_below_horizon) + 2 buckets, where the last bucket is for all deltas above the horizon,
2680 : // and the second-to-last bucket is for the horizon. Each bucket contains lsn_last_bucket < deltas <= lsn_this_bucket.
2681 324 : let (mut split_history, lsn_split_points) = {
2682 324 : let mut split_history = Vec::new();
2683 324 : split_history.resize_with(retain_lsn_below_horizon.len() + 2, Vec::new);
2684 324 : let mut lsn_split_points = Vec::with_capacity(retain_lsn_below_horizon.len() + 1);
2685 714 : for lsn in retain_lsn_below_horizon {
2686 390 : lsn_split_points.push(*lsn);
2687 390 : }
2688 324 : lsn_split_points.push(horizon);
2689 324 : let mut current_idx = 0;
2690 786 : for item @ (_, lsn, _) in full_history {
2691 584 : while current_idx < lsn_split_points.len() && *lsn > lsn_split_points[current_idx] {
2692 122 : current_idx += 1;
2693 122 : }
2694 462 : split_history[current_idx].push(item);
2695 : }
2696 324 : (split_history, lsn_split_points)
2697 : };
2698 : // Step 2: filter out duplicated records due to the k-merge of image/delta layers
2699 1362 : for split_for_lsn in &mut split_history {
2700 1038 : let mut prev_lsn = None;
2701 1038 : let mut new_split_for_lsn = Vec::with_capacity(split_for_lsn.len());
2702 1038 : for record @ (_, lsn, _) in std::mem::take(split_for_lsn) {
2703 462 : if let Some(prev_lsn) = &prev_lsn {
2704 62 : if *prev_lsn == lsn {
2705 : // The case that we have an LSN with both data from the delta layer and the image layer. As
2706 : // `ValueWrapper` ensures that an image is ordered before a delta at the same LSN, we simply
2707 : // drop this delta and keep the image.
2708 : //
2709 : // For example, we have delta layer key1@0x10, key1@0x20, and image layer key1@0x10, we will
2710 : // keep the image for key1@0x10 and the delta for key1@0x20. key1@0x10 delta will be simply
2711 : // dropped.
2712 : //
2713 : // TODO: in case we have both delta + images for a given LSN and it does not exceed the delta
2714 : // threshold, we could have kept delta instead to save space. This is an optimization for the future.
2715 0 : continue;
2716 62 : }
2717 400 : }
2718 462 : prev_lsn = Some(lsn);
2719 462 : new_split_for_lsn.push(record);
2720 : }
2721 1038 : *split_for_lsn = new_split_for_lsn;
2722 : }
2723 : // Step 3: generate images when necessary
2724 324 : let mut retention = Vec::with_capacity(split_history.len());
2725 324 : let mut records_since_last_image = 0;
2726 324 : let batch_cnt = split_history.len();
2727 324 : assert!(
2728 324 : batch_cnt >= 2,
2729 0 : "should have at least below + above horizon batches"
2730 : );
2731 324 : let mut replay_history: Vec<(Key, Lsn, Value)> = Vec::new();
2732 324 : if let Some((key, lsn, ref img)) = base_img_from_ancestor {
2733 21 : replay_history.push((key, lsn, Value::Image(img.clone())));
2734 303 : }
2735 :
2736 : /// Generate debug information for the replay history
2737 0 : fn generate_history_trace(replay_history: &[(Key, Lsn, Value)]) -> String {
2738 : use std::fmt::Write;
2739 0 : let mut output = String::new();
2740 0 : if let Some((key, _, _)) = replay_history.first() {
2741 0 : write!(output, "key={key} ").unwrap();
2742 0 : let mut cnt = 0;
2743 0 : for (_, lsn, val) in replay_history {
2744 0 : if val.is_image() {
2745 0 : write!(output, "i@{lsn} ").unwrap();
2746 0 : } else if val.will_init() {
2747 0 : write!(output, "di@{lsn} ").unwrap();
2748 0 : } else {
2749 0 : write!(output, "d@{lsn} ").unwrap();
2750 0 : }
2751 0 : cnt += 1;
2752 0 : if cnt >= 128 {
2753 0 : write!(output, "... and more").unwrap();
2754 0 : break;
2755 0 : }
2756 : }
2757 0 : } else {
2758 0 : write!(output, "<no history>").unwrap();
2759 0 : }
2760 0 : output
2761 0 : }
2762 :
2763 0 : fn generate_debug_trace(
2764 0 : replay_history: Option<&[(Key, Lsn, Value)]>,
2765 0 : full_history: &[(Key, Lsn, Value)],
2766 0 : lsns: &[Lsn],
2767 0 : horizon: Lsn,
2768 0 : ) -> String {
2769 : use std::fmt::Write;
2770 0 : let mut output = String::new();
2771 0 : if let Some(replay_history) = replay_history {
2772 0 : writeln!(
2773 0 : output,
2774 0 : "replay_history: {}",
2775 0 : generate_history_trace(replay_history)
2776 0 : )
2777 0 : .unwrap();
2778 0 : } else {
2779 0 : writeln!(output, "replay_history: <disabled>",).unwrap();
2780 0 : }
2781 0 : writeln!(
2782 0 : output,
2783 0 : "full_history: {}",
2784 0 : generate_history_trace(full_history)
2785 : )
2786 0 : .unwrap();
2787 0 : writeln!(
2788 0 : output,
2789 0 : "when processing: [{}] horizon={}",
2790 0 : lsns.iter().map(|l| format!("{l}")).join(","),
2791 : horizon
2792 : )
2793 0 : .unwrap();
2794 0 : output
2795 0 : }
2796 :
2797 324 : let mut key_exists = false;
2798 1037 : for (i, split_for_lsn) in split_history.into_iter().enumerate() {
2799 : // TODO: there could be image keys inside the splits, and we can compute records_since_last_image accordingly.
2800 1037 : records_since_last_image += split_for_lsn.len();
2801 : // Whether to produce an image into the final layer files
2802 1037 : let produce_image = if i == 0 && !has_ancestor {
2803 : // We always generate images for the first batch (below horizon / lowest retain_lsn)
2804 303 : true
2805 734 : } else if i == batch_cnt - 1 {
2806 : // Do not generate images for the last batch (above horizon)
2807 323 : false
2808 411 : } else if records_since_last_image == 0 {
2809 322 : false
2810 89 : } else if records_since_last_image >= delta_threshold_cnt {
2811 : // Generate images when there are too many records
2812 3 : true
2813 : } else {
2814 86 : false
2815 : };
2816 1037 : replay_history.extend(split_for_lsn.iter().map(|x| (*x).clone()));
2817 : // Only retain the items after the last image record
2818 1277 : for idx in (0..replay_history.len()).rev() {
2819 1277 : if replay_history[idx].2.will_init() {
2820 1037 : replay_history = replay_history[idx..].to_vec();
2821 1037 : break;
2822 240 : }
2823 : }
2824 1037 : if replay_history.is_empty() && !key_exists {
2825 : // The key does not exist at earlier LSN, we can skip this iteration.
2826 0 : retention.push(Vec::new());
2827 0 : continue;
2828 1037 : } else {
2829 1037 : key_exists = true;
2830 1037 : }
2831 1037 : let Some((_, _, val)) = replay_history.first() else {
2832 0 : unreachable!("replay history should not be empty once it exists")
2833 : };
2834 1037 : if !val.will_init() {
2835 0 : return Err(anyhow::anyhow!("invalid history, no base image")).with_context(|| {
2836 0 : generate_debug_trace(
2837 0 : Some(&replay_history),
2838 0 : full_history,
2839 0 : retain_lsn_below_horizon,
2840 0 : horizon,
2841 : )
2842 0 : });
2843 1037 : }
2844 : // Whether to reconstruct the image. In debug mode, we will generate an image
2845 : // at every retain_lsn to ensure data is not corrupted, but we won't put the
2846 : // image into the final layer.
2847 1037 : let img_and_lsn = if produce_image {
2848 306 : records_since_last_image = 0;
2849 306 : let replay_history_for_debug = if debug_mode {
2850 306 : Some(replay_history.clone())
2851 : } else {
2852 0 : None
2853 : };
2854 306 : let replay_history_for_debug_ref = replay_history_for_debug.as_deref();
2855 306 : let history = std::mem::take(&mut replay_history);
2856 306 : let mut img = None;
2857 306 : let mut records = Vec::with_capacity(history.len());
2858 306 : if let (_, lsn, Value::Image(val)) = history.first().as_ref().unwrap() {
2859 295 : img = Some((*lsn, val.clone()));
2860 295 : for (_, lsn, val) in history.into_iter().skip(1) {
2861 20 : let Value::WalRecord(rec) = val else {
2862 0 : return Err(anyhow::anyhow!(
2863 0 : "invalid record, first record is image, expect walrecords"
2864 0 : ))
2865 0 : .with_context(|| {
2866 0 : generate_debug_trace(
2867 0 : replay_history_for_debug_ref,
2868 0 : full_history,
2869 0 : retain_lsn_below_horizon,
2870 0 : horizon,
2871 : )
2872 0 : });
2873 : };
2874 20 : records.push((lsn, rec));
2875 : }
2876 : } else {
2877 18 : for (_, lsn, val) in history.into_iter() {
2878 18 : let Value::WalRecord(rec) = val else {
2879 0 : return Err(anyhow::anyhow!("invalid record, first record is walrecord, expect rest are walrecord"))
2880 0 : .with_context(|| generate_debug_trace(
2881 0 : replay_history_for_debug_ref,
2882 0 : full_history,
2883 0 : retain_lsn_below_horizon,
2884 0 : horizon,
2885 : ));
2886 : };
2887 18 : records.push((lsn, rec));
2888 : }
2889 : }
2890 : // WAL redo requires records in the reverse LSN order
2891 306 : records.reverse();
2892 306 : let state = ValueReconstructState { img, records };
2893 : // last batch does not generate image so i is always in range, unless we force generate
2894 : // an image during testing
2895 306 : let request_lsn = if i >= lsn_split_points.len() {
2896 0 : Lsn::MAX
2897 : } else {
2898 306 : lsn_split_points[i]
2899 : };
2900 306 : let img = self
2901 306 : .reconstruct_value(key, request_lsn, state, RedoAttemptType::GcCompaction)
2902 306 : .await?;
2903 305 : Some((request_lsn, img))
2904 : } else {
2905 731 : None
2906 : };
2907 1036 : if produce_image {
2908 305 : let (request_lsn, img) = img_and_lsn.unwrap();
2909 305 : replay_history.push((key, request_lsn, Value::Image(img.clone())));
2910 305 : retention.push(vec![(request_lsn, Value::Image(img))]);
2911 305 : } else {
2912 731 : let deltas = split_for_lsn
2913 731 : .iter()
2914 731 : .map(|(_, lsn, value)| (*lsn, value.clone()))
2915 731 : .collect_vec();
2916 731 : retention.push(deltas);
2917 : }
2918 : }
2919 323 : let mut result = Vec::with_capacity(retention.len());
2920 323 : assert_eq!(retention.len(), lsn_split_points.len() + 1);
2921 1036 : for (idx, logs) in retention.into_iter().enumerate() {
2922 1036 : if idx == lsn_split_points.len() {
2923 323 : let retention = KeyHistoryRetention {
2924 323 : below_horizon: result,
2925 323 : above_horizon: KeyLogAtLsn(logs),
2926 323 : };
2927 323 : if verification {
2928 323 : retention
2929 323 : .verify(key, &base_img_from_ancestor, full_history, self)
2930 323 : .await?;
2931 0 : }
2932 323 : return Ok(retention);
2933 713 : } else {
2934 713 : result.push((lsn_split_points[idx], KeyLogAtLsn(logs)));
2935 713 : }
2936 : }
2937 0 : unreachable!("key retention is empty")
2938 324 : }
2939 :
2940 : /// Check how much space is left on the disk
2941 27 : async fn check_available_space(self: &Arc<Self>) -> anyhow::Result<u64> {
2942 27 : let tenants_dir = self.conf.tenants_path();
2943 :
2944 27 : let stat = Statvfs::get(&tenants_dir, None)
2945 27 : .context("statvfs failed, presumably directory got unlinked")?;
2946 :
2947 27 : let (avail_bytes, _) = stat.get_avail_total_bytes();
2948 :
2949 27 : Ok(avail_bytes)
2950 27 : }
2951 :
2952 : /// Check if the compaction can proceed safely without running out of space. We assume the size
2953 : /// upper bound of the produced files of a compaction job is the same as all layers involved in
2954 : /// the compaction. Therefore, we need `2 * layers_to_be_compacted_size` at least to do a
2955 : /// compaction.
2956 27 : async fn check_compaction_space(
2957 27 : self: &Arc<Self>,
2958 27 : layer_selection: &[Layer],
2959 27 : ) -> Result<(), CompactionError> {
2960 27 : let available_space = self
2961 27 : .check_available_space()
2962 27 : .await
2963 27 : .map_err(CompactionError::Other)?;
2964 27 : let mut remote_layer_size = 0;
2965 27 : let mut all_layer_size = 0;
2966 106 : for layer in layer_selection {
2967 79 : let needs_download = layer
2968 79 : .needs_download()
2969 79 : .await
2970 79 : .context("failed to check if layer needs download")
2971 79 : .map_err(CompactionError::Other)?;
2972 79 : if needs_download.is_some() {
2973 0 : remote_layer_size += layer.layer_desc().file_size;
2974 79 : }
2975 79 : all_layer_size += layer.layer_desc().file_size;
2976 : }
2977 27 : let allocated_space = (available_space as f64 * 0.8) as u64; /* reserve 20% space for other tasks */
2978 27 : if all_layer_size /* space needed for newly-generated file */ + remote_layer_size /* space for downloading layers */ > allocated_space
2979 : {
2980 0 : return Err(CompactionError::Other(anyhow!(
2981 0 : "not enough space for compaction: available_space={}, allocated_space={}, all_layer_size={}, remote_layer_size={}, required_space={}",
2982 0 : available_space,
2983 0 : allocated_space,
2984 0 : all_layer_size,
2985 0 : remote_layer_size,
2986 0 : all_layer_size + remote_layer_size
2987 0 : )));
2988 27 : }
2989 27 : Ok(())
2990 27 : }
2991 :
2992 : /// Check to bail out of gc compaction early if it would use too much memory.
2993 27 : async fn check_memory_usage(
2994 27 : self: &Arc<Self>,
2995 27 : layer_selection: &[Layer],
2996 27 : ) -> Result<(), CompactionError> {
2997 27 : let mut estimated_memory_usage_mb = 0.0;
2998 27 : let mut num_image_layers = 0;
2999 27 : let mut num_delta_layers = 0;
3000 27 : let target_layer_size_bytes = 256 * 1024 * 1024;
3001 106 : for layer in layer_selection {
3002 79 : let layer_desc = layer.layer_desc();
3003 79 : if layer_desc.is_delta() {
3004 44 : // Delta layers at most have 1MB buffer; 3x to make it safe (there're deltas as large as 16KB).
3005 44 : // Scale it by target_layer_size_bytes so that tests can pass (some tests, e.g., `test_pageserver_gc_compaction_preempt
3006 44 : // use 3MB layer size and we need to account for that).
3007 44 : estimated_memory_usage_mb +=
3008 44 : 3.0 * (layer_desc.file_size / target_layer_size_bytes) as f64;
3009 44 : num_delta_layers += 1;
3010 44 : } else {
3011 35 : // Image layers at most have 1MB buffer but it might be compressed; assume 5x compression ratio.
3012 35 : estimated_memory_usage_mb +=
3013 35 : 5.0 * (layer_desc.file_size / target_layer_size_bytes) as f64;
3014 35 : num_image_layers += 1;
3015 35 : }
3016 : }
3017 27 : if estimated_memory_usage_mb > 1024.0 {
3018 0 : return Err(CompactionError::Other(anyhow!(
3019 0 : "estimated memory usage is too high: {}MB, giving up compaction; num_image_layers={}, num_delta_layers={}",
3020 0 : estimated_memory_usage_mb,
3021 0 : num_image_layers,
3022 0 : num_delta_layers
3023 0 : )));
3024 27 : }
3025 27 : Ok(())
3026 27 : }
3027 :
3028 : /// Get a watermark for gc-compaction, that is the lowest LSN that we can use as the `gc_horizon` for
3029 : /// the compaction algorithm. It is min(space_cutoff, time_cutoff, latest_gc_cutoff, standby_horizon).
3030 : /// Leases and retain_lsns are considered in the gc-compaction job itself so we don't need to account for them
3031 : /// here.
3032 28 : pub(crate) fn get_gc_compaction_watermark(self: &Arc<Self>) -> Lsn {
3033 28 : let gc_cutoff_lsn = {
3034 28 : let gc_info = self.gc_info.read().unwrap();
3035 28 : gc_info.min_cutoff()
3036 : };
3037 :
3038 : // TODO: standby horizon should use leases so we don't really need to consider it here.
3039 : // let watermark = watermark.min(self.standby_horizon.load());
3040 :
3041 : // TODO: ensure the child branches will not use anything below the watermark, or consider
3042 : // them when computing the watermark.
3043 28 : gc_cutoff_lsn.min(*self.get_applied_gc_cutoff_lsn())
3044 28 : }
3045 :
3046 : /// Split a gc-compaction job into multiple compaction jobs. The split is based on the key range and the estimated size of the compaction job.
3047 : /// The function returns a list of compaction jobs that can be executed separately. If the upper bound of the compact LSN
3048 : /// range is not specified, we will use the latest gc_cutoff as the upper bound, so that all jobs in the jobset acts
3049 : /// like a full compaction of the specified keyspace.
3050 0 : pub(crate) async fn gc_compaction_split_jobs(
3051 0 : self: &Arc<Self>,
3052 0 : job: GcCompactJob,
3053 0 : sub_compaction_max_job_size_mb: Option<u64>,
3054 0 : ) -> Result<Vec<GcCompactJob>, CompactionError> {
3055 0 : let compact_below_lsn = if job.compact_lsn_range.end != Lsn::MAX {
3056 0 : job.compact_lsn_range.end
3057 : } else {
3058 0 : self.get_gc_compaction_watermark()
3059 : };
3060 :
3061 0 : if compact_below_lsn == Lsn::INVALID {
3062 0 : tracing::warn!(
3063 0 : "no layers to compact with gc: gc_cutoff not generated yet, skipping gc bottom-most compaction"
3064 : );
3065 0 : return Ok(vec![]);
3066 0 : }
3067 :
3068 : // Split compaction job to about 4GB each
3069 : const GC_COMPACT_MAX_SIZE_MB: u64 = 4 * 1024;
3070 0 : let sub_compaction_max_job_size_mb =
3071 0 : sub_compaction_max_job_size_mb.unwrap_or(GC_COMPACT_MAX_SIZE_MB);
3072 :
3073 0 : let mut compact_jobs = Vec::<GcCompactJob>::new();
3074 : // For now, we simply use the key partitioning information; we should do a more fine-grained partitioning
3075 : // by estimating the amount of files read for a compaction job. We should also partition on LSN.
3076 0 : let ((dense_ks, sparse_ks), _) = self.partitioning.read().as_ref().clone();
3077 : // Truncate the key range to be within user specified compaction range.
3078 0 : fn truncate_to(
3079 0 : source_start: &Key,
3080 0 : source_end: &Key,
3081 0 : target_start: &Key,
3082 0 : target_end: &Key,
3083 0 : ) -> Option<(Key, Key)> {
3084 0 : let start = source_start.max(target_start);
3085 0 : let end = source_end.min(target_end);
3086 0 : if start < end {
3087 0 : Some((*start, *end))
3088 : } else {
3089 0 : None
3090 : }
3091 0 : }
3092 0 : let mut split_key_ranges = Vec::new();
3093 0 : let ranges = dense_ks
3094 0 : .parts
3095 0 : .iter()
3096 0 : .map(|partition| partition.ranges.iter())
3097 0 : .chain(sparse_ks.parts.iter().map(|x| x.0.ranges.iter()))
3098 0 : .flatten()
3099 0 : .cloned()
3100 0 : .collect_vec();
3101 0 : for range in ranges.iter() {
3102 0 : let Some((start, end)) = truncate_to(
3103 0 : &range.start,
3104 0 : &range.end,
3105 0 : &job.compact_key_range.start,
3106 0 : &job.compact_key_range.end,
3107 0 : ) else {
3108 0 : continue;
3109 : };
3110 0 : split_key_ranges.push((start, end));
3111 : }
3112 0 : split_key_ranges.sort();
3113 0 : let all_layers = {
3114 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
3115 0 : let layer_map = guard.layer_map()?;
3116 0 : layer_map.iter_historic_layers().collect_vec()
3117 : };
3118 0 : let mut current_start = None;
3119 0 : let ranges_num = split_key_ranges.len();
3120 0 : for (idx, (start, end)) in split_key_ranges.into_iter().enumerate() {
3121 0 : if current_start.is_none() {
3122 0 : current_start = Some(start);
3123 0 : }
3124 0 : let start = current_start.unwrap();
3125 0 : if start >= end {
3126 : // We have already processed this partition.
3127 0 : continue;
3128 0 : }
3129 0 : let overlapping_layers = {
3130 0 : let mut desc = Vec::new();
3131 0 : for layer in all_layers.iter() {
3132 0 : if overlaps_with(&layer.get_key_range(), &(start..end))
3133 0 : && layer.get_lsn_range().start <= compact_below_lsn
3134 0 : {
3135 0 : desc.push(layer.clone());
3136 0 : }
3137 : }
3138 0 : desc
3139 : };
3140 0 : let total_size = overlapping_layers.iter().map(|x| x.file_size).sum::<u64>();
3141 0 : if total_size > sub_compaction_max_job_size_mb * 1024 * 1024 || ranges_num == idx + 1 {
3142 : // Try to extend the compaction range so that we include at least one full layer file.
3143 0 : let extended_end = overlapping_layers
3144 0 : .iter()
3145 0 : .map(|layer| layer.key_range.end)
3146 0 : .min();
3147 : // It is possible that the search range does not contain any layer files when we reach the end of the loop.
3148 : // In this case, we simply use the specified key range end.
3149 0 : let end = if let Some(extended_end) = extended_end {
3150 0 : extended_end.max(end)
3151 : } else {
3152 0 : end
3153 : };
3154 0 : let end = if ranges_num == idx + 1 {
3155 : // extend the compaction range to the end of the key range if it's the last partition
3156 0 : end.max(job.compact_key_range.end)
3157 : } else {
3158 0 : end
3159 : };
3160 0 : if total_size == 0 && !compact_jobs.is_empty() {
3161 0 : info!(
3162 0 : "splitting compaction job: {}..{}, estimated_size={}, extending the previous job",
3163 : start, end, total_size
3164 : );
3165 0 : compact_jobs.last_mut().unwrap().compact_key_range.end = end;
3166 0 : current_start = Some(end);
3167 : } else {
3168 0 : info!(
3169 0 : "splitting compaction job: {}..{}, estimated_size={}",
3170 : start, end, total_size
3171 : );
3172 0 : compact_jobs.push(GcCompactJob {
3173 0 : dry_run: job.dry_run,
3174 0 : compact_key_range: start..end,
3175 0 : compact_lsn_range: job.compact_lsn_range.start..compact_below_lsn,
3176 0 : do_metadata_compaction: false,
3177 0 : });
3178 0 : current_start = Some(end);
3179 : }
3180 0 : }
3181 : }
3182 0 : Ok(compact_jobs)
3183 0 : }
3184 :
3185 : /// An experimental compaction building block that combines compaction with garbage collection.
3186 : ///
3187 : /// The current implementation picks all delta + image layers that are below or intersecting with
3188 : /// the GC horizon without considering retain_lsns. Then, it does a full compaction over all these delta
3189 : /// layers and image layers, which generates image layers on the gc horizon, drop deltas below gc horizon,
3190 : /// and create delta layers with all deltas >= gc horizon.
3191 : ///
3192 : /// If `options.compact_range` is provided, it will only compact the keys within the range, aka partial compaction.
3193 : /// Partial compaction will read and process all layers overlapping with the key range, even if it might
3194 : /// contain extra keys. After the gc-compaction phase completes, delta layers that are not fully contained
3195 : /// within the key range will be rewritten to ensure they do not overlap with the delta layers. Providing
3196 : /// Key::MIN..Key..MAX to the function indicates a full compaction, though technically, `Key::MAX` is not
3197 : /// part of the range.
3198 : ///
3199 : /// If `options.compact_lsn_range.end` is provided, the compaction will only compact layers below or intersect with
3200 : /// the LSN. Otherwise, it will use the gc cutoff by default.
3201 28 : pub(crate) async fn compact_with_gc(
3202 28 : self: &Arc<Self>,
3203 28 : cancel: &CancellationToken,
3204 28 : options: CompactOptions,
3205 28 : ctx: &RequestContext,
3206 28 : ) -> Result<CompactionOutcome, CompactionError> {
3207 28 : let sub_compaction = options.sub_compaction;
3208 28 : let job = GcCompactJob::from_compact_options(options.clone());
3209 28 : let yield_for_l0 = options.flags.contains(CompactFlags::YieldForL0);
3210 28 : if sub_compaction {
3211 0 : info!(
3212 0 : "running enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs"
3213 : );
3214 0 : let jobs = self
3215 0 : .gc_compaction_split_jobs(job, options.sub_compaction_max_job_size_mb)
3216 0 : .await?;
3217 0 : let jobs_len = jobs.len();
3218 0 : for (idx, job) in jobs.into_iter().enumerate() {
3219 0 : let sub_compaction_progress = format!("{}/{}", idx + 1, jobs_len);
3220 0 : self.compact_with_gc_inner(cancel, job, ctx, yield_for_l0)
3221 0 : .instrument(info_span!(
3222 : "sub_compaction",
3223 : sub_compaction_progress = sub_compaction_progress
3224 : ))
3225 0 : .await?;
3226 : }
3227 0 : if jobs_len == 0 {
3228 0 : info!("no jobs to run, skipping gc bottom-most compaction");
3229 0 : }
3230 0 : return Ok(CompactionOutcome::Done);
3231 28 : }
3232 28 : self.compact_with_gc_inner(cancel, job, ctx, yield_for_l0)
3233 28 : .await
3234 28 : }
3235 :
3236 28 : async fn compact_with_gc_inner(
3237 28 : self: &Arc<Self>,
3238 28 : cancel: &CancellationToken,
3239 28 : mut job: GcCompactJob,
3240 28 : ctx: &RequestContext,
3241 28 : yield_for_l0: bool,
3242 28 : ) -> Result<CompactionOutcome, CompactionError> {
3243 : // Block other compaction/GC tasks from running for now. GC-compaction could run along
3244 : // with legacy compaction tasks in the future. Always ensure the lock order is compaction -> gc.
3245 : // Note that we already acquired the compaction lock when the outer `compact` function gets called.
3246 :
3247 : // If the job is not configured to compact the metadata key range, shrink the key range
3248 : // to exclude the metadata key range. The check is done by checking if the end of the key range
3249 : // is larger than the start of the metadata key range. Note that metadata keys cover the entire
3250 : // second half of the keyspace, so it's enough to only check the end of the key range.
3251 28 : if !job.do_metadata_compaction
3252 0 : && job.compact_key_range.end > Key::metadata_key_range().start
3253 : {
3254 0 : tracing::info!(
3255 0 : "compaction for metadata key range is not supported yet, overriding compact_key_range from {} to {}",
3256 : job.compact_key_range.end,
3257 0 : Key::metadata_key_range().start
3258 : );
3259 : // Shrink the key range to exclude the metadata key range.
3260 0 : job.compact_key_range.end = Key::metadata_key_range().start;
3261 :
3262 : // Skip the job if the key range completely lies within the metadata key range.
3263 0 : if job.compact_key_range.start >= job.compact_key_range.end {
3264 0 : tracing::info!("compact_key_range is empty, skipping compaction");
3265 0 : return Ok(CompactionOutcome::Done);
3266 0 : }
3267 28 : }
3268 :
3269 28 : let timer = Instant::now();
3270 28 : let begin_timer = timer;
3271 :
3272 28 : let gc_lock = async {
3273 28 : tokio::select! {
3274 28 : guard = self.gc_lock.lock() => Ok(guard),
3275 28 : _ = cancel.cancelled() => Err(CompactionError::new_cancelled()),
3276 : }
3277 28 : };
3278 :
3279 28 : let time_acquire_lock = timer.elapsed();
3280 28 : let timer = Instant::now();
3281 :
3282 28 : let gc_lock = crate::timed(
3283 28 : gc_lock,
3284 28 : "acquires gc lock",
3285 28 : std::time::Duration::from_secs(5),
3286 28 : )
3287 28 : .await?;
3288 :
3289 28 : let dry_run = job.dry_run;
3290 28 : let compact_key_range = job.compact_key_range;
3291 28 : let compact_lsn_range = job.compact_lsn_range;
3292 :
3293 28 : let debug_mode = cfg!(debug_assertions) || cfg!(feature = "testing");
3294 :
3295 28 : info!(
3296 0 : "running enhanced gc bottom-most compaction, dry_run={dry_run}, compact_key_range={}..{}, compact_lsn_range={}..{}",
3297 : compact_key_range.start,
3298 : compact_key_range.end,
3299 : compact_lsn_range.start,
3300 : compact_lsn_range.end
3301 : );
3302 :
3303 28 : scopeguard::defer! {
3304 : info!("done enhanced gc bottom-most compaction");
3305 : };
3306 :
3307 28 : let mut stat = CompactionStatistics::default();
3308 :
3309 : // Step 0: pick all delta layers + image layers below/intersect with the GC horizon.
3310 : // The layer selection has the following properties:
3311 : // 1. If a layer is in the selection, all layers below it are in the selection.
3312 : // 2. Inferred from (1), for each key in the layer selection, the value can be reconstructed only with the layers in the layer selection.
3313 27 : let job_desc = {
3314 28 : let guard = self
3315 28 : .layers
3316 28 : .read(LayerManagerLockHolder::GarbageCollection)
3317 28 : .await;
3318 28 : let layers = guard.layer_map()?;
3319 28 : let gc_info = self.gc_info.read().unwrap();
3320 28 : let mut retain_lsns_below_horizon = Vec::new();
3321 28 : let gc_cutoff = {
3322 : // Currently, gc-compaction only kicks in after the legacy gc has updated the gc_cutoff.
3323 : // Therefore, it can only clean up data that cannot be cleaned up with legacy gc, instead of
3324 : // cleaning everything that theoritically it could. In the future, it should use `self.gc_info`
3325 : // to get the truth data.
3326 28 : let real_gc_cutoff = self.get_gc_compaction_watermark();
3327 : // The compaction algorithm will keep all keys above the gc_cutoff while keeping only necessary keys below the gc_cutoff for
3328 : // each of the retain_lsn. Therefore, if the user-provided `compact_lsn_range.end` is larger than the real gc cutoff, we will use
3329 : // the real cutoff.
3330 28 : let mut gc_cutoff = if compact_lsn_range.end == Lsn::MAX {
3331 25 : if real_gc_cutoff == Lsn::INVALID {
3332 : // If the gc_cutoff is not generated yet, we should not compact anything.
3333 0 : tracing::warn!(
3334 0 : "no layers to compact with gc: gc_cutoff not generated yet, skipping gc bottom-most compaction"
3335 : );
3336 0 : return Ok(CompactionOutcome::Skipped);
3337 25 : }
3338 25 : real_gc_cutoff
3339 : } else {
3340 3 : compact_lsn_range.end
3341 : };
3342 28 : if gc_cutoff > real_gc_cutoff {
3343 2 : warn!(
3344 0 : "provided compact_lsn_range.end={} is larger than the real_gc_cutoff={}, using the real gc cutoff",
3345 : gc_cutoff, real_gc_cutoff
3346 : );
3347 2 : gc_cutoff = real_gc_cutoff;
3348 26 : }
3349 28 : gc_cutoff
3350 : };
3351 35 : for (lsn, _timeline_id, _is_offloaded) in &gc_info.retain_lsns {
3352 35 : if lsn < &gc_cutoff {
3353 35 : retain_lsns_below_horizon.push(*lsn);
3354 35 : }
3355 : }
3356 28 : for lsn in gc_info.leases.keys() {
3357 0 : if lsn < &gc_cutoff {
3358 0 : retain_lsns_below_horizon.push(*lsn);
3359 0 : }
3360 : }
3361 28 : let mut selected_layers: Vec<Layer> = Vec::new();
3362 28 : drop(gc_info);
3363 : // Firstly, pick all the layers intersect or below the gc_cutoff, get the largest LSN in the selected layers.
3364 28 : let Some(max_layer_lsn) = layers
3365 28 : .iter_historic_layers()
3366 125 : .filter(|desc| desc.get_lsn_range().start <= gc_cutoff)
3367 107 : .map(|desc| desc.get_lsn_range().end)
3368 28 : .max()
3369 : else {
3370 0 : info!(
3371 0 : "no layers to compact with gc: no historic layers below gc_cutoff, gc_cutoff={}",
3372 : gc_cutoff
3373 : );
3374 0 : return Ok(CompactionOutcome::Done);
3375 : };
3376 : // Next, if the user specifies compact_lsn_range.start, we need to filter some layers out. All the layers (strictly) below
3377 : // the min_layer_lsn computed as below will be filtered out and the data will be accessed using the normal read path, as if
3378 : // it is a branch.
3379 28 : let Some(min_layer_lsn) = layers
3380 28 : .iter_historic_layers()
3381 125 : .filter(|desc| {
3382 125 : if compact_lsn_range.start == Lsn::INVALID {
3383 102 : true // select all layers below if start == Lsn(0)
3384 : } else {
3385 23 : desc.get_lsn_range().end > compact_lsn_range.start // strictly larger than compact_above_lsn
3386 : }
3387 125 : })
3388 116 : .map(|desc| desc.get_lsn_range().start)
3389 28 : .min()
3390 : else {
3391 0 : info!(
3392 0 : "no layers to compact with gc: no historic layers above compact_above_lsn, compact_above_lsn={}",
3393 : compact_lsn_range.end
3394 : );
3395 0 : return Ok(CompactionOutcome::Done);
3396 : };
3397 : // Then, pick all the layers that are below the max_layer_lsn. This is to ensure we can pick all single-key
3398 : // layers to compact.
3399 28 : let mut rewrite_layers = Vec::new();
3400 125 : for desc in layers.iter_historic_layers() {
3401 125 : if desc.get_lsn_range().end <= max_layer_lsn
3402 107 : && desc.get_lsn_range().start >= min_layer_lsn
3403 98 : && overlaps_with(&desc.get_key_range(), &compact_key_range)
3404 : {
3405 : // If the layer overlaps with the compaction key range, we need to read it to obtain all keys within the range,
3406 : // even if it might contain extra keys
3407 79 : selected_layers.push(guard.get_from_desc(&desc));
3408 : // If the layer is not fully contained within the key range, we need to rewrite it if it's a delta layer (it's fine
3409 : // to overlap image layers)
3410 79 : if desc.is_delta() && !fully_contains(&compact_key_range, &desc.get_key_range())
3411 1 : {
3412 1 : rewrite_layers.push(desc);
3413 78 : }
3414 46 : }
3415 : }
3416 28 : if selected_layers.is_empty() {
3417 1 : info!(
3418 0 : "no layers to compact with gc: no layers within the key range, gc_cutoff={}, key_range={}..{}",
3419 : gc_cutoff, compact_key_range.start, compact_key_range.end
3420 : );
3421 1 : return Ok(CompactionOutcome::Done);
3422 27 : }
3423 27 : retain_lsns_below_horizon.sort();
3424 27 : GcCompactionJobDescription {
3425 27 : selected_layers,
3426 27 : gc_cutoff,
3427 27 : retain_lsns_below_horizon,
3428 27 : min_layer_lsn,
3429 27 : max_layer_lsn,
3430 27 : compaction_key_range: compact_key_range,
3431 27 : rewrite_layers,
3432 27 : }
3433 : };
3434 27 : let (has_data_below, lowest_retain_lsn) = if compact_lsn_range.start != Lsn::INVALID {
3435 : // If we only compact above some LSN, we should get the history from the current branch below the specified LSN.
3436 : // We use job_desc.min_layer_lsn as if it's the lowest branch point.
3437 4 : (true, job_desc.min_layer_lsn)
3438 23 : } else if self.ancestor_timeline.is_some() {
3439 : // In theory, we can also use min_layer_lsn here, but using ancestor LSN makes sure the delta layers cover the
3440 : // LSN ranges all the way to the ancestor timeline.
3441 1 : (true, self.ancestor_lsn)
3442 : } else {
3443 22 : let res = job_desc
3444 22 : .retain_lsns_below_horizon
3445 22 : .first()
3446 22 : .copied()
3447 22 : .unwrap_or(job_desc.gc_cutoff);
3448 22 : if debug_mode {
3449 22 : assert_eq!(
3450 : res,
3451 22 : job_desc
3452 22 : .retain_lsns_below_horizon
3453 22 : .iter()
3454 22 : .min()
3455 22 : .copied()
3456 22 : .unwrap_or(job_desc.gc_cutoff)
3457 : );
3458 0 : }
3459 22 : (false, res)
3460 : };
3461 :
3462 27 : let verification = self.get_gc_compaction_settings().gc_compaction_verification;
3463 :
3464 27 : info!(
3465 0 : "picked {} layers for compaction ({} layers need rewriting) with max_layer_lsn={} min_layer_lsn={} gc_cutoff={} lowest_retain_lsn={}, key_range={}..{}, has_data_below={}",
3466 0 : job_desc.selected_layers.len(),
3467 0 : job_desc.rewrite_layers.len(),
3468 : job_desc.max_layer_lsn,
3469 : job_desc.min_layer_lsn,
3470 : job_desc.gc_cutoff,
3471 : lowest_retain_lsn,
3472 : job_desc.compaction_key_range.start,
3473 : job_desc.compaction_key_range.end,
3474 : has_data_below,
3475 : );
3476 :
3477 27 : let time_analyze = timer.elapsed();
3478 27 : let timer = Instant::now();
3479 :
3480 106 : for layer in &job_desc.selected_layers {
3481 79 : debug!("read layer: {}", layer.layer_desc().key());
3482 : }
3483 28 : for layer in &job_desc.rewrite_layers {
3484 1 : debug!("rewrite layer: {}", layer.key());
3485 : }
3486 :
3487 27 : self.check_compaction_space(&job_desc.selected_layers)
3488 27 : .await?;
3489 :
3490 27 : self.check_memory_usage(&job_desc.selected_layers).await?;
3491 27 : if job_desc.selected_layers.len() > 100
3492 0 : && job_desc.rewrite_layers.len() as f64 >= job_desc.selected_layers.len() as f64 * 0.7
3493 : {
3494 0 : return Err(CompactionError::Other(anyhow!(
3495 0 : "too many layers to rewrite: {} / {}, giving up compaction",
3496 0 : job_desc.rewrite_layers.len(),
3497 0 : job_desc.selected_layers.len()
3498 0 : )));
3499 27 : }
3500 :
3501 : // Generate statistics for the compaction
3502 106 : for layer in &job_desc.selected_layers {
3503 79 : let desc = layer.layer_desc();
3504 79 : if desc.is_delta() {
3505 44 : stat.visit_delta_layer(desc.file_size());
3506 44 : } else {
3507 35 : stat.visit_image_layer(desc.file_size());
3508 35 : }
3509 : }
3510 :
3511 : // Step 1: construct a k-merge iterator over all layers.
3512 : // Also, verify if the layer map can be split by drawing a horizontal line at every LSN start/end split point.
3513 27 : let layer_names = job_desc
3514 27 : .selected_layers
3515 27 : .iter()
3516 79 : .map(|layer| layer.layer_desc().layer_name())
3517 27 : .collect_vec();
3518 27 : if let Some(err) = check_valid_layermap(&layer_names) {
3519 0 : return Err(CompactionError::Other(anyhow!(
3520 0 : "gc-compaction layer map check failed because {}, cannot proceed with compaction due to potential data loss",
3521 0 : err
3522 0 : )));
3523 27 : }
3524 : // The maximum LSN we are processing in this compaction loop
3525 27 : let end_lsn = job_desc
3526 27 : .selected_layers
3527 27 : .iter()
3528 79 : .map(|l| l.layer_desc().lsn_range.end)
3529 27 : .max()
3530 27 : .unwrap();
3531 27 : let mut delta_layers = Vec::new();
3532 27 : let mut image_layers = Vec::new();
3533 27 : let mut downloaded_layers = Vec::new();
3534 27 : let mut total_downloaded_size = 0;
3535 27 : let mut total_layer_size = 0;
3536 106 : for layer in &job_desc.selected_layers {
3537 79 : if layer
3538 79 : .needs_download()
3539 79 : .await
3540 79 : .context("failed to check if layer needs download")
3541 79 : .map_err(CompactionError::Other)?
3542 79 : .is_some()
3543 0 : {
3544 0 : total_downloaded_size += layer.layer_desc().file_size;
3545 79 : }
3546 79 : total_layer_size += layer.layer_desc().file_size;
3547 79 : if cancel.is_cancelled() {
3548 0 : return Err(CompactionError::new_cancelled());
3549 79 : }
3550 79 : let should_yield = yield_for_l0
3551 0 : && self
3552 0 : .l0_compaction_trigger
3553 0 : .notified()
3554 0 : .now_or_never()
3555 0 : .is_some();
3556 79 : if should_yield {
3557 0 : tracing::info!("preempt gc-compaction when downloading layers: too many L0 layers");
3558 0 : return Ok(CompactionOutcome::YieldForL0);
3559 79 : }
3560 79 : let resident_layer = layer
3561 79 : .download_and_keep_resident(ctx)
3562 79 : .await
3563 79 : .context("failed to download and keep resident layer")
3564 79 : .map_err(CompactionError::Other)?;
3565 79 : downloaded_layers.push(resident_layer);
3566 : }
3567 27 : info!(
3568 0 : "finish downloading layers, downloaded={}, total={}, ratio={:.2}",
3569 : total_downloaded_size,
3570 : total_layer_size,
3571 0 : total_downloaded_size as f64 / total_layer_size as f64
3572 : );
3573 106 : for resident_layer in &downloaded_layers {
3574 79 : if resident_layer.layer_desc().is_delta() {
3575 44 : let layer = resident_layer
3576 44 : .get_as_delta(ctx)
3577 44 : .await
3578 44 : .context("failed to get delta layer")
3579 44 : .map_err(CompactionError::Other)?;
3580 44 : delta_layers.push(layer);
3581 : } else {
3582 35 : let layer = resident_layer
3583 35 : .get_as_image(ctx)
3584 35 : .await
3585 35 : .context("failed to get image layer")
3586 35 : .map_err(CompactionError::Other)?;
3587 35 : image_layers.push(layer);
3588 : }
3589 : }
3590 27 : let (dense_ks, sparse_ks) = self
3591 27 : .collect_gc_compaction_keyspace()
3592 27 : .await
3593 27 : .context("failed to collect gc compaction keyspace")
3594 27 : .map_err(CompactionError::Other)?;
3595 27 : let mut merge_iter = FilterIterator::create(
3596 27 : MergeIterator::create_with_options(
3597 27 : &delta_layers,
3598 27 : &image_layers,
3599 27 : ctx,
3600 27 : 128 * 8192, /* 1MB buffer for each of the inner iterators */
3601 : 128,
3602 : ),
3603 27 : dense_ks,
3604 27 : sparse_ks,
3605 : )
3606 27 : .context("failed to create filter iterator")
3607 27 : .map_err(CompactionError::Other)?;
3608 :
3609 27 : let time_download_layer = timer.elapsed();
3610 27 : let mut timer = Instant::now();
3611 :
3612 : // Step 2: Produce images+deltas.
3613 27 : let mut accumulated_values = Vec::new();
3614 27 : let mut accumulated_values_estimated_size = 0;
3615 27 : let mut last_key: Option<Key> = None;
3616 :
3617 : // Only create image layers when there is no ancestor branches. TODO: create covering image layer
3618 : // when some condition meet.
3619 27 : let mut image_layer_writer = if !has_data_below {
3620 22 : Some(SplitImageLayerWriter::new(
3621 22 : self.conf,
3622 22 : self.timeline_id,
3623 22 : self.tenant_shard_id,
3624 22 : job_desc.compaction_key_range.start,
3625 22 : lowest_retain_lsn,
3626 22 : self.get_compaction_target_size(),
3627 22 : &self.gate,
3628 22 : self.cancel.clone(),
3629 22 : ))
3630 : } else {
3631 5 : None
3632 : };
3633 :
3634 27 : let mut delta_layer_writer = SplitDeltaLayerWriter::new(
3635 27 : self.conf,
3636 27 : self.timeline_id,
3637 27 : self.tenant_shard_id,
3638 27 : lowest_retain_lsn..end_lsn,
3639 27 : self.get_compaction_target_size(),
3640 27 : &self.gate,
3641 27 : self.cancel.clone(),
3642 : );
3643 :
3644 : #[derive(Default)]
3645 : struct RewritingLayers {
3646 : before: Option<DeltaLayerWriter>,
3647 : after: Option<DeltaLayerWriter>,
3648 : }
3649 27 : let mut delta_layer_rewriters = HashMap::<Arc<PersistentLayerKey>, RewritingLayers>::new();
3650 :
3651 : /// When compacting not at a bottom range (=`[0,X)`) of the root branch, we "have data below" (`has_data_below=true`).
3652 : /// The two cases are compaction in ancestor branches and when `compact_lsn_range.start` is set.
3653 : /// In those cases, we need to pull up data from below the LSN range we're compaction.
3654 : ///
3655 : /// This function unifies the cases so that later code doesn't have to think about it.
3656 : ///
3657 : /// Currently, we always get the ancestor image for each key in the child branch no matter whether the image
3658 : /// is needed for reconstruction. This should be fixed in the future.
3659 : ///
3660 : /// Furthermore, we should do vectored get instead of a single get, or better, use k-merge for ancestor
3661 : /// images.
3662 320 : async fn get_ancestor_image(
3663 320 : this_tline: &Arc<Timeline>,
3664 320 : key: Key,
3665 320 : ctx: &RequestContext,
3666 320 : has_data_below: bool,
3667 320 : history_lsn_point: Lsn,
3668 320 : ) -> anyhow::Result<Option<(Key, Lsn, Bytes)>> {
3669 320 : if !has_data_below {
3670 301 : return Ok(None);
3671 19 : };
3672 : // This function is implemented as a get of the current timeline at ancestor LSN, therefore reusing
3673 : // as much existing code as possible.
3674 19 : let img = this_tline.get(key, history_lsn_point, ctx).await?;
3675 19 : Ok(Some((key, history_lsn_point, img)))
3676 320 : }
3677 :
3678 : // Actually, we can decide not to write to the image layer at all at this point because
3679 : // the key and LSN range are determined. However, to keep things simple here, we still
3680 : // create this writer, and discard the writer in the end.
3681 27 : let mut time_to_first_kv_pair = None;
3682 :
3683 496 : while let Some(((key, lsn, val), desc)) = merge_iter
3684 496 : .next_with_trace()
3685 496 : .await
3686 496 : .context("failed to get next key-value pair")
3687 496 : .map_err(CompactionError::Other)?
3688 : {
3689 470 : if time_to_first_kv_pair.is_none() {
3690 27 : time_to_first_kv_pair = Some(timer.elapsed());
3691 27 : timer = Instant::now();
3692 443 : }
3693 :
3694 470 : if cancel.is_cancelled() {
3695 0 : return Err(CompactionError::new_cancelled());
3696 470 : }
3697 :
3698 470 : let should_yield = yield_for_l0
3699 0 : && self
3700 0 : .l0_compaction_trigger
3701 0 : .notified()
3702 0 : .now_or_never()
3703 0 : .is_some();
3704 470 : if should_yield {
3705 0 : tracing::info!("preempt gc-compaction in the main loop: too many L0 layers");
3706 0 : return Ok(CompactionOutcome::YieldForL0);
3707 470 : }
3708 470 : if self.shard_identity.is_key_disposable(&key) {
3709 : // If this shard does not need to store this key, simply skip it.
3710 : //
3711 : // This is not handled in the filter iterator because shard is determined by hash.
3712 : // Therefore, it does not give us any performance benefit to do things like skip
3713 : // a whole layer file as handling key spaces (ranges).
3714 0 : if cfg!(debug_assertions) {
3715 0 : let shard = self.shard_identity.shard_index();
3716 0 : let owner = self.shard_identity.get_shard_number(&key);
3717 0 : panic!("key {key} does not belong on shard {shard}, owned by {owner}");
3718 0 : }
3719 0 : continue;
3720 470 : }
3721 470 : if !job_desc.compaction_key_range.contains(&key) {
3722 32 : if !desc.is_delta {
3723 30 : continue;
3724 2 : }
3725 2 : let rewriter = delta_layer_rewriters.entry(desc.clone()).or_default();
3726 2 : let rewriter = if key < job_desc.compaction_key_range.start {
3727 0 : if rewriter.before.is_none() {
3728 0 : rewriter.before = Some(
3729 0 : DeltaLayerWriter::new(
3730 0 : self.conf,
3731 0 : self.timeline_id,
3732 0 : self.tenant_shard_id,
3733 0 : desc.key_range.start,
3734 0 : desc.lsn_range.clone(),
3735 0 : &self.gate,
3736 0 : self.cancel.clone(),
3737 0 : ctx,
3738 0 : )
3739 0 : .await
3740 0 : .context("failed to create delta layer writer")
3741 0 : .map_err(CompactionError::Other)?,
3742 : );
3743 0 : }
3744 0 : rewriter.before.as_mut().unwrap()
3745 2 : } else if key >= job_desc.compaction_key_range.end {
3746 2 : if rewriter.after.is_none() {
3747 1 : rewriter.after = Some(
3748 1 : DeltaLayerWriter::new(
3749 1 : self.conf,
3750 1 : self.timeline_id,
3751 1 : self.tenant_shard_id,
3752 1 : job_desc.compaction_key_range.end,
3753 1 : desc.lsn_range.clone(),
3754 1 : &self.gate,
3755 1 : self.cancel.clone(),
3756 1 : ctx,
3757 1 : )
3758 1 : .await
3759 1 : .context("failed to create delta layer writer")
3760 1 : .map_err(CompactionError::Other)?,
3761 : );
3762 1 : }
3763 2 : rewriter.after.as_mut().unwrap()
3764 : } else {
3765 0 : unreachable!()
3766 : };
3767 2 : rewriter
3768 2 : .put_value(key, lsn, val, ctx)
3769 2 : .await
3770 2 : .context("failed to put value")
3771 2 : .map_err(CompactionError::Other)?;
3772 2 : continue;
3773 438 : }
3774 438 : match val {
3775 315 : Value::Image(_) => stat.visit_image_key(&val),
3776 123 : Value::WalRecord(_) => stat.visit_wal_key(&val),
3777 : }
3778 438 : if last_key.is_none() || last_key.as_ref() == Some(&key) {
3779 144 : if last_key.is_none() {
3780 27 : last_key = Some(key);
3781 117 : }
3782 144 : accumulated_values_estimated_size += val.estimated_size();
3783 144 : accumulated_values.push((key, lsn, val));
3784 :
3785 : // Accumulated values should never exceed 512MB.
3786 144 : if accumulated_values_estimated_size >= 1024 * 1024 * 512 {
3787 0 : return Err(CompactionError::Other(anyhow!(
3788 0 : "too many values for a single key: {} for key {}, {} items",
3789 0 : accumulated_values_estimated_size,
3790 0 : key,
3791 0 : accumulated_values.len()
3792 0 : )));
3793 144 : }
3794 : } else {
3795 294 : let last_key: &mut Key = last_key.as_mut().unwrap();
3796 294 : stat.on_unique_key_visited(); // TODO: adjust statistics for partial compaction
3797 294 : let retention = self
3798 294 : .generate_key_retention(
3799 294 : *last_key,
3800 294 : &accumulated_values,
3801 294 : job_desc.gc_cutoff,
3802 294 : &job_desc.retain_lsns_below_horizon,
3803 : COMPACTION_DELTA_THRESHOLD,
3804 294 : get_ancestor_image(self, *last_key, ctx, has_data_below, lowest_retain_lsn)
3805 294 : .await
3806 294 : .context("failed to get ancestor image")
3807 294 : .map_err(CompactionError::Other)?,
3808 294 : verification,
3809 : )
3810 294 : .await
3811 294 : .context("failed to generate key retention")
3812 294 : .map_err(CompactionError::Other)?;
3813 293 : retention
3814 293 : .pipe_to(
3815 293 : *last_key,
3816 293 : &mut delta_layer_writer,
3817 293 : image_layer_writer.as_mut(),
3818 293 : &mut stat,
3819 293 : ctx,
3820 293 : )
3821 293 : .await
3822 293 : .context("failed to pipe to delta layer writer")
3823 293 : .map_err(CompactionError::Other)?;
3824 293 : accumulated_values.clear();
3825 293 : *last_key = key;
3826 293 : accumulated_values_estimated_size = val.estimated_size();
3827 293 : accumulated_values.push((key, lsn, val));
3828 : }
3829 : }
3830 :
3831 : // TODO: move the below part to the loop body
3832 26 : let Some(last_key) = last_key else {
3833 0 : return Err(CompactionError::Other(anyhow!(
3834 0 : "no keys produced during compaction"
3835 0 : )));
3836 : };
3837 26 : stat.on_unique_key_visited();
3838 :
3839 26 : let retention = self
3840 26 : .generate_key_retention(
3841 26 : last_key,
3842 26 : &accumulated_values,
3843 26 : job_desc.gc_cutoff,
3844 26 : &job_desc.retain_lsns_below_horizon,
3845 : COMPACTION_DELTA_THRESHOLD,
3846 26 : get_ancestor_image(self, last_key, ctx, has_data_below, lowest_retain_lsn)
3847 26 : .await
3848 26 : .context("failed to get ancestor image")
3849 26 : .map_err(CompactionError::Other)?,
3850 26 : verification,
3851 : )
3852 26 : .await
3853 26 : .context("failed to generate key retention")
3854 26 : .map_err(CompactionError::Other)?;
3855 26 : retention
3856 26 : .pipe_to(
3857 26 : last_key,
3858 26 : &mut delta_layer_writer,
3859 26 : image_layer_writer.as_mut(),
3860 26 : &mut stat,
3861 26 : ctx,
3862 26 : )
3863 26 : .await
3864 26 : .context("failed to pipe to delta layer writer")
3865 26 : .map_err(CompactionError::Other)?;
3866 : // end: move the above part to the loop body
3867 :
3868 26 : let time_main_loop = timer.elapsed();
3869 26 : let timer = Instant::now();
3870 :
3871 26 : let mut rewrote_delta_layers = Vec::new();
3872 27 : for (key, writers) in delta_layer_rewriters {
3873 1 : if let Some(delta_writer_before) = writers.before {
3874 0 : let (desc, path) = delta_writer_before
3875 0 : .finish(job_desc.compaction_key_range.start, ctx)
3876 0 : .await
3877 0 : .context("failed to finish delta layer writer")
3878 0 : .map_err(CompactionError::Other)?;
3879 0 : let layer = Layer::finish_creating(self.conf, self, desc, &path)
3880 0 : .context("failed to finish creating delta layer")
3881 0 : .map_err(CompactionError::Other)?;
3882 0 : rewrote_delta_layers.push(layer);
3883 1 : }
3884 1 : if let Some(delta_writer_after) = writers.after {
3885 1 : let (desc, path) = delta_writer_after
3886 1 : .finish(key.key_range.end, ctx)
3887 1 : .await
3888 1 : .context("failed to finish delta layer writer")
3889 1 : .map_err(CompactionError::Other)?;
3890 1 : let layer = Layer::finish_creating(self.conf, self, desc, &path)
3891 1 : .context("failed to finish creating delta layer")
3892 1 : .map_err(CompactionError::Other)?;
3893 1 : rewrote_delta_layers.push(layer);
3894 0 : }
3895 : }
3896 :
3897 37 : let discard = |key: &PersistentLayerKey| {
3898 37 : let key = key.clone();
3899 37 : async move { KeyHistoryRetention::discard_key(&key, self, dry_run).await }
3900 37 : };
3901 :
3902 26 : let produced_image_layers = if let Some(writer) = image_layer_writer {
3903 21 : if !dry_run {
3904 19 : let end_key = job_desc.compaction_key_range.end;
3905 19 : writer
3906 19 : .finish_with_discard_fn(self, ctx, end_key, discard)
3907 19 : .await
3908 19 : .context("failed to finish image layer writer")
3909 19 : .map_err(CompactionError::Other)?
3910 : } else {
3911 2 : drop(writer);
3912 2 : Vec::new()
3913 : }
3914 : } else {
3915 5 : Vec::new()
3916 : };
3917 :
3918 26 : let produced_delta_layers = if !dry_run {
3919 24 : delta_layer_writer
3920 24 : .finish_with_discard_fn(self, ctx, discard)
3921 24 : .await
3922 24 : .context("failed to finish delta layer writer")
3923 24 : .map_err(CompactionError::Other)?
3924 : } else {
3925 2 : drop(delta_layer_writer);
3926 2 : Vec::new()
3927 : };
3928 :
3929 : // TODO: make image/delta/rewrote_delta layers generation atomic. At this point, we already generated resident layers, and if
3930 : // compaction is cancelled at this point, we might have some layers that are not cleaned up.
3931 26 : let mut compact_to = Vec::new();
3932 26 : let mut keep_layers = HashSet::new();
3933 26 : let produced_delta_layers_len = produced_delta_layers.len();
3934 26 : let produced_image_layers_len = produced_image_layers.len();
3935 :
3936 26 : let layer_selection_by_key = job_desc
3937 26 : .selected_layers
3938 26 : .iter()
3939 76 : .map(|l| (l.layer_desc().key(), l.layer_desc().clone()))
3940 26 : .collect::<HashMap<_, _>>();
3941 :
3942 44 : for action in produced_delta_layers {
3943 18 : match action {
3944 11 : BatchWriterResult::Produced(layer) => {
3945 11 : if cfg!(debug_assertions) {
3946 11 : info!("produced delta layer: {}", layer.layer_desc().key());
3947 0 : }
3948 11 : stat.produce_delta_layer(layer.layer_desc().file_size());
3949 11 : compact_to.push(layer);
3950 : }
3951 7 : BatchWriterResult::Discarded(l) => {
3952 7 : if cfg!(debug_assertions) {
3953 7 : info!("discarded delta layer: {}", l);
3954 0 : }
3955 7 : if let Some(layer_desc) = layer_selection_by_key.get(&l) {
3956 7 : stat.discard_delta_layer(layer_desc.file_size());
3957 7 : } else {
3958 0 : tracing::warn!(
3959 0 : "discarded delta layer not in layer_selection: {}, produced a layer outside of the compaction key range?",
3960 : l
3961 : );
3962 0 : stat.discard_delta_layer(0);
3963 : }
3964 7 : keep_layers.insert(l);
3965 : }
3966 : }
3967 : }
3968 27 : for layer in &rewrote_delta_layers {
3969 1 : debug!(
3970 0 : "produced rewritten delta layer: {}",
3971 0 : layer.layer_desc().key()
3972 : );
3973 : // For now, we include rewritten delta layer size in the "produce_delta_layer". We could
3974 : // make it a separate statistics in the future.
3975 1 : stat.produce_delta_layer(layer.layer_desc().file_size());
3976 : }
3977 26 : compact_to.extend(rewrote_delta_layers);
3978 45 : for action in produced_image_layers {
3979 19 : match action {
3980 15 : BatchWriterResult::Produced(layer) => {
3981 15 : debug!("produced image layer: {}", layer.layer_desc().key());
3982 15 : stat.produce_image_layer(layer.layer_desc().file_size());
3983 15 : compact_to.push(layer);
3984 : }
3985 4 : BatchWriterResult::Discarded(l) => {
3986 4 : debug!("discarded image layer: {}", l);
3987 4 : if let Some(layer_desc) = layer_selection_by_key.get(&l) {
3988 4 : stat.discard_image_layer(layer_desc.file_size());
3989 4 : } else {
3990 0 : tracing::warn!(
3991 0 : "discarded image layer not in layer_selection: {}, produced a layer outside of the compaction key range?",
3992 : l
3993 : );
3994 0 : stat.discard_image_layer(0);
3995 : }
3996 4 : keep_layers.insert(l);
3997 : }
3998 : }
3999 : }
4000 :
4001 26 : let mut layer_selection = job_desc.selected_layers;
4002 :
4003 : // Partial compaction might select more data than it processes, e.g., if
4004 : // the compaction_key_range only partially overlaps:
4005 : //
4006 : // [---compaction_key_range---]
4007 : // [---A----][----B----][----C----][----D----]
4008 : //
4009 : // For delta layers, we will rewrite the layers so that it is cut exactly at
4010 : // the compaction key range, so we can always discard them. However, for image
4011 : // layers, as we do not rewrite them for now, we need to handle them differently.
4012 : // Assume image layers A, B, C, D are all in the `layer_selection`.
4013 : //
4014 : // The created image layers contain whatever is needed from B, C, and from
4015 : // `----]` of A, and from `[---` of D.
4016 : //
4017 : // In contrast, `[---A` and `D----]` have not been processed, so, we must
4018 : // keep that data.
4019 : //
4020 : // The solution for now is to keep A and D completely if they are image layers.
4021 : // (layer_selection is what we'll remove from the layer map, so, retain what
4022 : // is _not_ fully covered by compaction_key_range).
4023 102 : for layer in &layer_selection {
4024 76 : if !layer.layer_desc().is_delta() {
4025 33 : if !overlaps_with(
4026 33 : &layer.layer_desc().key_range,
4027 33 : &job_desc.compaction_key_range,
4028 33 : ) {
4029 0 : return Err(CompactionError::Other(anyhow!(
4030 0 : "violated constraint: image layer outside of compaction key range"
4031 0 : )));
4032 33 : }
4033 33 : if !fully_contains(
4034 33 : &job_desc.compaction_key_range,
4035 33 : &layer.layer_desc().key_range,
4036 33 : ) {
4037 4 : keep_layers.insert(layer.layer_desc().key());
4038 29 : }
4039 43 : }
4040 : }
4041 :
4042 76 : layer_selection.retain(|x| !keep_layers.contains(&x.layer_desc().key()));
4043 :
4044 26 : let time_final_phase = timer.elapsed();
4045 :
4046 26 : stat.time_final_phase_secs = time_final_phase.as_secs_f64();
4047 26 : stat.time_to_first_kv_pair_secs = time_to_first_kv_pair
4048 26 : .unwrap_or(Duration::ZERO)
4049 26 : .as_secs_f64();
4050 26 : stat.time_main_loop_secs = time_main_loop.as_secs_f64();
4051 26 : stat.time_acquire_lock_secs = time_acquire_lock.as_secs_f64();
4052 26 : stat.time_download_layer_secs = time_download_layer.as_secs_f64();
4053 26 : stat.time_analyze_secs = time_analyze.as_secs_f64();
4054 26 : stat.time_total_secs = begin_timer.elapsed().as_secs_f64();
4055 26 : stat.finalize();
4056 :
4057 26 : info!(
4058 0 : "gc-compaction statistics: {}",
4059 0 : serde_json::to_string(&stat)
4060 0 : .context("failed to serialize gc-compaction statistics")
4061 0 : .map_err(CompactionError::Other)?
4062 : );
4063 :
4064 26 : if dry_run {
4065 2 : return Ok(CompactionOutcome::Done);
4066 24 : }
4067 :
4068 24 : info!(
4069 0 : "produced {} delta layers and {} image layers, {} layers are kept",
4070 : produced_delta_layers_len,
4071 : produced_image_layers_len,
4072 0 : keep_layers.len()
4073 : );
4074 :
4075 : // Step 3: Place back to the layer map.
4076 :
4077 : // First, do a sanity check to ensure the newly-created layer map does not contain overlaps.
4078 24 : let all_layers = {
4079 24 : let guard = self
4080 24 : .layers
4081 24 : .read(LayerManagerLockHolder::GarbageCollection)
4082 24 : .await;
4083 24 : let layer_map = guard.layer_map()?;
4084 24 : layer_map.iter_historic_layers().collect_vec()
4085 : };
4086 :
4087 24 : let mut final_layers = all_layers
4088 24 : .iter()
4089 107 : .map(|layer| layer.layer_name())
4090 24 : .collect::<HashSet<_>>();
4091 76 : for layer in &layer_selection {
4092 52 : final_layers.remove(&layer.layer_desc().layer_name());
4093 52 : }
4094 51 : for layer in &compact_to {
4095 27 : final_layers.insert(layer.layer_desc().layer_name());
4096 27 : }
4097 24 : let final_layers = final_layers.into_iter().collect_vec();
4098 :
4099 : // TODO: move this check before we call `finish` on image layer writers. However, this will require us to get the layer name before we finish
4100 : // the writer, so potentially, we will need a function like `ImageLayerBatchWriter::get_all_pending_layer_keys` to get all the keys that are
4101 : // in the writer before finalizing the persistent layers. Now we would leave some dangling layers on the disk if the check fails.
4102 24 : if let Some(err) = check_valid_layermap(&final_layers) {
4103 0 : return Err(CompactionError::Other(anyhow!(
4104 0 : "gc-compaction layer map check failed after compaction because {}, compaction result not applied to the layer map due to potential data loss",
4105 0 : err
4106 0 : )));
4107 24 : }
4108 :
4109 : // Between the sanity check and this compaction update, there could be new layers being flushed, but it should be fine because we only
4110 : // operate on L1 layers.
4111 : {
4112 : // Gc-compaction will rewrite the history of a key. This could happen in two ways:
4113 : //
4114 : // 1. We create an image layer to replace all the deltas below the compact LSN. In this case, assume
4115 : // we have 2 delta layers A and B, both below the compact LSN. We create an image layer I to replace
4116 : // A and B at the compact LSN. If the read path finishes reading A, yields, and now we update the layer
4117 : // map, the read path then cannot find any keys below A, reporting a missing key error, while the key
4118 : // now gets stored in I at the compact LSN.
4119 : //
4120 : // --------------- ---------------
4121 : // delta1@LSN20 image1@LSN20
4122 : // --------------- (read path collects delta@LSN20, => --------------- (read path cannot find anything
4123 : // delta1@LSN10 yields) below LSN 20)
4124 : // ---------------
4125 : //
4126 : // 2. We create a delta layer to replace all the deltas below the compact LSN, and in the delta layers,
4127 : // we combines the history of a key into a single image. For example, we have deltas at LSN 1, 2, 3, 4,
4128 : // Assume one delta layer contains LSN 1, 2, 3 and the other contains LSN 4.
4129 : //
4130 : // We let gc-compaction combine delta 2, 3, 4 into an image at LSN 4, which produces a delta layer that
4131 : // contains the delta at LSN 1, the image at LSN 4. If the read path finishes reading the original delta
4132 : // layer containing 4, yields, and we update the layer map to put the delta layer.
4133 : //
4134 : // --------------- ---------------
4135 : // delta1@LSN4 image1@LSN4
4136 : // --------------- (read path collects delta@LSN4, => --------------- (read path collects LSN4 and LSN1,
4137 : // delta1@LSN1-3 yields) delta1@LSN1 which is an invalid history)
4138 : // --------------- ---------------
4139 : //
4140 : // Therefore, the gc-compaction layer update operation should wait for all ongoing reads, block all pending reads,
4141 : // and only allow reads to continue after the update is finished.
4142 :
4143 24 : let update_guard = self.gc_compaction_layer_update_lock.write().await;
4144 : // Acquiring the update guard ensures current read operations end and new read operations are blocked.
4145 : // TODO: can we use `latest_gc_cutoff` Rcu to achieve the same effect?
4146 24 : let mut guard = self
4147 24 : .layers
4148 24 : .write(LayerManagerLockHolder::GarbageCollection)
4149 24 : .await;
4150 24 : guard
4151 24 : .open_mut()?
4152 24 : .finish_gc_compaction(&layer_selection, &compact_to, &self.metrics);
4153 24 : drop(update_guard); // Allow new reads to start ONLY after we finished updating the layer map.
4154 : };
4155 :
4156 : // Schedule an index-only upload to update the `latest_gc_cutoff` in the index_part.json.
4157 : // Otherwise, after restart, the index_part only contains the old `latest_gc_cutoff` and
4158 : // find_gc_cutoffs will try accessing things below the cutoff. TODO: ideally, this should
4159 : // be batched into `schedule_compaction_update`.
4160 24 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
4161 24 : self.schedule_uploads(disk_consistent_lsn, None)
4162 24 : .context("failed to schedule uploads")
4163 24 : .map_err(CompactionError::Other)?;
4164 : // If a layer gets rewritten throughout gc-compaction, we need to keep that layer only in `compact_to` instead
4165 : // of `compact_from`.
4166 24 : let compact_from = {
4167 24 : let mut compact_from = Vec::new();
4168 24 : let mut compact_to_set = HashMap::new();
4169 51 : for layer in &compact_to {
4170 27 : compact_to_set.insert(layer.layer_desc().key(), layer);
4171 27 : }
4172 76 : for layer in &layer_selection {
4173 52 : if let Some(to) = compact_to_set.get(&layer.layer_desc().key()) {
4174 0 : tracing::info!(
4175 0 : "skipping delete {} because found same layer key at different generation {}",
4176 : layer,
4177 : to
4178 : );
4179 52 : } else {
4180 52 : compact_from.push(layer.clone());
4181 52 : }
4182 : }
4183 24 : compact_from
4184 : };
4185 24 : self.remote_client
4186 24 : .schedule_compaction_update(&compact_from, &compact_to)?;
4187 :
4188 24 : drop(gc_lock);
4189 :
4190 24 : Ok(CompactionOutcome::Done)
4191 28 : }
4192 : }
4193 :
4194 : struct TimelineAdaptor {
4195 : timeline: Arc<Timeline>,
4196 :
4197 : keyspace: (Lsn, KeySpace),
4198 :
4199 : new_deltas: Vec<ResidentLayer>,
4200 : new_images: Vec<ResidentLayer>,
4201 : layers_to_delete: Vec<Arc<PersistentLayerDesc>>,
4202 : }
4203 :
4204 : impl TimelineAdaptor {
4205 0 : pub fn new(timeline: &Arc<Timeline>, keyspace: (Lsn, KeySpace)) -> Self {
4206 0 : Self {
4207 0 : timeline: timeline.clone(),
4208 0 : keyspace,
4209 0 : new_images: Vec::new(),
4210 0 : new_deltas: Vec::new(),
4211 0 : layers_to_delete: Vec::new(),
4212 0 : }
4213 0 : }
4214 :
4215 0 : pub async fn flush_updates(&mut self) -> Result<(), CompactionError> {
4216 0 : let layers_to_delete = {
4217 0 : let guard = self
4218 0 : .timeline
4219 0 : .layers
4220 0 : .read(LayerManagerLockHolder::Compaction)
4221 0 : .await;
4222 0 : self.layers_to_delete
4223 0 : .iter()
4224 0 : .map(|x| guard.get_from_desc(x))
4225 0 : .collect::<Vec<Layer>>()
4226 : };
4227 0 : self.timeline
4228 0 : .finish_compact_batch(&self.new_deltas, &self.new_images, &layers_to_delete)
4229 0 : .await?;
4230 :
4231 0 : self.timeline
4232 0 : .upload_new_image_layers(std::mem::take(&mut self.new_images))?;
4233 :
4234 0 : self.new_deltas.clear();
4235 0 : self.layers_to_delete.clear();
4236 0 : Ok(())
4237 0 : }
4238 : }
4239 :
4240 : #[derive(Clone)]
4241 : struct ResidentDeltaLayer(ResidentLayer);
4242 : #[derive(Clone)]
4243 : struct ResidentImageLayer(ResidentLayer);
4244 :
4245 : impl CompactionJobExecutor for TimelineAdaptor {
4246 : type Key = pageserver_api::key::Key;
4247 :
4248 : type Layer = OwnArc<PersistentLayerDesc>;
4249 : type DeltaLayer = ResidentDeltaLayer;
4250 : type ImageLayer = ResidentImageLayer;
4251 :
4252 : type RequestContext = crate::context::RequestContext;
4253 :
4254 0 : fn get_shard_identity(&self) -> &ShardIdentity {
4255 0 : self.timeline.get_shard_identity()
4256 0 : }
4257 :
4258 0 : async fn get_layers(
4259 0 : &mut self,
4260 0 : key_range: &Range<Key>,
4261 0 : lsn_range: &Range<Lsn>,
4262 0 : _ctx: &RequestContext,
4263 0 : ) -> anyhow::Result<Vec<OwnArc<PersistentLayerDesc>>> {
4264 0 : self.flush_updates().await?;
4265 :
4266 0 : let guard = self
4267 0 : .timeline
4268 0 : .layers
4269 0 : .read(LayerManagerLockHolder::Compaction)
4270 0 : .await;
4271 0 : let layer_map = guard.layer_map()?;
4272 :
4273 0 : let result = layer_map
4274 0 : .iter_historic_layers()
4275 0 : .filter(|l| {
4276 0 : overlaps_with(&l.lsn_range, lsn_range) && overlaps_with(&l.key_range, key_range)
4277 0 : })
4278 0 : .map(OwnArc)
4279 0 : .collect();
4280 0 : Ok(result)
4281 0 : }
4282 :
4283 0 : async fn get_keyspace(
4284 0 : &mut self,
4285 0 : key_range: &Range<Key>,
4286 0 : lsn: Lsn,
4287 0 : _ctx: &RequestContext,
4288 0 : ) -> anyhow::Result<Vec<Range<Key>>> {
4289 0 : if lsn == self.keyspace.0 {
4290 0 : Ok(pageserver_compaction::helpers::intersect_keyspace(
4291 0 : &self.keyspace.1.ranges,
4292 0 : key_range,
4293 0 : ))
4294 : } else {
4295 : // The current compaction implementation only ever requests the key space
4296 : // at the compaction end LSN.
4297 0 : anyhow::bail!("keyspace not available for requested lsn");
4298 : }
4299 0 : }
4300 :
4301 0 : async fn downcast_delta_layer(
4302 0 : &self,
4303 0 : layer: &OwnArc<PersistentLayerDesc>,
4304 0 : ctx: &RequestContext,
4305 0 : ) -> anyhow::Result<Option<ResidentDeltaLayer>> {
4306 : // this is a lot more complex than a simple downcast...
4307 0 : if layer.is_delta() {
4308 0 : let l = {
4309 0 : let guard = self
4310 0 : .timeline
4311 0 : .layers
4312 0 : .read(LayerManagerLockHolder::Compaction)
4313 0 : .await;
4314 0 : guard.get_from_desc(layer)
4315 : };
4316 0 : let result = l.download_and_keep_resident(ctx).await?;
4317 :
4318 0 : Ok(Some(ResidentDeltaLayer(result)))
4319 : } else {
4320 0 : Ok(None)
4321 : }
4322 0 : }
4323 :
4324 0 : async fn create_image(
4325 0 : &mut self,
4326 0 : lsn: Lsn,
4327 0 : key_range: &Range<Key>,
4328 0 : ctx: &RequestContext,
4329 0 : ) -> anyhow::Result<()> {
4330 0 : Ok(self.create_image_impl(lsn, key_range, ctx).await?)
4331 0 : }
4332 :
4333 0 : async fn create_delta(
4334 0 : &mut self,
4335 0 : lsn_range: &Range<Lsn>,
4336 0 : key_range: &Range<Key>,
4337 0 : input_layers: &[ResidentDeltaLayer],
4338 0 : ctx: &RequestContext,
4339 0 : ) -> anyhow::Result<()> {
4340 0 : debug!("Create new layer {}..{}", lsn_range.start, lsn_range.end);
4341 :
4342 0 : let mut all_entries = Vec::new();
4343 0 : for dl in input_layers.iter() {
4344 0 : all_entries.extend(dl.load_keys(ctx).await?);
4345 : }
4346 :
4347 : // The current stdlib sorting implementation is designed in a way where it is
4348 : // particularly fast where the slice is made up of sorted sub-ranges.
4349 0 : all_entries.sort_by_key(|DeltaEntry { key, lsn, .. }| (*key, *lsn));
4350 :
4351 0 : let mut writer = DeltaLayerWriter::new(
4352 0 : self.timeline.conf,
4353 0 : self.timeline.timeline_id,
4354 0 : self.timeline.tenant_shard_id,
4355 0 : key_range.start,
4356 0 : lsn_range.clone(),
4357 0 : &self.timeline.gate,
4358 0 : self.timeline.cancel.clone(),
4359 0 : ctx,
4360 0 : )
4361 0 : .await?;
4362 :
4363 0 : let mut dup_values = 0;
4364 :
4365 : // This iterator walks through all key-value pairs from all the layers
4366 : // we're compacting, in key, LSN order.
4367 0 : let mut prev: Option<(Key, Lsn)> = None;
4368 : for &DeltaEntry {
4369 0 : key, lsn, ref val, ..
4370 0 : } in all_entries.iter()
4371 : {
4372 0 : if prev == Some((key, lsn)) {
4373 : // This is a duplicate. Skip it.
4374 : //
4375 : // It can happen if compaction is interrupted after writing some
4376 : // layers but not all, and we are compacting the range again.
4377 : // The calculations in the algorithm assume that there are no
4378 : // duplicates, so the math on targeted file size is likely off,
4379 : // and we will create smaller files than expected.
4380 0 : dup_values += 1;
4381 0 : continue;
4382 0 : }
4383 :
4384 0 : let value = val.load(ctx).await?;
4385 :
4386 0 : writer.put_value(key, lsn, value, ctx).await?;
4387 :
4388 0 : prev = Some((key, lsn));
4389 : }
4390 :
4391 0 : if dup_values > 0 {
4392 0 : warn!("delta layer created with {} duplicate values", dup_values);
4393 0 : }
4394 :
4395 0 : fail_point!("delta-layer-writer-fail-before-finish", |_| {
4396 0 : Err(anyhow::anyhow!(
4397 0 : "failpoint delta-layer-writer-fail-before-finish"
4398 0 : ))
4399 0 : });
4400 :
4401 0 : let (desc, path) = writer.finish(prev.unwrap().0.next(), ctx).await?;
4402 0 : let new_delta_layer =
4403 0 : Layer::finish_creating(self.timeline.conf, &self.timeline, desc, &path)?;
4404 :
4405 0 : self.new_deltas.push(new_delta_layer);
4406 0 : Ok(())
4407 0 : }
4408 :
4409 0 : async fn delete_layer(
4410 0 : &mut self,
4411 0 : layer: &OwnArc<PersistentLayerDesc>,
4412 0 : _ctx: &RequestContext,
4413 0 : ) -> anyhow::Result<()> {
4414 0 : self.layers_to_delete.push(layer.clone().0);
4415 0 : Ok(())
4416 0 : }
4417 : }
4418 :
4419 : impl TimelineAdaptor {
4420 0 : async fn create_image_impl(
4421 0 : &mut self,
4422 0 : lsn: Lsn,
4423 0 : key_range: &Range<Key>,
4424 0 : ctx: &RequestContext,
4425 0 : ) -> Result<(), CreateImageLayersError> {
4426 0 : let timer = self.timeline.metrics.create_images_time_histo.start_timer();
4427 :
4428 0 : let image_layer_writer = ImageLayerWriter::new(
4429 0 : self.timeline.conf,
4430 0 : self.timeline.timeline_id,
4431 0 : self.timeline.tenant_shard_id,
4432 0 : key_range,
4433 0 : lsn,
4434 0 : &self.timeline.gate,
4435 0 : self.timeline.cancel.clone(),
4436 0 : ctx,
4437 0 : )
4438 0 : .await
4439 0 : .map_err(CreateImageLayersError::Other)?;
4440 :
4441 0 : fail_point!("image-layer-writer-fail-before-finish", |_| {
4442 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
4443 0 : "failpoint image-layer-writer-fail-before-finish"
4444 0 : )))
4445 0 : });
4446 :
4447 0 : let keyspace = KeySpace {
4448 0 : ranges: self
4449 0 : .get_keyspace(key_range, lsn, ctx)
4450 0 : .await
4451 0 : .map_err(CreateImageLayersError::Other)?,
4452 : };
4453 : // TODO set proper (stateful) start. The create_image_layer_for_rel_blocks function mostly
4454 0 : let outcome = self
4455 0 : .timeline
4456 0 : .create_image_layer_for_rel_blocks(
4457 0 : &keyspace,
4458 0 : image_layer_writer,
4459 0 : lsn,
4460 0 : ctx,
4461 0 : key_range.clone(),
4462 0 : IoConcurrency::sequential(),
4463 0 : None,
4464 0 : )
4465 0 : .await?;
4466 :
4467 : if let ImageLayerCreationOutcome::Generated {
4468 0 : unfinished_image_layer,
4469 0 : } = outcome
4470 : {
4471 0 : let (desc, path) = unfinished_image_layer
4472 0 : .finish(ctx)
4473 0 : .await
4474 0 : .map_err(CreateImageLayersError::Other)?;
4475 0 : let image_layer =
4476 0 : Layer::finish_creating(self.timeline.conf, &self.timeline, desc, &path)
4477 0 : .map_err(CreateImageLayersError::Other)?;
4478 0 : self.new_images.push(image_layer);
4479 0 : }
4480 :
4481 0 : timer.stop_and_record();
4482 :
4483 0 : Ok(())
4484 0 : }
4485 : }
4486 :
4487 : impl CompactionRequestContext for crate::context::RequestContext {}
4488 :
4489 : #[derive(Debug, Clone)]
4490 : pub struct OwnArc<T>(pub Arc<T>);
4491 :
4492 : impl<T> Deref for OwnArc<T> {
4493 : type Target = <Arc<T> as Deref>::Target;
4494 0 : fn deref(&self) -> &Self::Target {
4495 0 : &self.0
4496 0 : }
4497 : }
4498 :
4499 : impl<T> AsRef<T> for OwnArc<T> {
4500 0 : fn as_ref(&self) -> &T {
4501 0 : self.0.as_ref()
4502 0 : }
4503 : }
4504 :
4505 : impl CompactionLayer<Key> for OwnArc<PersistentLayerDesc> {
4506 0 : fn key_range(&self) -> &Range<Key> {
4507 0 : &self.key_range
4508 0 : }
4509 0 : fn lsn_range(&self) -> &Range<Lsn> {
4510 0 : &self.lsn_range
4511 0 : }
4512 0 : fn file_size(&self) -> u64 {
4513 0 : self.file_size
4514 0 : }
4515 0 : fn short_id(&self) -> std::string::String {
4516 0 : self.as_ref().short_id().to_string()
4517 0 : }
4518 0 : fn is_delta(&self) -> bool {
4519 0 : self.as_ref().is_delta()
4520 0 : }
4521 : }
4522 :
4523 : impl CompactionLayer<Key> for OwnArc<DeltaLayer> {
4524 0 : fn key_range(&self) -> &Range<Key> {
4525 0 : &self.layer_desc().key_range
4526 0 : }
4527 0 : fn lsn_range(&self) -> &Range<Lsn> {
4528 0 : &self.layer_desc().lsn_range
4529 0 : }
4530 0 : fn file_size(&self) -> u64 {
4531 0 : self.layer_desc().file_size
4532 0 : }
4533 0 : fn short_id(&self) -> std::string::String {
4534 0 : self.layer_desc().short_id().to_string()
4535 0 : }
4536 0 : fn is_delta(&self) -> bool {
4537 0 : true
4538 0 : }
4539 : }
4540 :
4541 : impl CompactionLayer<Key> for ResidentDeltaLayer {
4542 0 : fn key_range(&self) -> &Range<Key> {
4543 0 : &self.0.layer_desc().key_range
4544 0 : }
4545 0 : fn lsn_range(&self) -> &Range<Lsn> {
4546 0 : &self.0.layer_desc().lsn_range
4547 0 : }
4548 0 : fn file_size(&self) -> u64 {
4549 0 : self.0.layer_desc().file_size
4550 0 : }
4551 0 : fn short_id(&self) -> std::string::String {
4552 0 : self.0.layer_desc().short_id().to_string()
4553 0 : }
4554 0 : fn is_delta(&self) -> bool {
4555 0 : true
4556 0 : }
4557 : }
4558 :
4559 : impl CompactionDeltaLayer<TimelineAdaptor> for ResidentDeltaLayer {
4560 : type DeltaEntry<'a> = DeltaEntry<'a>;
4561 :
4562 0 : async fn load_keys(&self, ctx: &RequestContext) -> anyhow::Result<Vec<DeltaEntry<'_>>> {
4563 0 : self.0.get_as_delta(ctx).await?.index_entries(ctx).await
4564 0 : }
4565 : }
4566 :
4567 : impl CompactionLayer<Key> for ResidentImageLayer {
4568 0 : fn key_range(&self) -> &Range<Key> {
4569 0 : &self.0.layer_desc().key_range
4570 0 : }
4571 0 : fn lsn_range(&self) -> &Range<Lsn> {
4572 0 : &self.0.layer_desc().lsn_range
4573 0 : }
4574 0 : fn file_size(&self) -> u64 {
4575 0 : self.0.layer_desc().file_size
4576 0 : }
4577 0 : fn short_id(&self) -> std::string::String {
4578 0 : self.0.layer_desc().short_id().to_string()
4579 0 : }
4580 0 : fn is_delta(&self) -> bool {
4581 0 : false
4582 0 : }
4583 : }
4584 : impl CompactionImageLayer<TimelineAdaptor> for ResidentImageLayer {}
|