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 : "missing key during compaction: {err:?}"
1401 : );
1402 0 : }
1403 0 : })?;
1404 :
1405 80 : self.last_image_layer_creation_status
1406 80 : .store(Arc::new(outcome.clone()));
1407 :
1408 80 : self.upload_new_image_layers(image_layers)?;
1409 80 : if let LastImageLayerCreationStatus::Incomplete { .. } = outcome {
1410 : // Yield and do not do any other kind of compaction.
1411 0 : info!(
1412 0 : "skipping shard ancestor compaction due to pending image layer generation tasks (preempted by L0 compaction)."
1413 : );
1414 0 : return Ok(CompactionOutcome::YieldForL0);
1415 80 : }
1416 : }
1417 :
1418 : Ok(_) => {
1419 : // This happens very frequently so we don't want to log it.
1420 112 : debug!("skipping repartitioning due to image compaction LSN being below GC cutoff");
1421 : }
1422 :
1423 : // Suppress errors when cancelled.
1424 : //
1425 : // Log other errors but continue. Failure to repartition is normal, if the timeline was just created
1426 : // as an empty timeline. Also in unit tests, when we use the timeline as a simple
1427 : // key-value store, ignoring the datadir layout. Log the error but continue.
1428 : //
1429 : // TODO:
1430 : // 1. shouldn't we return early here if we observe cancellation
1431 : // 2. Experiment: can we stop checking self.cancel here?
1432 0 : Err(_) if self.cancel.is_cancelled() => {} // TODO: try how we fare removing this branch
1433 0 : Err(err) if err.is_cancel() => {}
1434 : Err(RepartitionError::CollectKeyspace(
1435 0 : e @ CollectKeySpaceError::Decode(_)
1436 0 : | e @ CollectKeySpaceError::PageRead(
1437 : PageReconstructError::MissingKey(_) | PageReconstructError::WalRedo(_),
1438 : ),
1439 : )) => {
1440 : // Alert on critical errors that indicate data corruption.
1441 0 : critical_timeline!(
1442 0 : self.tenant_shard_id,
1443 0 : self.timeline_id,
1444 0 : "could not compact, repartitioning keyspace failed: {e:?}"
1445 : );
1446 : }
1447 0 : Err(e) => error!(
1448 0 : "could not compact, repartitioning keyspace failed: {:?}",
1449 0 : e.into_anyhow()
1450 : ),
1451 : };
1452 :
1453 192 : let partition_count = self.partitioning.read().0.0.parts.len();
1454 :
1455 : // 4. Shard ancestor compaction
1456 192 : if self.get_compaction_shard_ancestor() && self.shard_identity.count >= ShardCount::new(2) {
1457 : // Limit the number of layer rewrites to the number of partitions: this means its
1458 : // runtime should be comparable to a full round of image layer creations, rather than
1459 : // being potentially much longer.
1460 0 : let rewrite_max = partition_count;
1461 :
1462 0 : let outcome = self
1463 0 : .compact_shard_ancestors(
1464 0 : rewrite_max,
1465 0 : options.flags.contains(CompactFlags::YieldForL0),
1466 0 : ctx,
1467 0 : )
1468 0 : .await?;
1469 0 : match outcome {
1470 0 : CompactionOutcome::Pending | CompactionOutcome::YieldForL0 => return Ok(outcome),
1471 0 : CompactionOutcome::Done | CompactionOutcome::Skipped => {}
1472 : }
1473 192 : }
1474 :
1475 192 : Ok(CompactionOutcome::Done)
1476 192 : }
1477 :
1478 : /* BEGIN_HADRON */
1479 : // Get the force image creation LSN based on gc_cutoff_lsn.
1480 : // Note that this is an estimation and the workload rate may suddenly change. When that happens,
1481 : // the force image creation may be too early or too late, but eventually it should be able to catch up.
1482 193 : pub(crate) fn get_force_image_creation_lsn(self: &Arc<Self>) -> Option<Lsn> {
1483 193 : let image_creation_period = self.get_image_layer_force_creation_period()?;
1484 1 : let current_lsn = self.get_last_record_lsn();
1485 1 : let pitr_lsn = self.gc_info.read().unwrap().cutoffs.time?;
1486 1 : let pitr_interval = self.get_pitr_interval();
1487 1 : if pitr_lsn == Lsn::INVALID || pitr_interval.is_zero() {
1488 0 : tracing::warn!(
1489 0 : "pitr LSN/interval not found, skipping force image creation LSN calculation"
1490 : );
1491 0 : return None;
1492 1 : }
1493 :
1494 1 : let delta_lsn = current_lsn.checked_sub(pitr_lsn).unwrap().0
1495 1 : * image_creation_period.as_secs()
1496 1 : / pitr_interval.as_secs();
1497 1 : let force_image_creation_lsn = current_lsn.checked_sub(delta_lsn).unwrap_or(Lsn(0));
1498 :
1499 1 : tracing::info!(
1500 0 : "Tenant shard {} computed force_image_creation_lsn: {}. Current lsn: {}, image_layer_force_creation_period: {:?}, GC cutoff: {}, PITR interval: {:?}",
1501 0 : self.tenant_shard_id,
1502 : force_image_creation_lsn,
1503 : current_lsn,
1504 : image_creation_period,
1505 : pitr_lsn,
1506 : pitr_interval
1507 : );
1508 :
1509 1 : Some(force_image_creation_lsn)
1510 193 : }
1511 : /* END_HADRON */
1512 :
1513 : /// Check for layers that are elegible to be rewritten:
1514 : /// - Shard splitting: After a shard split, ancestor layers beyond pitr_interval, so that
1515 : /// we don't indefinitely retain keys in this shard that aren't needed.
1516 : /// - For future use: layers beyond pitr_interval that are in formats we would
1517 : /// rather not maintain compatibility with indefinitely.
1518 : ///
1519 : /// Note: this phase may read and write many gigabytes of data: use rewrite_max to bound
1520 : /// how much work it will try to do in each compaction pass.
1521 0 : async fn compact_shard_ancestors(
1522 0 : self: &Arc<Self>,
1523 0 : rewrite_max: usize,
1524 0 : yield_for_l0: bool,
1525 0 : ctx: &RequestContext,
1526 0 : ) -> Result<CompactionOutcome, CompactionError> {
1527 0 : let mut outcome = CompactionOutcome::Done;
1528 0 : let mut drop_layers = Vec::new();
1529 0 : let mut layers_to_rewrite: Vec<Layer> = Vec::new();
1530 :
1531 : // We will use the Lsn cutoff of the last GC as a threshold for rewriting layers: if a
1532 : // layer is behind this Lsn, it indicates that the layer is being retained beyond the
1533 : // pitr_interval, for example because a branchpoint references it.
1534 : //
1535 : // Holding this read guard also blocks [`Self::gc_timeline`] from entering while we
1536 : // are rewriting layers.
1537 0 : let latest_gc_cutoff = self.get_applied_gc_cutoff_lsn();
1538 0 : let pitr_cutoff = self.gc_info.read().unwrap().cutoffs.time;
1539 :
1540 0 : let layers = self.layers.read(LayerManagerLockHolder::Compaction).await;
1541 0 : let layers_iter = layers.layer_map()?.iter_historic_layers();
1542 0 : let (layers_total, mut layers_checked) = (layers_iter.len(), 0);
1543 0 : for layer_desc in layers_iter {
1544 0 : layers_checked += 1;
1545 0 : let layer = layers.get_from_desc(&layer_desc);
1546 0 : if layer.metadata().shard.shard_count == self.shard_identity.count {
1547 : // This layer does not belong to a historic ancestor, no need to re-image it.
1548 0 : continue;
1549 0 : }
1550 :
1551 : // This layer was created on an ancestor shard: check if it contains any data for this shard.
1552 0 : let sharded_range = ShardedRange::new(layer_desc.get_key_range(), &self.shard_identity);
1553 0 : let layer_local_page_count = sharded_range.page_count();
1554 0 : let layer_raw_page_count = ShardedRange::raw_size(&layer_desc.get_key_range());
1555 0 : if layer_local_page_count == 0 {
1556 : // This ancestral layer only covers keys that belong to other shards.
1557 : // We include the full metadata in the log: if we had some critical bug that caused
1558 : // us to incorrectly drop layers, this would simplify manually debugging + reinstating those layers.
1559 0 : debug!(%layer, old_metadata=?layer.metadata(),
1560 0 : "dropping layer after shard split, contains no keys for this shard",
1561 : );
1562 :
1563 0 : if cfg!(debug_assertions) {
1564 : // Expensive, exhaustive check of keys in this layer: this guards against ShardedRange's calculations being
1565 : // wrong. If ShardedRange claims the local page count is zero, then no keys in this layer
1566 : // should be !is_key_disposable()
1567 : // TODO: exclude sparse keyspace from this check, otherwise it will infinitely loop.
1568 0 : let range = layer_desc.get_key_range();
1569 0 : let mut key = range.start;
1570 0 : while key < range.end {
1571 0 : debug_assert!(self.shard_identity.is_key_disposable(&key));
1572 0 : key = key.next();
1573 : }
1574 0 : }
1575 :
1576 0 : drop_layers.push(layer);
1577 0 : continue;
1578 0 : } else if layer_local_page_count != u32::MAX
1579 0 : && layer_local_page_count == layer_raw_page_count
1580 : {
1581 0 : debug!(%layer,
1582 0 : "layer is entirely shard local ({} keys), no need to filter it",
1583 : layer_local_page_count
1584 : );
1585 0 : continue;
1586 0 : }
1587 :
1588 : // Only rewrite a layer if we can reclaim significant space.
1589 0 : if layer_local_page_count != u32::MAX
1590 0 : && layer_local_page_count as f64 / layer_raw_page_count as f64
1591 0 : <= ANCESTOR_COMPACTION_REWRITE_THRESHOLD
1592 : {
1593 0 : debug!(%layer,
1594 0 : "layer has a large share of local pages \
1595 0 : ({layer_local_page_count}/{layer_raw_page_count} > \
1596 0 : {ANCESTOR_COMPACTION_REWRITE_THRESHOLD}), not rewriting",
1597 : );
1598 0 : }
1599 :
1600 : // Don't bother re-writing a layer if it is within the PITR window: it will age-out eventually
1601 : // without incurring the I/O cost of a rewrite.
1602 0 : if layer_desc.get_lsn_range().end >= *latest_gc_cutoff {
1603 0 : debug!(%layer, "Skipping rewrite of layer still in GC window ({} >= {})",
1604 0 : layer_desc.get_lsn_range().end, *latest_gc_cutoff);
1605 0 : continue;
1606 0 : }
1607 :
1608 : // We do not yet implement rewrite of delta layers.
1609 0 : if layer_desc.is_delta() {
1610 0 : debug!(%layer, "Skipping rewrite of delta layer");
1611 0 : continue;
1612 0 : }
1613 :
1614 : // We don't bother rewriting layers that aren't visible, since these won't be needed by
1615 : // reads and will likely be garbage collected soon.
1616 0 : if layer.visibility() != LayerVisibilityHint::Visible {
1617 0 : debug!(%layer, "Skipping rewrite of invisible layer");
1618 0 : continue;
1619 0 : }
1620 :
1621 : // Only rewrite layers if their generations differ. This guarantees:
1622 : // - that local rewrite is safe, as local layer paths will differ between existing layer and rewritten one
1623 : // - that the layer is persistent in remote storage, as we only see old-generation'd layer via loading from remote storage
1624 0 : if layer.metadata().generation == self.generation {
1625 0 : debug!(%layer, "Skipping rewrite, is not from old generation");
1626 0 : continue;
1627 0 : }
1628 :
1629 0 : if layers_to_rewrite.len() >= rewrite_max {
1630 0 : debug!(%layer, "Will rewrite layer on a future compaction, already rewrote {}",
1631 0 : layers_to_rewrite.len()
1632 : );
1633 0 : outcome = CompactionOutcome::Pending;
1634 0 : break;
1635 0 : }
1636 :
1637 : // Fall through: all our conditions for doing a rewrite passed.
1638 0 : layers_to_rewrite.push(layer);
1639 : }
1640 :
1641 : // Drop read lock on layer map before we start doing time-consuming I/O.
1642 0 : drop(layers);
1643 :
1644 : // Drop out early if there's nothing to do.
1645 0 : if layers_to_rewrite.is_empty() && drop_layers.is_empty() {
1646 0 : return Ok(CompactionOutcome::Done);
1647 0 : }
1648 :
1649 0 : info!(
1650 0 : "starting shard ancestor compaction, rewriting {} layers and dropping {} layers, \
1651 0 : checked {layers_checked}/{layers_total} layers \
1652 0 : (latest_gc_cutoff={} pitr_cutoff={:?})",
1653 0 : layers_to_rewrite.len(),
1654 0 : drop_layers.len(),
1655 0 : *latest_gc_cutoff,
1656 : pitr_cutoff,
1657 : );
1658 0 : let started = Instant::now();
1659 :
1660 0 : let mut replace_image_layers = Vec::new();
1661 0 : let total = layers_to_rewrite.len();
1662 :
1663 0 : for (i, layer) in layers_to_rewrite.into_iter().enumerate() {
1664 0 : if self.cancel.is_cancelled() {
1665 0 : return Err(CompactionError::new_cancelled());
1666 0 : }
1667 :
1668 0 : info!(layer=%layer, "rewriting layer after shard split: {}/{}", i, total);
1669 :
1670 0 : let mut image_layer_writer = ImageLayerWriter::new(
1671 0 : self.conf,
1672 0 : self.timeline_id,
1673 0 : self.tenant_shard_id,
1674 0 : &layer.layer_desc().key_range,
1675 0 : layer.layer_desc().image_layer_lsn(),
1676 0 : &self.gate,
1677 0 : self.cancel.clone(),
1678 0 : ctx,
1679 0 : )
1680 0 : .await
1681 0 : .map_err(CompactionError::Other)?;
1682 :
1683 : // Safety of layer rewrites:
1684 : // - We are writing to a different local file path than we are reading from, so the old Layer
1685 : // cannot interfere with the new one.
1686 : // - In the page cache, contents for a particular VirtualFile are stored with a file_id that
1687 : // is different for two layers with the same name (in `ImageLayerInner::new` we always
1688 : // acquire a fresh id from [`crate::page_cache::next_file_id`]. So readers do not risk
1689 : // reading the index from one layer file, and then data blocks from the rewritten layer file.
1690 : // - Any readers that have a reference to the old layer will keep it alive until they are done
1691 : // with it. If they are trying to promote from remote storage, that will fail, but this is the same
1692 : // as for compaction generally: compaction is allowed to delete layers that readers might be trying to use.
1693 : // - We do not run concurrently with other kinds of compaction, so the only layer map writes we race with are:
1694 : // - GC, which at worst witnesses us "undelete" a layer that they just deleted.
1695 : // - ingestion, which only inserts layers, therefore cannot collide with us.
1696 0 : let resident = layer.download_and_keep_resident(ctx).await?;
1697 :
1698 0 : let keys_written = resident
1699 0 : .filter(&self.shard_identity, &mut image_layer_writer, ctx)
1700 0 : .await?;
1701 :
1702 0 : if keys_written > 0 {
1703 0 : let (desc, path) = image_layer_writer
1704 0 : .finish(ctx)
1705 0 : .await
1706 0 : .map_err(CompactionError::Other)?;
1707 0 : let new_layer = Layer::finish_creating(self.conf, self, desc, &path)
1708 0 : .map_err(CompactionError::Other)?;
1709 0 : info!(layer=%new_layer, "rewrote layer, {} -> {} bytes",
1710 0 : layer.metadata().file_size,
1711 0 : new_layer.metadata().file_size);
1712 :
1713 0 : replace_image_layers.push((layer, new_layer));
1714 0 : } else {
1715 0 : // Drop the old layer. Usually for this case we would already have noticed that
1716 0 : // the layer has no data for us with the ShardedRange check above, but
1717 0 : drop_layers.push(layer);
1718 0 : }
1719 :
1720 : // Yield for L0 compaction if necessary, but make sure we update the layer map below
1721 : // with the work we've already done.
1722 0 : if yield_for_l0
1723 0 : && self
1724 0 : .l0_compaction_trigger
1725 0 : .notified()
1726 0 : .now_or_never()
1727 0 : .is_some()
1728 : {
1729 0 : info!("shard ancestor compaction yielding for L0 compaction");
1730 0 : outcome = CompactionOutcome::YieldForL0;
1731 0 : break;
1732 0 : }
1733 : }
1734 :
1735 0 : for layer in &drop_layers {
1736 0 : info!(%layer, old_metadata=?layer.metadata(),
1737 0 : "dropping layer after shard split (no keys for this shard)",
1738 : );
1739 : }
1740 :
1741 : // At this point, we have replaced local layer files with their rewritten form, but not yet uploaded
1742 : // metadata to reflect that. If we restart here, the replaced layer files will look invalid (size mismatch
1743 : // to remote index) and be removed. This is inefficient but safe.
1744 0 : fail::fail_point!("compact-shard-ancestors-localonly");
1745 :
1746 : // Update the LayerMap so that readers will use the new layers, and enqueue it for writing to remote storage
1747 0 : self.rewrite_layers(replace_image_layers, drop_layers)
1748 0 : .await?;
1749 :
1750 0 : fail::fail_point!("compact-shard-ancestors-enqueued");
1751 :
1752 : // We wait for all uploads to complete before finishing this compaction stage. This is not
1753 : // necessary for correctness, but it simplifies testing, and avoids proceeding with another
1754 : // Timeline's compaction while this timeline's uploads may be generating lots of disk I/O
1755 : // load.
1756 0 : if outcome != CompactionOutcome::YieldForL0 {
1757 0 : info!("shard ancestor compaction waiting for uploads");
1758 0 : tokio::select! {
1759 0 : result = self.remote_client.wait_completion() => match result {
1760 0 : Ok(()) => {},
1761 0 : Err(WaitCompletionError::NotInitialized(ni)) => return Err(CompactionError::from(ni)),
1762 : Err(WaitCompletionError::UploadQueueShutDownOrStopped) => {
1763 0 : return Err(CompactionError::new_cancelled());
1764 : }
1765 : },
1766 : // Don't wait if there's L0 compaction to do. We don't need to update the outcome
1767 : // here, because we've already done the actual work.
1768 0 : _ = self.l0_compaction_trigger.notified(), if yield_for_l0 => {},
1769 : }
1770 0 : }
1771 :
1772 0 : info!(
1773 0 : "shard ancestor compaction done in {:.3}s{}",
1774 0 : started.elapsed().as_secs_f64(),
1775 0 : match outcome {
1776 : CompactionOutcome::Pending =>
1777 0 : format!(", with pending work (rewrite_max={rewrite_max})"),
1778 0 : CompactionOutcome::YieldForL0 => String::from(", yielding for L0 compaction"),
1779 0 : CompactionOutcome::Skipped | CompactionOutcome::Done => String::new(),
1780 : }
1781 : );
1782 :
1783 0 : fail::fail_point!("compact-shard-ancestors-persistent");
1784 :
1785 0 : Ok(outcome)
1786 0 : }
1787 :
1788 : /// Update the LayerVisibilityHint of layers covered by image layers, based on whether there is
1789 : /// an image layer between them and the most recent readable LSN (branch point or tip of timeline). The
1790 : /// purpose of the visibility hint is to record which layers need to be available to service reads.
1791 : ///
1792 : /// The result may be used as an input to eviction and secondary downloads to de-prioritize layers
1793 : /// that we know won't be needed for reads.
1794 123 : pub(crate) async fn update_layer_visibility(
1795 123 : &self,
1796 123 : ) -> Result<(), super::layer_manager::Shutdown> {
1797 123 : let head_lsn = self.get_last_record_lsn();
1798 :
1799 : // We will sweep through layers in reverse-LSN order. We only do historic layers. L0 deltas
1800 : // are implicitly left visible, because LayerVisibilityHint's default is Visible, and we never modify it here.
1801 : // Note that L0 deltas _can_ be covered by image layers, but we consider them 'visible' because we anticipate that
1802 : // they will be subject to L0->L1 compaction in the near future.
1803 123 : let layer_manager = self
1804 123 : .layers
1805 123 : .read(LayerManagerLockHolder::GetLayerMapInfo)
1806 123 : .await;
1807 123 : let layer_map = layer_manager.layer_map()?;
1808 :
1809 123 : let readable_points = {
1810 123 : let children = self.gc_info.read().unwrap().retain_lsns.clone();
1811 :
1812 123 : let mut readable_points = Vec::with_capacity(children.len() + 1);
1813 124 : for (child_lsn, _child_timeline_id, is_offloaded) in &children {
1814 1 : if *is_offloaded == MaybeOffloaded::Yes {
1815 0 : continue;
1816 1 : }
1817 1 : readable_points.push(*child_lsn);
1818 : }
1819 123 : readable_points.push(head_lsn);
1820 123 : readable_points
1821 : };
1822 :
1823 123 : let (layer_visibility, covered) = layer_map.get_visibility(readable_points);
1824 313 : for (layer_desc, visibility) in layer_visibility {
1825 190 : // FIXME: a more efficiency bulk zip() through the layers rather than NlogN getting each one
1826 190 : let layer = layer_manager.get_from_desc(&layer_desc);
1827 190 : layer.set_visibility(visibility);
1828 190 : }
1829 :
1830 : // TODO: publish our covered KeySpace to our parent, so that when they update their visibility, they can
1831 : // avoid assuming that everything at a branch point is visible.
1832 123 : drop(covered);
1833 123 : Ok(())
1834 123 : }
1835 :
1836 : /// Collect a bunch of Level 0 layer files, and compact and reshuffle them as
1837 : /// as Level 1 files. Returns whether the L0 layers are fully compacted.
1838 192 : async fn compact_level0(
1839 192 : self: &Arc<Self>,
1840 192 : target_file_size: u64,
1841 192 : force_compaction_ignore_threshold: bool,
1842 192 : force_compaction_lsn: Option<Lsn>,
1843 192 : ctx: &RequestContext,
1844 192 : ) -> Result<CompactionOutcome, CompactionError> {
1845 : let CompactLevel0Phase1Result {
1846 192 : new_layers,
1847 192 : deltas_to_compact,
1848 192 : outcome,
1849 : } = {
1850 192 : let phase1_span = info_span!("compact_level0_phase1");
1851 192 : let ctx = ctx.attached_child();
1852 192 : let stats = CompactLevel0Phase1StatsBuilder {
1853 192 : version: Some(2),
1854 192 : tenant_id: Some(self.tenant_shard_id),
1855 192 : timeline_id: Some(self.timeline_id),
1856 192 : ..Default::default()
1857 192 : };
1858 :
1859 192 : self.compact_level0_phase1(
1860 192 : stats,
1861 192 : target_file_size,
1862 192 : force_compaction_ignore_threshold,
1863 192 : force_compaction_lsn,
1864 192 : &ctx,
1865 192 : )
1866 192 : .instrument(phase1_span)
1867 192 : .await?
1868 : };
1869 :
1870 192 : if new_layers.is_empty() && deltas_to_compact.is_empty() {
1871 : // nothing to do
1872 169 : return Ok(CompactionOutcome::Done);
1873 23 : }
1874 :
1875 23 : self.finish_compact_batch(&new_layers, &Vec::new(), &deltas_to_compact)
1876 23 : .await?;
1877 23 : Ok(outcome)
1878 192 : }
1879 :
1880 : /// Level0 files first phase of compaction, explained in the [`Self::compact_legacy`] comment.
1881 192 : async fn compact_level0_phase1(
1882 192 : self: &Arc<Self>,
1883 192 : mut stats: CompactLevel0Phase1StatsBuilder,
1884 192 : target_file_size: u64,
1885 192 : force_compaction_ignore_threshold: bool,
1886 192 : force_compaction_lsn: Option<Lsn>,
1887 192 : ctx: &RequestContext,
1888 192 : ) -> Result<CompactLevel0Phase1Result, CompactionError> {
1889 192 : let begin = tokio::time::Instant::now();
1890 192 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
1891 192 : let now = tokio::time::Instant::now();
1892 192 : stats.read_lock_acquisition_micros =
1893 192 : DurationRecorder::Recorded(RecordedDuration(now - begin), now);
1894 :
1895 192 : let layers = guard.layer_map()?;
1896 192 : let level0_deltas = layers.level0_deltas();
1897 192 : stats.level0_deltas_count = Some(level0_deltas.len());
1898 :
1899 : // Only compact if enough layers have accumulated.
1900 192 : let threshold = self.get_compaction_threshold();
1901 192 : if level0_deltas.is_empty() || level0_deltas.len() < threshold {
1902 179 : if force_compaction_ignore_threshold {
1903 12 : if !level0_deltas.is_empty() {
1904 10 : info!(
1905 0 : level0_deltas = level0_deltas.len(),
1906 0 : threshold, "too few deltas to compact, but forcing compaction"
1907 : );
1908 : } else {
1909 2 : info!(
1910 0 : level0_deltas = level0_deltas.len(),
1911 0 : threshold, "too few deltas to compact, cannot force compaction"
1912 : );
1913 2 : return Ok(CompactLevel0Phase1Result::default());
1914 : }
1915 : } else {
1916 : // HADRON
1917 167 : let min_lsn = level0_deltas
1918 167 : .iter()
1919 602 : .map(|a| a.get_lsn_range().start)
1920 167 : .reduce(min);
1921 167 : if force_compaction_lsn.is_some()
1922 0 : && min_lsn.is_some()
1923 0 : && min_lsn.unwrap() < force_compaction_lsn.unwrap()
1924 : {
1925 0 : info!(
1926 0 : "forcing L0 compaction of {} L0 deltas. Min lsn: {}, force compaction lsn: {}",
1927 0 : level0_deltas.len(),
1928 0 : min_lsn.unwrap(),
1929 0 : force_compaction_lsn.unwrap()
1930 : );
1931 : } else {
1932 167 : debug!(
1933 0 : level0_deltas = level0_deltas.len(),
1934 0 : threshold, "too few deltas to compact"
1935 : );
1936 167 : return Ok(CompactLevel0Phase1Result::default());
1937 : }
1938 : }
1939 13 : }
1940 :
1941 23 : let mut level0_deltas = level0_deltas
1942 23 : .iter()
1943 201 : .map(|x| guard.get_from_desc(x))
1944 23 : .collect::<Vec<_>>();
1945 :
1946 23 : drop_layer_manager_rlock(guard);
1947 :
1948 : // The is the last LSN that we have seen for L0 compaction in the timeline. This LSN might be updated
1949 : // by the time we finish the compaction. So we need to get it here.
1950 23 : let l0_last_record_lsn = self.get_last_record_lsn();
1951 :
1952 : // Gather the files to compact in this iteration.
1953 : //
1954 : // Start with the oldest Level 0 delta file, and collect any other
1955 : // level 0 files that form a contiguous sequence, such that the end
1956 : // LSN of previous file matches the start LSN of the next file.
1957 : //
1958 : // Note that if the files don't form such a sequence, we might
1959 : // "compact" just a single file. That's a bit pointless, but it allows
1960 : // us to get rid of the level 0 file, and compact the other files on
1961 : // the next iteration. This could probably made smarter, but such
1962 : // "gaps" in the sequence of level 0 files should only happen in case
1963 : // of a crash, partial download from cloud storage, or something like
1964 : // that, so it's not a big deal in practice.
1965 356 : level0_deltas.sort_by_key(|l| l.layer_desc().lsn_range.start);
1966 23 : let mut level0_deltas_iter = level0_deltas.iter();
1967 :
1968 23 : let first_level0_delta = level0_deltas_iter.next().unwrap();
1969 23 : let mut prev_lsn_end = first_level0_delta.layer_desc().lsn_range.end;
1970 23 : let mut deltas_to_compact = Vec::with_capacity(level0_deltas.len());
1971 :
1972 : // Accumulate the size of layers in `deltas_to_compact`
1973 23 : let mut deltas_to_compact_bytes = 0;
1974 :
1975 : // Under normal circumstances, we will accumulate up to compaction_upper_limit L0s of size
1976 : // checkpoint_distance each. To avoid edge cases using extra system resources, bound our
1977 : // work in this function to only operate on this much delta data at once.
1978 : //
1979 : // In general, compaction_threshold should be <= compaction_upper_limit, but in case that
1980 : // the constraint is not respected, we use the larger of the two.
1981 23 : let delta_size_limit = std::cmp::max(
1982 23 : self.get_compaction_upper_limit(),
1983 23 : self.get_compaction_threshold(),
1984 23 : ) as u64
1985 23 : * std::cmp::max(self.get_checkpoint_distance(), DEFAULT_CHECKPOINT_DISTANCE);
1986 :
1987 23 : let mut fully_compacted = true;
1988 :
1989 23 : deltas_to_compact.push(first_level0_delta.download_and_keep_resident(ctx).await?);
1990 201 : for l in level0_deltas_iter {
1991 178 : let lsn_range = &l.layer_desc().lsn_range;
1992 :
1993 178 : if lsn_range.start != prev_lsn_end {
1994 0 : break;
1995 178 : }
1996 178 : deltas_to_compact.push(l.download_and_keep_resident(ctx).await?);
1997 178 : deltas_to_compact_bytes += l.metadata().file_size;
1998 178 : prev_lsn_end = lsn_range.end;
1999 :
2000 178 : if deltas_to_compact_bytes >= delta_size_limit {
2001 0 : info!(
2002 0 : l0_deltas_selected = deltas_to_compact.len(),
2003 0 : l0_deltas_total = level0_deltas.len(),
2004 0 : "L0 compaction picker hit max delta layer size limit: {}",
2005 : delta_size_limit
2006 : );
2007 0 : fully_compacted = false;
2008 :
2009 : // Proceed with compaction, but only a subset of L0s
2010 0 : break;
2011 178 : }
2012 : }
2013 23 : let lsn_range = Range {
2014 23 : start: deltas_to_compact
2015 23 : .first()
2016 23 : .unwrap()
2017 23 : .layer_desc()
2018 23 : .lsn_range
2019 23 : .start,
2020 23 : end: deltas_to_compact.last().unwrap().layer_desc().lsn_range.end,
2021 23 : };
2022 :
2023 23 : info!(
2024 0 : "Starting Level0 compaction in LSN range {}-{} for {} layers ({} deltas in total)",
2025 : lsn_range.start,
2026 : lsn_range.end,
2027 0 : deltas_to_compact.len(),
2028 0 : level0_deltas.len()
2029 : );
2030 :
2031 201 : for l in deltas_to_compact.iter() {
2032 201 : info!("compact includes {l}");
2033 : }
2034 :
2035 : // We don't need the original list of layers anymore. Drop it so that
2036 : // we don't accidentally use it later in the function.
2037 23 : drop(level0_deltas);
2038 :
2039 23 : stats.compaction_prerequisites_micros = stats.read_lock_acquisition_micros.till_now();
2040 :
2041 : // TODO: replace with streaming k-merge
2042 23 : let all_keys = {
2043 23 : let mut all_keys = Vec::new();
2044 201 : for l in deltas_to_compact.iter() {
2045 201 : if self.cancel.is_cancelled() {
2046 0 : return Err(CompactionError::new_cancelled());
2047 201 : }
2048 201 : let delta = l.get_as_delta(ctx).await.map_err(CompactionError::Other)?;
2049 201 : let keys = delta
2050 201 : .index_entries(ctx)
2051 201 : .await
2052 201 : .map_err(CompactionError::Other)?;
2053 201 : all_keys.extend(keys);
2054 : }
2055 : // The current stdlib sorting implementation is designed in a way where it is
2056 : // particularly fast where the slice is made up of sorted sub-ranges.
2057 2137928 : all_keys.sort_by_key(|DeltaEntry { key, lsn, .. }| (*key, *lsn));
2058 23 : all_keys
2059 : };
2060 :
2061 23 : stats.read_lock_held_key_sort_micros = stats.compaction_prerequisites_micros.till_now();
2062 :
2063 : // Determine N largest holes where N is number of compacted layers. The vec is sorted by key range start.
2064 : //
2065 : // A hole is a key range for which this compaction doesn't have any WAL records.
2066 : // Our goal in this compaction iteration is to avoid creating L1s that, in terms of their key range,
2067 : // cover the hole, but actually don't contain any WAL records for that key range.
2068 : // The reason is that the mere stack of L1s (`count_deltas`) triggers image layer creation (`create_image_layers`).
2069 : // That image layer creation would be useless for a hole range covered by L1s that don't contain any WAL records.
2070 : //
2071 : // The algorithm chooses holes as follows.
2072 : // - Slide a 2-window over the keys in key orde to get the hole range (=distance between two keys).
2073 : // - Filter: min threshold on range length
2074 : // - Rank: by coverage size (=number of image layers required to reconstruct each key in the range for which we have any data)
2075 : //
2076 : // For more details, intuition, and some ASCII art see https://github.com/neondatabase/neon/pull/3597#discussion_r1112704451
2077 : #[derive(PartialEq, Eq)]
2078 : struct Hole {
2079 : key_range: Range<Key>,
2080 : coverage_size: usize,
2081 : }
2082 23 : let holes: Vec<Hole> = {
2083 : use std::cmp::Ordering;
2084 : impl Ord for Hole {
2085 0 : fn cmp(&self, other: &Self) -> Ordering {
2086 0 : self.coverage_size.cmp(&other.coverage_size).reverse()
2087 0 : }
2088 : }
2089 : impl PartialOrd for Hole {
2090 0 : fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2091 0 : Some(self.cmp(other))
2092 0 : }
2093 : }
2094 23 : let max_holes = deltas_to_compact.len();
2095 23 : let min_hole_range = (target_file_size / page_cache::PAGE_SZ as u64) as i128;
2096 23 : let min_hole_coverage_size = 3; // TODO: something more flexible?
2097 : // min-heap (reserve space for one more element added before eviction)
2098 23 : let mut heap: BinaryHeap<Hole> = BinaryHeap::with_capacity(max_holes + 1);
2099 23 : let mut prev: Option<Key> = None;
2100 :
2101 1032019 : for &DeltaEntry { key: next_key, .. } in all_keys.iter() {
2102 1032019 : if let Some(prev_key) = prev {
2103 : // just first fast filter, do not create hole entries for metadata keys. The last hole in the
2104 : // compaction is the gap between data key and metadata keys.
2105 1031996 : if next_key.to_i128() - prev_key.to_i128() >= min_hole_range
2106 288 : && !Key::is_metadata_key(&prev_key)
2107 : {
2108 0 : let key_range = prev_key..next_key;
2109 : // Measuring hole by just subtraction of i128 representation of key range boundaries
2110 : // has not so much sense, because largest holes will corresponds field1/field2 changes.
2111 : // But we are mostly interested to eliminate holes which cause generation of excessive image layers.
2112 : // That is why it is better to measure size of hole as number of covering image layers.
2113 0 : let coverage_size = {
2114 : // TODO: optimize this with copy-on-write layer map.
2115 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
2116 0 : let layers = guard.layer_map()?;
2117 0 : layers.image_coverage(&key_range, l0_last_record_lsn).len()
2118 : };
2119 0 : if coverage_size >= min_hole_coverage_size {
2120 0 : heap.push(Hole {
2121 0 : key_range,
2122 0 : coverage_size,
2123 0 : });
2124 0 : if heap.len() > max_holes {
2125 0 : heap.pop(); // remove smallest hole
2126 0 : }
2127 0 : }
2128 1031996 : }
2129 23 : }
2130 1032019 : prev = Some(next_key.next());
2131 : }
2132 23 : let mut holes = heap.into_vec();
2133 23 : holes.sort_unstable_by_key(|hole| hole.key_range.start);
2134 23 : holes
2135 : };
2136 23 : stats.read_lock_held_compute_holes_micros = stats.read_lock_held_key_sort_micros.till_now();
2137 :
2138 23 : if self.cancel.is_cancelled() {
2139 0 : return Err(CompactionError::new_cancelled());
2140 23 : }
2141 :
2142 23 : stats.read_lock_drop_micros = stats.read_lock_held_compute_holes_micros.till_now();
2143 :
2144 : // This iterator walks through all key-value pairs from all the layers
2145 : // we're compacting, in key, LSN order.
2146 : // If there's both a Value::Image and Value::WalRecord for the same (key,lsn),
2147 : // then the Value::Image is ordered before Value::WalRecord.
2148 23 : let mut all_values_iter = {
2149 23 : let mut deltas = Vec::with_capacity(deltas_to_compact.len());
2150 201 : for l in deltas_to_compact.iter() {
2151 201 : let l = l.get_as_delta(ctx).await.map_err(CompactionError::Other)?;
2152 201 : deltas.push(l);
2153 : }
2154 23 : MergeIterator::create_with_options(
2155 23 : &deltas,
2156 23 : &[],
2157 23 : ctx,
2158 23 : 1024 * 8192, /* 8 MiB buffer per layer iterator */
2159 : 1024,
2160 : )
2161 : };
2162 :
2163 : // This iterator walks through all keys and is needed to calculate size used by each key
2164 23 : let mut all_keys_iter = all_keys
2165 23 : .iter()
2166 1032019 : .map(|DeltaEntry { key, lsn, size, .. }| (*key, *lsn, *size))
2167 1031996 : .coalesce(|mut prev, cur| {
2168 : // Coalesce keys that belong to the same key pair.
2169 : // This ensures that compaction doesn't put them
2170 : // into different layer files.
2171 : // Still limit this by the target file size,
2172 : // so that we keep the size of the files in
2173 : // check.
2174 1031996 : if prev.0 == cur.0 && prev.2 < target_file_size {
2175 14345 : prev.2 += cur.2;
2176 14345 : Ok(prev)
2177 : } else {
2178 1017651 : Err((prev, cur))
2179 : }
2180 1031996 : });
2181 :
2182 : // Merge the contents of all the input delta layers into a new set
2183 : // of delta layers, based on the current partitioning.
2184 : //
2185 : // 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.
2186 : // It's possible that there is a single key with so many page versions that storing all of them in a single layer file
2187 : // would be too large. In that case, we also split on the LSN dimension.
2188 : //
2189 : // LSN
2190 : // ^
2191 : // |
2192 : // | +-----------+ +--+--+--+--+
2193 : // | | | | | | | |
2194 : // | +-----------+ | | | | |
2195 : // | | | | | | | |
2196 : // | +-----------+ ==> | | | | |
2197 : // | | | | | | | |
2198 : // | +-----------+ | | | | |
2199 : // | | | | | | | |
2200 : // | +-----------+ +--+--+--+--+
2201 : // |
2202 : // +--------------> key
2203 : //
2204 : //
2205 : // If one key (X) has a lot of page versions:
2206 : //
2207 : // LSN
2208 : // ^
2209 : // | (X)
2210 : // | +-----------+ +--+--+--+--+
2211 : // | | | | | | | |
2212 : // | +-----------+ | | +--+ |
2213 : // | | | | | | | |
2214 : // | +-----------+ ==> | | | | |
2215 : // | | | | | +--+ |
2216 : // | +-----------+ | | | | |
2217 : // | | | | | | | |
2218 : // | +-----------+ +--+--+--+--+
2219 : // |
2220 : // +--------------> key
2221 : // TODO: this actually divides the layers into fixed-size chunks, not
2222 : // based on the partitioning.
2223 : //
2224 : // TODO: we should also opportunistically materialize and
2225 : // garbage collect what we can.
2226 23 : let mut new_layers = Vec::new();
2227 23 : let mut prev_key: Option<Key> = None;
2228 23 : let mut writer: Option<DeltaLayerWriter> = None;
2229 23 : let mut key_values_total_size = 0u64;
2230 23 : let mut dup_start_lsn: Lsn = Lsn::INVALID; // start LSN of layer containing values of the single key
2231 23 : let mut dup_end_lsn: Lsn = Lsn::INVALID; // end LSN of layer containing values of the single key
2232 23 : let mut next_hole = 0; // index of next hole in holes vector
2233 :
2234 23 : let mut keys = 0;
2235 :
2236 1032042 : while let Some((key, lsn, value)) = all_values_iter
2237 1032042 : .next()
2238 1032042 : .await
2239 1032042 : .map_err(CompactionError::Other)?
2240 : {
2241 1032019 : keys += 1;
2242 :
2243 1032019 : if keys % 32_768 == 0 && self.cancel.is_cancelled() {
2244 : // avoid hitting the cancellation token on every key. in benches, we end up
2245 : // shuffling an order of million keys per layer, this means we'll check it
2246 : // around tens of times per layer.
2247 0 : return Err(CompactionError::new_cancelled());
2248 1032019 : }
2249 :
2250 1032019 : let same_key = prev_key == Some(key);
2251 : // We need to check key boundaries once we reach next key or end of layer with the same key
2252 1032019 : if !same_key || lsn == dup_end_lsn {
2253 1017674 : let mut next_key_size = 0u64;
2254 1017674 : let is_dup_layer = dup_end_lsn.is_valid();
2255 1017674 : dup_start_lsn = Lsn::INVALID;
2256 1017674 : if !same_key {
2257 1017674 : dup_end_lsn = Lsn::INVALID;
2258 1017674 : }
2259 : // Determine size occupied by this key. We stop at next key or when size becomes larger than target_file_size
2260 1017674 : for (next_key, next_lsn, next_size) in all_keys_iter.by_ref() {
2261 1017674 : next_key_size = next_size;
2262 1017674 : if key != next_key {
2263 1017651 : if dup_end_lsn.is_valid() {
2264 0 : // We are writting segment with duplicates:
2265 0 : // place all remaining values of this key in separate segment
2266 0 : dup_start_lsn = dup_end_lsn; // new segments starts where old stops
2267 0 : dup_end_lsn = lsn_range.end; // there are no more values of this key till end of LSN range
2268 1017651 : }
2269 1017651 : break;
2270 23 : }
2271 23 : key_values_total_size += next_size;
2272 : // Check if it is time to split segment: if total keys size is larger than target file size.
2273 : // We need to avoid generation of empty segments if next_size > target_file_size.
2274 23 : if key_values_total_size > target_file_size && lsn != next_lsn {
2275 : // Split key between multiple layers: such layer can contain only single key
2276 0 : dup_start_lsn = if dup_end_lsn.is_valid() {
2277 0 : dup_end_lsn // new segment with duplicates starts where old one stops
2278 : } else {
2279 0 : lsn // start with the first LSN for this key
2280 : };
2281 0 : dup_end_lsn = next_lsn; // upper LSN boundary is exclusive
2282 0 : break;
2283 23 : }
2284 : }
2285 : // handle case when loop reaches last key: in this case dup_end is non-zero but dup_start is not set.
2286 1017674 : if dup_end_lsn.is_valid() && !dup_start_lsn.is_valid() {
2287 0 : dup_start_lsn = dup_end_lsn;
2288 0 : dup_end_lsn = lsn_range.end;
2289 1017674 : }
2290 1017674 : if writer.is_some() {
2291 1017651 : let written_size = writer.as_mut().unwrap().size();
2292 1017651 : let contains_hole =
2293 1017651 : next_hole < holes.len() && key >= holes[next_hole].key_range.end;
2294 : // check if key cause layer overflow or contains hole...
2295 1017651 : if is_dup_layer
2296 1017651 : || dup_end_lsn.is_valid()
2297 1017651 : || written_size + key_values_total_size > target_file_size
2298 1017511 : || contains_hole
2299 : {
2300 : // ... if so, flush previous layer and prepare to write new one
2301 140 : let (desc, path) = writer
2302 140 : .take()
2303 140 : .unwrap()
2304 140 : .finish(prev_key.unwrap().next(), ctx)
2305 140 : .await
2306 140 : .map_err(CompactionError::Other)?;
2307 140 : let new_delta = Layer::finish_creating(self.conf, self, desc, &path)
2308 140 : .map_err(CompactionError::Other)?;
2309 :
2310 140 : new_layers.push(new_delta);
2311 140 : writer = None;
2312 :
2313 140 : if contains_hole {
2314 0 : // skip hole
2315 0 : next_hole += 1;
2316 140 : }
2317 1017511 : }
2318 23 : }
2319 : // Remember size of key value because at next iteration we will access next item
2320 1017674 : key_values_total_size = next_key_size;
2321 14345 : }
2322 1032019 : fail_point!("delta-layer-writer-fail-before-finish", |_| {
2323 0 : Err(CompactionError::Other(anyhow::anyhow!(
2324 0 : "failpoint delta-layer-writer-fail-before-finish"
2325 0 : )))
2326 0 : });
2327 :
2328 1032019 : if !self.shard_identity.is_key_disposable(&key) {
2329 1032019 : if writer.is_none() {
2330 163 : if self.cancel.is_cancelled() {
2331 : // to be somewhat responsive to cancellation, check for each new layer
2332 0 : return Err(CompactionError::new_cancelled());
2333 163 : }
2334 : // Create writer if not initiaized yet
2335 163 : writer = Some(
2336 163 : DeltaLayerWriter::new(
2337 163 : self.conf,
2338 163 : self.timeline_id,
2339 163 : self.tenant_shard_id,
2340 163 : key,
2341 163 : if dup_end_lsn.is_valid() {
2342 : // this is a layer containing slice of values of the same key
2343 0 : debug!("Create new dup layer {}..{}", dup_start_lsn, dup_end_lsn);
2344 0 : dup_start_lsn..dup_end_lsn
2345 : } else {
2346 163 : debug!("Create new layer {}..{}", lsn_range.start, lsn_range.end);
2347 163 : lsn_range.clone()
2348 : },
2349 163 : &self.gate,
2350 163 : self.cancel.clone(),
2351 163 : ctx,
2352 : )
2353 163 : .await
2354 163 : .map_err(CompactionError::Other)?,
2355 : );
2356 :
2357 163 : keys = 0;
2358 1031856 : }
2359 :
2360 1032019 : writer
2361 1032019 : .as_mut()
2362 1032019 : .unwrap()
2363 1032019 : .put_value(key, lsn, value, ctx)
2364 1032019 : .await?;
2365 : } else {
2366 0 : let owner = self.shard_identity.get_shard_number(&key);
2367 :
2368 : // This happens after a shard split, when we're compacting an L0 created by our parent shard
2369 0 : debug!("dropping key {key} during compaction (it belongs on shard {owner})");
2370 : }
2371 :
2372 1032019 : if !new_layers.is_empty() {
2373 9893 : fail_point!("after-timeline-compacted-first-L1");
2374 1022126 : }
2375 :
2376 1032019 : prev_key = Some(key);
2377 : }
2378 23 : if let Some(writer) = writer {
2379 23 : let (desc, path) = writer
2380 23 : .finish(prev_key.unwrap().next(), ctx)
2381 23 : .await
2382 23 : .map_err(CompactionError::Other)?;
2383 23 : let new_delta = Layer::finish_creating(self.conf, self, desc, &path)
2384 23 : .map_err(CompactionError::Other)?;
2385 23 : new_layers.push(new_delta);
2386 0 : }
2387 :
2388 : // Sync layers
2389 23 : if !new_layers.is_empty() {
2390 : // Print a warning if the created layer is larger than double the target size
2391 : // Add two pages for potential overhead. This should in theory be already
2392 : // accounted for in the target calculation, but for very small targets,
2393 : // we still might easily hit the limit otherwise.
2394 23 : let warn_limit = target_file_size * 2 + page_cache::PAGE_SZ as u64 * 2;
2395 163 : for layer in new_layers.iter() {
2396 163 : if layer.layer_desc().file_size > warn_limit {
2397 0 : warn!(
2398 : %layer,
2399 0 : "created delta file of size {} larger than double of target of {target_file_size}", layer.layer_desc().file_size
2400 : );
2401 163 : }
2402 : }
2403 :
2404 : // The writer.finish() above already did the fsync of the inodes.
2405 : // We just need to fsync the directory in which these inodes are linked,
2406 : // which we know to be the timeline directory.
2407 : //
2408 : // We use fatal_err() below because the after writer.finish() returns with success,
2409 : // the in-memory state of the filesystem already has the layer file in its final place,
2410 : // and subsequent pageserver code could think it's durable while it really isn't.
2411 23 : let timeline_dir = VirtualFile::open(
2412 23 : &self
2413 23 : .conf
2414 23 : .timeline_path(&self.tenant_shard_id, &self.timeline_id),
2415 23 : ctx,
2416 23 : )
2417 23 : .await
2418 23 : .fatal_err("VirtualFile::open for timeline dir fsync");
2419 23 : timeline_dir
2420 23 : .sync_all()
2421 23 : .await
2422 23 : .fatal_err("VirtualFile::sync_all timeline dir");
2423 0 : }
2424 :
2425 23 : stats.write_layer_files_micros = stats.read_lock_drop_micros.till_now();
2426 23 : stats.new_deltas_count = Some(new_layers.len());
2427 163 : stats.new_deltas_size = Some(new_layers.iter().map(|l| l.layer_desc().file_size).sum());
2428 :
2429 23 : match TryInto::<CompactLevel0Phase1Stats>::try_into(stats)
2430 23 : .and_then(|stats| serde_json::to_string(&stats).context("serde_json::to_string"))
2431 : {
2432 23 : Ok(stats_json) => {
2433 23 : info!(
2434 0 : stats_json = stats_json.as_str(),
2435 0 : "compact_level0_phase1 stats available"
2436 : )
2437 : }
2438 0 : Err(e) => {
2439 0 : warn!("compact_level0_phase1 stats failed to serialize: {:#}", e);
2440 : }
2441 : }
2442 :
2443 : // Without this, rustc complains about deltas_to_compact still
2444 : // being borrowed when we `.into_iter()` below.
2445 23 : drop(all_values_iter);
2446 :
2447 : Ok(CompactLevel0Phase1Result {
2448 23 : new_layers,
2449 23 : deltas_to_compact: deltas_to_compact
2450 23 : .into_iter()
2451 201 : .map(|x| x.drop_eviction_guard())
2452 23 : .collect::<Vec<_>>(),
2453 23 : outcome: if fully_compacted {
2454 23 : CompactionOutcome::Done
2455 : } else {
2456 0 : CompactionOutcome::Pending
2457 : },
2458 : })
2459 192 : }
2460 : }
2461 :
2462 : #[derive(Default)]
2463 : struct CompactLevel0Phase1Result {
2464 : new_layers: Vec<ResidentLayer>,
2465 : deltas_to_compact: Vec<Layer>,
2466 : // Whether we have included all L0 layers, or selected only part of them due to the
2467 : // L0 compaction size limit.
2468 : outcome: CompactionOutcome,
2469 : }
2470 :
2471 : #[derive(Default)]
2472 : struct CompactLevel0Phase1StatsBuilder {
2473 : version: Option<u64>,
2474 : tenant_id: Option<TenantShardId>,
2475 : timeline_id: Option<TimelineId>,
2476 : read_lock_acquisition_micros: DurationRecorder,
2477 : read_lock_held_key_sort_micros: DurationRecorder,
2478 : compaction_prerequisites_micros: DurationRecorder,
2479 : read_lock_held_compute_holes_micros: DurationRecorder,
2480 : read_lock_drop_micros: DurationRecorder,
2481 : write_layer_files_micros: DurationRecorder,
2482 : level0_deltas_count: Option<usize>,
2483 : new_deltas_count: Option<usize>,
2484 : new_deltas_size: Option<u64>,
2485 : }
2486 :
2487 : #[derive(serde::Serialize)]
2488 : struct CompactLevel0Phase1Stats {
2489 : version: u64,
2490 : tenant_id: TenantShardId,
2491 : timeline_id: TimelineId,
2492 : read_lock_acquisition_micros: RecordedDuration,
2493 : read_lock_held_key_sort_micros: RecordedDuration,
2494 : compaction_prerequisites_micros: RecordedDuration,
2495 : read_lock_held_compute_holes_micros: RecordedDuration,
2496 : read_lock_drop_micros: RecordedDuration,
2497 : write_layer_files_micros: RecordedDuration,
2498 : level0_deltas_count: usize,
2499 : new_deltas_count: usize,
2500 : new_deltas_size: u64,
2501 : }
2502 :
2503 : impl TryFrom<CompactLevel0Phase1StatsBuilder> for CompactLevel0Phase1Stats {
2504 : type Error = anyhow::Error;
2505 :
2506 23 : fn try_from(value: CompactLevel0Phase1StatsBuilder) -> Result<Self, Self::Error> {
2507 : Ok(Self {
2508 23 : version: value.version.ok_or_else(|| anyhow!("version not set"))?,
2509 23 : tenant_id: value
2510 23 : .tenant_id
2511 23 : .ok_or_else(|| anyhow!("tenant_id not set"))?,
2512 23 : timeline_id: value
2513 23 : .timeline_id
2514 23 : .ok_or_else(|| anyhow!("timeline_id not set"))?,
2515 23 : read_lock_acquisition_micros: value
2516 23 : .read_lock_acquisition_micros
2517 23 : .into_recorded()
2518 23 : .ok_or_else(|| anyhow!("read_lock_acquisition_micros not set"))?,
2519 23 : read_lock_held_key_sort_micros: value
2520 23 : .read_lock_held_key_sort_micros
2521 23 : .into_recorded()
2522 23 : .ok_or_else(|| anyhow!("read_lock_held_key_sort_micros not set"))?,
2523 23 : compaction_prerequisites_micros: value
2524 23 : .compaction_prerequisites_micros
2525 23 : .into_recorded()
2526 23 : .ok_or_else(|| anyhow!("read_lock_held_prerequisites_micros not set"))?,
2527 23 : read_lock_held_compute_holes_micros: value
2528 23 : .read_lock_held_compute_holes_micros
2529 23 : .into_recorded()
2530 23 : .ok_or_else(|| anyhow!("read_lock_held_compute_holes_micros not set"))?,
2531 23 : read_lock_drop_micros: value
2532 23 : .read_lock_drop_micros
2533 23 : .into_recorded()
2534 23 : .ok_or_else(|| anyhow!("read_lock_drop_micros not set"))?,
2535 23 : write_layer_files_micros: value
2536 23 : .write_layer_files_micros
2537 23 : .into_recorded()
2538 23 : .ok_or_else(|| anyhow!("write_layer_files_micros not set"))?,
2539 23 : level0_deltas_count: value
2540 23 : .level0_deltas_count
2541 23 : .ok_or_else(|| anyhow!("level0_deltas_count not set"))?,
2542 23 : new_deltas_count: value
2543 23 : .new_deltas_count
2544 23 : .ok_or_else(|| anyhow!("new_deltas_count not set"))?,
2545 23 : new_deltas_size: value
2546 23 : .new_deltas_size
2547 23 : .ok_or_else(|| anyhow!("new_deltas_size not set"))?,
2548 : })
2549 23 : }
2550 : }
2551 :
2552 : impl Timeline {
2553 : /// Entry point for new tiered compaction algorithm.
2554 : ///
2555 : /// All the real work is in the implementation in the pageserver_compaction
2556 : /// crate. The code here would apply to any algorithm implemented by the
2557 : /// same interface, but tiered is the only one at the moment.
2558 : ///
2559 : /// TODO: cancellation
2560 0 : pub(crate) async fn compact_tiered(
2561 0 : self: &Arc<Self>,
2562 0 : _cancel: &CancellationToken,
2563 0 : ctx: &RequestContext,
2564 0 : ) -> Result<(), CompactionError> {
2565 0 : let fanout = self.get_compaction_threshold() as u64;
2566 0 : let target_file_size = self.get_checkpoint_distance();
2567 :
2568 : // Find the top of the historical layers
2569 0 : let end_lsn = {
2570 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
2571 0 : let layers = guard.layer_map()?;
2572 :
2573 0 : let l0_deltas = layers.level0_deltas();
2574 :
2575 : // As an optimization, if we find that there are too few L0 layers,
2576 : // bail out early. We know that the compaction algorithm would do
2577 : // nothing in that case.
2578 0 : if l0_deltas.len() < fanout as usize {
2579 : // doesn't need compacting
2580 0 : return Ok(());
2581 0 : }
2582 0 : l0_deltas.iter().map(|l| l.lsn_range.end).max().unwrap()
2583 : };
2584 :
2585 : // Is the timeline being deleted?
2586 0 : if self.is_stopping() {
2587 0 : trace!("Dropping out of compaction on timeline shutdown");
2588 0 : return Err(CompactionError::new_cancelled());
2589 0 : }
2590 :
2591 0 : let (dense_ks, _sparse_ks) = self
2592 0 : .collect_keyspace(end_lsn, ctx)
2593 0 : .await
2594 0 : .map_err(CompactionError::from_collect_keyspace)?;
2595 : // TODO(chi): ignore sparse_keyspace for now, compact it in the future.
2596 0 : let mut adaptor = TimelineAdaptor::new(self, (end_lsn, dense_ks));
2597 :
2598 0 : pageserver_compaction::compact_tiered::compact_tiered(
2599 0 : &mut adaptor,
2600 0 : end_lsn,
2601 0 : target_file_size,
2602 0 : fanout,
2603 0 : ctx,
2604 0 : )
2605 0 : .await
2606 : // TODO: compact_tiered needs to return CompactionError
2607 0 : .map_err(CompactionError::Other)?;
2608 :
2609 0 : adaptor.flush_updates().await?;
2610 0 : Ok(())
2611 0 : }
2612 :
2613 : /// Take a list of images and deltas, produce images and deltas according to GC horizon and retain_lsns.
2614 : ///
2615 : /// It takes a key, the values of the key within the compaction process, a GC horizon, and all retain_lsns below the horizon.
2616 : /// For now, it requires the `accumulated_values` contains the full history of the key (i.e., the key with the lowest LSN is
2617 : /// an image or a WAL not requiring a base image). This restriction will be removed once we implement gc-compaction on branch.
2618 : ///
2619 : /// The function returns the deltas and the base image that need to be placed at each of the retain LSN. For example, we have:
2620 : ///
2621 : /// A@0x10, +B@0x20, +C@0x30, +D@0x40, +E@0x50, +F@0x60
2622 : /// horizon = 0x50, retain_lsn = 0x20, 0x40, delta_threshold=3
2623 : ///
2624 : /// The function will produce:
2625 : ///
2626 : /// ```plain
2627 : /// 0x20(retain_lsn) -> img=AB@0x20 always produce a single image below the lowest retain LSN
2628 : /// 0x40(retain_lsn) -> deltas=[+C@0x30, +D@0x40] two deltas since the last base image, keeping the deltas
2629 : /// 0x50(horizon) -> deltas=[ABCDE@0x50] three deltas since the last base image, generate an image but put it in the delta
2630 : /// above_horizon -> deltas=[+F@0x60] full history above the horizon
2631 : /// ```
2632 : ///
2633 : /// Note that `accumulated_values` must be sorted by LSN and should belong to a single key.
2634 : #[allow(clippy::too_many_arguments)]
2635 324 : pub(crate) async fn generate_key_retention(
2636 324 : self: &Arc<Timeline>,
2637 324 : key: Key,
2638 324 : full_history: &[(Key, Lsn, Value)],
2639 324 : horizon: Lsn,
2640 324 : retain_lsn_below_horizon: &[Lsn],
2641 324 : delta_threshold_cnt: usize,
2642 324 : base_img_from_ancestor: Option<(Key, Lsn, Bytes)>,
2643 324 : verification: bool,
2644 324 : ) -> anyhow::Result<KeyHistoryRetention> {
2645 : // Pre-checks for the invariants
2646 :
2647 324 : let debug_mode = cfg!(debug_assertions) || cfg!(feature = "testing");
2648 :
2649 324 : if debug_mode {
2650 786 : for (log_key, _, _) in full_history {
2651 462 : assert_eq!(log_key, &key, "mismatched key");
2652 : }
2653 324 : for i in 1..full_history.len() {
2654 138 : assert!(full_history[i - 1].1 <= full_history[i].1, "unordered LSN");
2655 138 : if full_history[i - 1].1 == full_history[i].1 {
2656 0 : assert!(
2657 0 : matches!(full_history[i - 1].2, Value::Image(_)),
2658 0 : "unordered delta/image, or duplicated delta"
2659 : );
2660 138 : }
2661 : }
2662 : // There was an assertion for no base image that checks if the first
2663 : // record in the history is `will_init` before, but it was removed.
2664 : // This is explained in the test cases for generate_key_retention.
2665 : // Search "incomplete history" for more information.
2666 714 : for lsn in retain_lsn_below_horizon {
2667 390 : assert!(lsn < &horizon, "retain lsn must be below horizon")
2668 : }
2669 324 : for i in 1..retain_lsn_below_horizon.len() {
2670 178 : assert!(
2671 178 : retain_lsn_below_horizon[i - 1] <= retain_lsn_below_horizon[i],
2672 0 : "unordered LSN"
2673 : );
2674 : }
2675 0 : }
2676 324 : let has_ancestor = base_img_from_ancestor.is_some();
2677 : // Step 1: split history into len(retain_lsn_below_horizon) + 2 buckets, where the last bucket is for all deltas above the horizon,
2678 : // and the second-to-last bucket is for the horizon. Each bucket contains lsn_last_bucket < deltas <= lsn_this_bucket.
2679 324 : let (mut split_history, lsn_split_points) = {
2680 324 : let mut split_history = Vec::new();
2681 324 : split_history.resize_with(retain_lsn_below_horizon.len() + 2, Vec::new);
2682 324 : let mut lsn_split_points = Vec::with_capacity(retain_lsn_below_horizon.len() + 1);
2683 714 : for lsn in retain_lsn_below_horizon {
2684 390 : lsn_split_points.push(*lsn);
2685 390 : }
2686 324 : lsn_split_points.push(horizon);
2687 324 : let mut current_idx = 0;
2688 786 : for item @ (_, lsn, _) in full_history {
2689 584 : while current_idx < lsn_split_points.len() && *lsn > lsn_split_points[current_idx] {
2690 122 : current_idx += 1;
2691 122 : }
2692 462 : split_history[current_idx].push(item);
2693 : }
2694 324 : (split_history, lsn_split_points)
2695 : };
2696 : // Step 2: filter out duplicated records due to the k-merge of image/delta layers
2697 1362 : for split_for_lsn in &mut split_history {
2698 1038 : let mut prev_lsn = None;
2699 1038 : let mut new_split_for_lsn = Vec::with_capacity(split_for_lsn.len());
2700 1038 : for record @ (_, lsn, _) in std::mem::take(split_for_lsn) {
2701 462 : if let Some(prev_lsn) = &prev_lsn {
2702 62 : if *prev_lsn == lsn {
2703 : // The case that we have an LSN with both data from the delta layer and the image layer. As
2704 : // `ValueWrapper` ensures that an image is ordered before a delta at the same LSN, we simply
2705 : // drop this delta and keep the image.
2706 : //
2707 : // For example, we have delta layer key1@0x10, key1@0x20, and image layer key1@0x10, we will
2708 : // keep the image for key1@0x10 and the delta for key1@0x20. key1@0x10 delta will be simply
2709 : // dropped.
2710 : //
2711 : // TODO: in case we have both delta + images for a given LSN and it does not exceed the delta
2712 : // threshold, we could have kept delta instead to save space. This is an optimization for the future.
2713 0 : continue;
2714 62 : }
2715 400 : }
2716 462 : prev_lsn = Some(lsn);
2717 462 : new_split_for_lsn.push(record);
2718 : }
2719 1038 : *split_for_lsn = new_split_for_lsn;
2720 : }
2721 : // Step 3: generate images when necessary
2722 324 : let mut retention = Vec::with_capacity(split_history.len());
2723 324 : let mut records_since_last_image = 0;
2724 324 : let batch_cnt = split_history.len();
2725 324 : assert!(
2726 324 : batch_cnt >= 2,
2727 0 : "should have at least below + above horizon batches"
2728 : );
2729 324 : let mut replay_history: Vec<(Key, Lsn, Value)> = Vec::new();
2730 324 : if let Some((key, lsn, ref img)) = base_img_from_ancestor {
2731 21 : replay_history.push((key, lsn, Value::Image(img.clone())));
2732 303 : }
2733 :
2734 : /// Generate debug information for the replay history
2735 0 : fn generate_history_trace(replay_history: &[(Key, Lsn, Value)]) -> String {
2736 : use std::fmt::Write;
2737 0 : let mut output = String::new();
2738 0 : if let Some((key, _, _)) = replay_history.first() {
2739 0 : write!(output, "key={key} ").unwrap();
2740 0 : let mut cnt = 0;
2741 0 : for (_, lsn, val) in replay_history {
2742 0 : if val.is_image() {
2743 0 : write!(output, "i@{lsn} ").unwrap();
2744 0 : } else if val.will_init() {
2745 0 : write!(output, "di@{lsn} ").unwrap();
2746 0 : } else {
2747 0 : write!(output, "d@{lsn} ").unwrap();
2748 0 : }
2749 0 : cnt += 1;
2750 0 : if cnt >= 128 {
2751 0 : write!(output, "... and more").unwrap();
2752 0 : break;
2753 0 : }
2754 : }
2755 0 : } else {
2756 0 : write!(output, "<no history>").unwrap();
2757 0 : }
2758 0 : output
2759 0 : }
2760 :
2761 0 : fn generate_debug_trace(
2762 0 : replay_history: Option<&[(Key, Lsn, Value)]>,
2763 0 : full_history: &[(Key, Lsn, Value)],
2764 0 : lsns: &[Lsn],
2765 0 : horizon: Lsn,
2766 0 : ) -> String {
2767 : use std::fmt::Write;
2768 0 : let mut output = String::new();
2769 0 : if let Some(replay_history) = replay_history {
2770 0 : writeln!(
2771 0 : output,
2772 0 : "replay_history: {}",
2773 0 : generate_history_trace(replay_history)
2774 0 : )
2775 0 : .unwrap();
2776 0 : } else {
2777 0 : writeln!(output, "replay_history: <disabled>",).unwrap();
2778 0 : }
2779 0 : writeln!(
2780 0 : output,
2781 0 : "full_history: {}",
2782 0 : generate_history_trace(full_history)
2783 : )
2784 0 : .unwrap();
2785 0 : writeln!(
2786 0 : output,
2787 0 : "when processing: [{}] horizon={}",
2788 0 : lsns.iter().map(|l| format!("{l}")).join(","),
2789 : horizon
2790 : )
2791 0 : .unwrap();
2792 0 : output
2793 0 : }
2794 :
2795 324 : let mut key_exists = false;
2796 1037 : for (i, split_for_lsn) in split_history.into_iter().enumerate() {
2797 : // TODO: there could be image keys inside the splits, and we can compute records_since_last_image accordingly.
2798 1037 : records_since_last_image += split_for_lsn.len();
2799 : // Whether to produce an image into the final layer files
2800 1037 : let produce_image = if i == 0 && !has_ancestor {
2801 : // We always generate images for the first batch (below horizon / lowest retain_lsn)
2802 303 : true
2803 734 : } else if i == batch_cnt - 1 {
2804 : // Do not generate images for the last batch (above horizon)
2805 323 : false
2806 411 : } else if records_since_last_image == 0 {
2807 322 : false
2808 89 : } else if records_since_last_image >= delta_threshold_cnt {
2809 : // Generate images when there are too many records
2810 3 : true
2811 : } else {
2812 86 : false
2813 : };
2814 1037 : replay_history.extend(split_for_lsn.iter().map(|x| (*x).clone()));
2815 : // Only retain the items after the last image record
2816 1277 : for idx in (0..replay_history.len()).rev() {
2817 1277 : if replay_history[idx].2.will_init() {
2818 1037 : replay_history = replay_history[idx..].to_vec();
2819 1037 : break;
2820 240 : }
2821 : }
2822 1037 : if replay_history.is_empty() && !key_exists {
2823 : // The key does not exist at earlier LSN, we can skip this iteration.
2824 0 : retention.push(Vec::new());
2825 0 : continue;
2826 1037 : } else {
2827 1037 : key_exists = true;
2828 1037 : }
2829 1037 : let Some((_, _, val)) = replay_history.first() else {
2830 0 : unreachable!("replay history should not be empty once it exists")
2831 : };
2832 1037 : if !val.will_init() {
2833 0 : return Err(anyhow::anyhow!("invalid history, no base image")).with_context(|| {
2834 0 : generate_debug_trace(
2835 0 : Some(&replay_history),
2836 0 : full_history,
2837 0 : retain_lsn_below_horizon,
2838 0 : horizon,
2839 : )
2840 0 : });
2841 1037 : }
2842 : // Whether to reconstruct the image. In debug mode, we will generate an image
2843 : // at every retain_lsn to ensure data is not corrupted, but we won't put the
2844 : // image into the final layer.
2845 1037 : let img_and_lsn = if produce_image {
2846 306 : records_since_last_image = 0;
2847 306 : let replay_history_for_debug = if debug_mode {
2848 306 : Some(replay_history.clone())
2849 : } else {
2850 0 : None
2851 : };
2852 306 : let replay_history_for_debug_ref = replay_history_for_debug.as_deref();
2853 306 : let history = std::mem::take(&mut replay_history);
2854 306 : let mut img = None;
2855 306 : let mut records = Vec::with_capacity(history.len());
2856 306 : if let (_, lsn, Value::Image(val)) = history.first().as_ref().unwrap() {
2857 295 : img = Some((*lsn, val.clone()));
2858 295 : for (_, lsn, val) in history.into_iter().skip(1) {
2859 20 : let Value::WalRecord(rec) = val else {
2860 0 : return Err(anyhow::anyhow!(
2861 0 : "invalid record, first record is image, expect walrecords"
2862 0 : ))
2863 0 : .with_context(|| {
2864 0 : generate_debug_trace(
2865 0 : replay_history_for_debug_ref,
2866 0 : full_history,
2867 0 : retain_lsn_below_horizon,
2868 0 : horizon,
2869 : )
2870 0 : });
2871 : };
2872 20 : records.push((lsn, rec));
2873 : }
2874 : } else {
2875 18 : for (_, lsn, val) in history.into_iter() {
2876 18 : let Value::WalRecord(rec) = val else {
2877 0 : return Err(anyhow::anyhow!("invalid record, first record is walrecord, expect rest are walrecord"))
2878 0 : .with_context(|| generate_debug_trace(
2879 0 : replay_history_for_debug_ref,
2880 0 : full_history,
2881 0 : retain_lsn_below_horizon,
2882 0 : horizon,
2883 : ));
2884 : };
2885 18 : records.push((lsn, rec));
2886 : }
2887 : }
2888 : // WAL redo requires records in the reverse LSN order
2889 306 : records.reverse();
2890 306 : let state = ValueReconstructState { img, records };
2891 : // last batch does not generate image so i is always in range, unless we force generate
2892 : // an image during testing
2893 306 : let request_lsn = if i >= lsn_split_points.len() {
2894 0 : Lsn::MAX
2895 : } else {
2896 306 : lsn_split_points[i]
2897 : };
2898 306 : let img = self
2899 306 : .reconstruct_value(key, request_lsn, state, RedoAttemptType::GcCompaction)
2900 306 : .await?;
2901 305 : Some((request_lsn, img))
2902 : } else {
2903 731 : None
2904 : };
2905 1036 : if produce_image {
2906 305 : let (request_lsn, img) = img_and_lsn.unwrap();
2907 305 : replay_history.push((key, request_lsn, Value::Image(img.clone())));
2908 305 : retention.push(vec![(request_lsn, Value::Image(img))]);
2909 305 : } else {
2910 731 : let deltas = split_for_lsn
2911 731 : .iter()
2912 731 : .map(|(_, lsn, value)| (*lsn, value.clone()))
2913 731 : .collect_vec();
2914 731 : retention.push(deltas);
2915 : }
2916 : }
2917 323 : let mut result = Vec::with_capacity(retention.len());
2918 323 : assert_eq!(retention.len(), lsn_split_points.len() + 1);
2919 1036 : for (idx, logs) in retention.into_iter().enumerate() {
2920 1036 : if idx == lsn_split_points.len() {
2921 323 : let retention = KeyHistoryRetention {
2922 323 : below_horizon: result,
2923 323 : above_horizon: KeyLogAtLsn(logs),
2924 323 : };
2925 323 : if verification {
2926 323 : retention
2927 323 : .verify(key, &base_img_from_ancestor, full_history, self)
2928 323 : .await?;
2929 0 : }
2930 323 : return Ok(retention);
2931 713 : } else {
2932 713 : result.push((lsn_split_points[idx], KeyLogAtLsn(logs)));
2933 713 : }
2934 : }
2935 0 : unreachable!("key retention is empty")
2936 324 : }
2937 :
2938 : /// Check how much space is left on the disk
2939 27 : async fn check_available_space(self: &Arc<Self>) -> anyhow::Result<u64> {
2940 27 : let tenants_dir = self.conf.tenants_path();
2941 :
2942 27 : let stat = Statvfs::get(&tenants_dir, None)
2943 27 : .context("statvfs failed, presumably directory got unlinked")?;
2944 :
2945 27 : let (avail_bytes, _) = stat.get_avail_total_bytes();
2946 :
2947 27 : Ok(avail_bytes)
2948 27 : }
2949 :
2950 : /// Check if the compaction can proceed safely without running out of space. We assume the size
2951 : /// upper bound of the produced files of a compaction job is the same as all layers involved in
2952 : /// the compaction. Therefore, we need `2 * layers_to_be_compacted_size` at least to do a
2953 : /// compaction.
2954 27 : async fn check_compaction_space(
2955 27 : self: &Arc<Self>,
2956 27 : layer_selection: &[Layer],
2957 27 : ) -> Result<(), CompactionError> {
2958 27 : let available_space = self
2959 27 : .check_available_space()
2960 27 : .await
2961 27 : .map_err(CompactionError::Other)?;
2962 27 : let mut remote_layer_size = 0;
2963 27 : let mut all_layer_size = 0;
2964 106 : for layer in layer_selection {
2965 79 : let needs_download = layer
2966 79 : .needs_download()
2967 79 : .await
2968 79 : .context("failed to check if layer needs download")
2969 79 : .map_err(CompactionError::Other)?;
2970 79 : if needs_download.is_some() {
2971 0 : remote_layer_size += layer.layer_desc().file_size;
2972 79 : }
2973 79 : all_layer_size += layer.layer_desc().file_size;
2974 : }
2975 27 : let allocated_space = (available_space as f64 * 0.8) as u64; /* reserve 20% space for other tasks */
2976 27 : if all_layer_size /* space needed for newly-generated file */ + remote_layer_size /* space for downloading layers */ > allocated_space
2977 : {
2978 0 : return Err(CompactionError::Other(anyhow!(
2979 0 : "not enough space for compaction: available_space={}, allocated_space={}, all_layer_size={}, remote_layer_size={}, required_space={}",
2980 0 : available_space,
2981 0 : allocated_space,
2982 0 : all_layer_size,
2983 0 : remote_layer_size,
2984 0 : all_layer_size + remote_layer_size
2985 0 : )));
2986 27 : }
2987 27 : Ok(())
2988 27 : }
2989 :
2990 : /// Check to bail out of gc compaction early if it would use too much memory.
2991 27 : async fn check_memory_usage(
2992 27 : self: &Arc<Self>,
2993 27 : layer_selection: &[Layer],
2994 27 : ) -> Result<(), CompactionError> {
2995 27 : let mut estimated_memory_usage_mb = 0.0;
2996 27 : let mut num_image_layers = 0;
2997 27 : let mut num_delta_layers = 0;
2998 27 : let target_layer_size_bytes = 256 * 1024 * 1024;
2999 106 : for layer in layer_selection {
3000 79 : let layer_desc = layer.layer_desc();
3001 79 : if layer_desc.is_delta() {
3002 44 : // Delta layers at most have 1MB buffer; 3x to make it safe (there're deltas as large as 16KB).
3003 44 : // Scale it by target_layer_size_bytes so that tests can pass (some tests, e.g., `test_pageserver_gc_compaction_preempt
3004 44 : // use 3MB layer size and we need to account for that).
3005 44 : estimated_memory_usage_mb +=
3006 44 : 3.0 * (layer_desc.file_size / target_layer_size_bytes) as f64;
3007 44 : num_delta_layers += 1;
3008 44 : } else {
3009 35 : // Image layers at most have 1MB buffer but it might be compressed; assume 5x compression ratio.
3010 35 : estimated_memory_usage_mb +=
3011 35 : 5.0 * (layer_desc.file_size / target_layer_size_bytes) as f64;
3012 35 : num_image_layers += 1;
3013 35 : }
3014 : }
3015 27 : if estimated_memory_usage_mb > 1024.0 {
3016 0 : return Err(CompactionError::Other(anyhow!(
3017 0 : "estimated memory usage is too high: {}MB, giving up compaction; num_image_layers={}, num_delta_layers={}",
3018 0 : estimated_memory_usage_mb,
3019 0 : num_image_layers,
3020 0 : num_delta_layers
3021 0 : )));
3022 27 : }
3023 27 : Ok(())
3024 27 : }
3025 :
3026 : /// Get a watermark for gc-compaction, that is the lowest LSN that we can use as the `gc_horizon` for
3027 : /// the compaction algorithm. It is min(space_cutoff, time_cutoff, latest_gc_cutoff, standby_horizon).
3028 : /// Leases and retain_lsns are considered in the gc-compaction job itself so we don't need to account for them
3029 : /// here.
3030 28 : pub(crate) fn get_gc_compaction_watermark(self: &Arc<Self>) -> Lsn {
3031 28 : let gc_cutoff_lsn = {
3032 28 : let gc_info = self.gc_info.read().unwrap();
3033 28 : gc_info.min_cutoff()
3034 : };
3035 :
3036 : // TODO: standby horizon should use leases so we don't really need to consider it here.
3037 : // let watermark = watermark.min(self.standby_horizon.load());
3038 :
3039 : // TODO: ensure the child branches will not use anything below the watermark, or consider
3040 : // them when computing the watermark.
3041 28 : gc_cutoff_lsn.min(*self.get_applied_gc_cutoff_lsn())
3042 28 : }
3043 :
3044 : /// 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.
3045 : /// The function returns a list of compaction jobs that can be executed separately. If the upper bound of the compact LSN
3046 : /// range is not specified, we will use the latest gc_cutoff as the upper bound, so that all jobs in the jobset acts
3047 : /// like a full compaction of the specified keyspace.
3048 0 : pub(crate) async fn gc_compaction_split_jobs(
3049 0 : self: &Arc<Self>,
3050 0 : job: GcCompactJob,
3051 0 : sub_compaction_max_job_size_mb: Option<u64>,
3052 0 : ) -> Result<Vec<GcCompactJob>, CompactionError> {
3053 0 : let compact_below_lsn = if job.compact_lsn_range.end != Lsn::MAX {
3054 0 : job.compact_lsn_range.end
3055 : } else {
3056 0 : self.get_gc_compaction_watermark()
3057 : };
3058 :
3059 0 : if compact_below_lsn == Lsn::INVALID {
3060 0 : tracing::warn!(
3061 0 : "no layers to compact with gc: gc_cutoff not generated yet, skipping gc bottom-most compaction"
3062 : );
3063 0 : return Ok(vec![]);
3064 0 : }
3065 :
3066 : // Split compaction job to about 4GB each
3067 : const GC_COMPACT_MAX_SIZE_MB: u64 = 4 * 1024;
3068 0 : let sub_compaction_max_job_size_mb =
3069 0 : sub_compaction_max_job_size_mb.unwrap_or(GC_COMPACT_MAX_SIZE_MB);
3070 :
3071 0 : let mut compact_jobs = Vec::<GcCompactJob>::new();
3072 : // For now, we simply use the key partitioning information; we should do a more fine-grained partitioning
3073 : // by estimating the amount of files read for a compaction job. We should also partition on LSN.
3074 0 : let ((dense_ks, sparse_ks), _) = self.partitioning.read().as_ref().clone();
3075 : // Truncate the key range to be within user specified compaction range.
3076 0 : fn truncate_to(
3077 0 : source_start: &Key,
3078 0 : source_end: &Key,
3079 0 : target_start: &Key,
3080 0 : target_end: &Key,
3081 0 : ) -> Option<(Key, Key)> {
3082 0 : let start = source_start.max(target_start);
3083 0 : let end = source_end.min(target_end);
3084 0 : if start < end {
3085 0 : Some((*start, *end))
3086 : } else {
3087 0 : None
3088 : }
3089 0 : }
3090 0 : let mut split_key_ranges = Vec::new();
3091 0 : let ranges = dense_ks
3092 0 : .parts
3093 0 : .iter()
3094 0 : .map(|partition| partition.ranges.iter())
3095 0 : .chain(sparse_ks.parts.iter().map(|x| x.0.ranges.iter()))
3096 0 : .flatten()
3097 0 : .cloned()
3098 0 : .collect_vec();
3099 0 : for range in ranges.iter() {
3100 0 : let Some((start, end)) = truncate_to(
3101 0 : &range.start,
3102 0 : &range.end,
3103 0 : &job.compact_key_range.start,
3104 0 : &job.compact_key_range.end,
3105 0 : ) else {
3106 0 : continue;
3107 : };
3108 0 : split_key_ranges.push((start, end));
3109 : }
3110 0 : split_key_ranges.sort();
3111 0 : let all_layers = {
3112 0 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
3113 0 : let layer_map = guard.layer_map()?;
3114 0 : layer_map.iter_historic_layers().collect_vec()
3115 : };
3116 0 : let mut current_start = None;
3117 0 : let ranges_num = split_key_ranges.len();
3118 0 : for (idx, (start, end)) in split_key_ranges.into_iter().enumerate() {
3119 0 : if current_start.is_none() {
3120 0 : current_start = Some(start);
3121 0 : }
3122 0 : let start = current_start.unwrap();
3123 0 : if start >= end {
3124 : // We have already processed this partition.
3125 0 : continue;
3126 0 : }
3127 0 : let overlapping_layers = {
3128 0 : let mut desc = Vec::new();
3129 0 : for layer in all_layers.iter() {
3130 0 : if overlaps_with(&layer.get_key_range(), &(start..end))
3131 0 : && layer.get_lsn_range().start <= compact_below_lsn
3132 0 : {
3133 0 : desc.push(layer.clone());
3134 0 : }
3135 : }
3136 0 : desc
3137 : };
3138 0 : let total_size = overlapping_layers.iter().map(|x| x.file_size).sum::<u64>();
3139 0 : if total_size > sub_compaction_max_job_size_mb * 1024 * 1024 || ranges_num == idx + 1 {
3140 : // Try to extend the compaction range so that we include at least one full layer file.
3141 0 : let extended_end = overlapping_layers
3142 0 : .iter()
3143 0 : .map(|layer| layer.key_range.end)
3144 0 : .min();
3145 : // It is possible that the search range does not contain any layer files when we reach the end of the loop.
3146 : // In this case, we simply use the specified key range end.
3147 0 : let end = if let Some(extended_end) = extended_end {
3148 0 : extended_end.max(end)
3149 : } else {
3150 0 : end
3151 : };
3152 0 : let end = if ranges_num == idx + 1 {
3153 : // extend the compaction range to the end of the key range if it's the last partition
3154 0 : end.max(job.compact_key_range.end)
3155 : } else {
3156 0 : end
3157 : };
3158 0 : if total_size == 0 && !compact_jobs.is_empty() {
3159 0 : info!(
3160 0 : "splitting compaction job: {}..{}, estimated_size={}, extending the previous job",
3161 : start, end, total_size
3162 : );
3163 0 : compact_jobs.last_mut().unwrap().compact_key_range.end = end;
3164 0 : current_start = Some(end);
3165 : } else {
3166 0 : info!(
3167 0 : "splitting compaction job: {}..{}, estimated_size={}",
3168 : start, end, total_size
3169 : );
3170 0 : compact_jobs.push(GcCompactJob {
3171 0 : dry_run: job.dry_run,
3172 0 : compact_key_range: start..end,
3173 0 : compact_lsn_range: job.compact_lsn_range.start..compact_below_lsn,
3174 0 : do_metadata_compaction: false,
3175 0 : });
3176 0 : current_start = Some(end);
3177 : }
3178 0 : }
3179 : }
3180 0 : Ok(compact_jobs)
3181 0 : }
3182 :
3183 : /// An experimental compaction building block that combines compaction with garbage collection.
3184 : ///
3185 : /// The current implementation picks all delta + image layers that are below or intersecting with
3186 : /// the GC horizon without considering retain_lsns. Then, it does a full compaction over all these delta
3187 : /// layers and image layers, which generates image layers on the gc horizon, drop deltas below gc horizon,
3188 : /// and create delta layers with all deltas >= gc horizon.
3189 : ///
3190 : /// If `options.compact_range` is provided, it will only compact the keys within the range, aka partial compaction.
3191 : /// Partial compaction will read and process all layers overlapping with the key range, even if it might
3192 : /// contain extra keys. After the gc-compaction phase completes, delta layers that are not fully contained
3193 : /// within the key range will be rewritten to ensure they do not overlap with the delta layers. Providing
3194 : /// Key::MIN..Key..MAX to the function indicates a full compaction, though technically, `Key::MAX` is not
3195 : /// part of the range.
3196 : ///
3197 : /// If `options.compact_lsn_range.end` is provided, the compaction will only compact layers below or intersect with
3198 : /// the LSN. Otherwise, it will use the gc cutoff by default.
3199 28 : pub(crate) async fn compact_with_gc(
3200 28 : self: &Arc<Self>,
3201 28 : cancel: &CancellationToken,
3202 28 : options: CompactOptions,
3203 28 : ctx: &RequestContext,
3204 28 : ) -> Result<CompactionOutcome, CompactionError> {
3205 28 : let sub_compaction = options.sub_compaction;
3206 28 : let job = GcCompactJob::from_compact_options(options.clone());
3207 28 : let yield_for_l0 = options.flags.contains(CompactFlags::YieldForL0);
3208 28 : if sub_compaction {
3209 0 : info!(
3210 0 : "running enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs"
3211 : );
3212 0 : let jobs = self
3213 0 : .gc_compaction_split_jobs(job, options.sub_compaction_max_job_size_mb)
3214 0 : .await?;
3215 0 : let jobs_len = jobs.len();
3216 0 : for (idx, job) in jobs.into_iter().enumerate() {
3217 0 : let sub_compaction_progress = format!("{}/{}", idx + 1, jobs_len);
3218 0 : self.compact_with_gc_inner(cancel, job, ctx, yield_for_l0)
3219 0 : .instrument(info_span!(
3220 : "sub_compaction",
3221 : sub_compaction_progress = sub_compaction_progress
3222 : ))
3223 0 : .await?;
3224 : }
3225 0 : if jobs_len == 0 {
3226 0 : info!("no jobs to run, skipping gc bottom-most compaction");
3227 0 : }
3228 0 : return Ok(CompactionOutcome::Done);
3229 28 : }
3230 28 : self.compact_with_gc_inner(cancel, job, ctx, yield_for_l0)
3231 28 : .await
3232 28 : }
3233 :
3234 28 : async fn compact_with_gc_inner(
3235 28 : self: &Arc<Self>,
3236 28 : cancel: &CancellationToken,
3237 28 : mut job: GcCompactJob,
3238 28 : ctx: &RequestContext,
3239 28 : yield_for_l0: bool,
3240 28 : ) -> Result<CompactionOutcome, CompactionError> {
3241 : // Block other compaction/GC tasks from running for now. GC-compaction could run along
3242 : // with legacy compaction tasks in the future. Always ensure the lock order is compaction -> gc.
3243 : // Note that we already acquired the compaction lock when the outer `compact` function gets called.
3244 :
3245 : // If the job is not configured to compact the metadata key range, shrink the key range
3246 : // to exclude the metadata key range. The check is done by checking if the end of the key range
3247 : // is larger than the start of the metadata key range. Note that metadata keys cover the entire
3248 : // second half of the keyspace, so it's enough to only check the end of the key range.
3249 28 : if !job.do_metadata_compaction
3250 0 : && job.compact_key_range.end > Key::metadata_key_range().start
3251 : {
3252 0 : tracing::info!(
3253 0 : "compaction for metadata key range is not supported yet, overriding compact_key_range from {} to {}",
3254 : job.compact_key_range.end,
3255 0 : Key::metadata_key_range().start
3256 : );
3257 : // Shrink the key range to exclude the metadata key range.
3258 0 : job.compact_key_range.end = Key::metadata_key_range().start;
3259 :
3260 : // Skip the job if the key range completely lies within the metadata key range.
3261 0 : if job.compact_key_range.start >= job.compact_key_range.end {
3262 0 : tracing::info!("compact_key_range is empty, skipping compaction");
3263 0 : return Ok(CompactionOutcome::Done);
3264 0 : }
3265 28 : }
3266 :
3267 28 : let timer = Instant::now();
3268 28 : let begin_timer = timer;
3269 :
3270 28 : let gc_lock = async {
3271 28 : tokio::select! {
3272 28 : guard = self.gc_lock.lock() => Ok(guard),
3273 28 : _ = cancel.cancelled() => Err(CompactionError::new_cancelled()),
3274 : }
3275 28 : };
3276 :
3277 28 : let time_acquire_lock = timer.elapsed();
3278 28 : let timer = Instant::now();
3279 :
3280 28 : let gc_lock = crate::timed(
3281 28 : gc_lock,
3282 28 : "acquires gc lock",
3283 28 : std::time::Duration::from_secs(5),
3284 28 : )
3285 28 : .await?;
3286 :
3287 28 : let dry_run = job.dry_run;
3288 28 : let compact_key_range = job.compact_key_range;
3289 28 : let compact_lsn_range = job.compact_lsn_range;
3290 :
3291 28 : let debug_mode = cfg!(debug_assertions) || cfg!(feature = "testing");
3292 :
3293 28 : info!(
3294 0 : "running enhanced gc bottom-most compaction, dry_run={dry_run}, compact_key_range={}..{}, compact_lsn_range={}..{}",
3295 : compact_key_range.start,
3296 : compact_key_range.end,
3297 : compact_lsn_range.start,
3298 : compact_lsn_range.end
3299 : );
3300 :
3301 28 : scopeguard::defer! {
3302 : info!("done enhanced gc bottom-most compaction");
3303 : };
3304 :
3305 28 : let mut stat = CompactionStatistics::default();
3306 :
3307 : // Step 0: pick all delta layers + image layers below/intersect with the GC horizon.
3308 : // The layer selection has the following properties:
3309 : // 1. If a layer is in the selection, all layers below it are in the selection.
3310 : // 2. Inferred from (1), for each key in the layer selection, the value can be reconstructed only with the layers in the layer selection.
3311 27 : let job_desc = {
3312 28 : let guard = self
3313 28 : .layers
3314 28 : .read(LayerManagerLockHolder::GarbageCollection)
3315 28 : .await;
3316 28 : let layers = guard.layer_map()?;
3317 28 : let gc_info = self.gc_info.read().unwrap();
3318 28 : let mut retain_lsns_below_horizon = Vec::new();
3319 28 : let gc_cutoff = {
3320 : // Currently, gc-compaction only kicks in after the legacy gc has updated the gc_cutoff.
3321 : // Therefore, it can only clean up data that cannot be cleaned up with legacy gc, instead of
3322 : // cleaning everything that theoritically it could. In the future, it should use `self.gc_info`
3323 : // to get the truth data.
3324 28 : let real_gc_cutoff = self.get_gc_compaction_watermark();
3325 : // The compaction algorithm will keep all keys above the gc_cutoff while keeping only necessary keys below the gc_cutoff for
3326 : // each of the retain_lsn. Therefore, if the user-provided `compact_lsn_range.end` is larger than the real gc cutoff, we will use
3327 : // the real cutoff.
3328 28 : let mut gc_cutoff = if compact_lsn_range.end == Lsn::MAX {
3329 25 : if real_gc_cutoff == Lsn::INVALID {
3330 : // If the gc_cutoff is not generated yet, we should not compact anything.
3331 0 : tracing::warn!(
3332 0 : "no layers to compact with gc: gc_cutoff not generated yet, skipping gc bottom-most compaction"
3333 : );
3334 0 : return Ok(CompactionOutcome::Skipped);
3335 25 : }
3336 25 : real_gc_cutoff
3337 : } else {
3338 3 : compact_lsn_range.end
3339 : };
3340 28 : if gc_cutoff > real_gc_cutoff {
3341 2 : warn!(
3342 0 : "provided compact_lsn_range.end={} is larger than the real_gc_cutoff={}, using the real gc cutoff",
3343 : gc_cutoff, real_gc_cutoff
3344 : );
3345 2 : gc_cutoff = real_gc_cutoff;
3346 26 : }
3347 28 : gc_cutoff
3348 : };
3349 35 : for (lsn, _timeline_id, _is_offloaded) in &gc_info.retain_lsns {
3350 35 : if lsn < &gc_cutoff {
3351 35 : retain_lsns_below_horizon.push(*lsn);
3352 35 : }
3353 : }
3354 28 : for lsn in gc_info.leases.keys() {
3355 0 : if lsn < &gc_cutoff {
3356 0 : retain_lsns_below_horizon.push(*lsn);
3357 0 : }
3358 : }
3359 28 : let mut selected_layers: Vec<Layer> = Vec::new();
3360 28 : drop(gc_info);
3361 : // Firstly, pick all the layers intersect or below the gc_cutoff, get the largest LSN in the selected layers.
3362 28 : let Some(max_layer_lsn) = layers
3363 28 : .iter_historic_layers()
3364 125 : .filter(|desc| desc.get_lsn_range().start <= gc_cutoff)
3365 107 : .map(|desc| desc.get_lsn_range().end)
3366 28 : .max()
3367 : else {
3368 0 : info!(
3369 0 : "no layers to compact with gc: no historic layers below gc_cutoff, gc_cutoff={}",
3370 : gc_cutoff
3371 : );
3372 0 : return Ok(CompactionOutcome::Done);
3373 : };
3374 : // Next, if the user specifies compact_lsn_range.start, we need to filter some layers out. All the layers (strictly) below
3375 : // the min_layer_lsn computed as below will be filtered out and the data will be accessed using the normal read path, as if
3376 : // it is a branch.
3377 28 : let Some(min_layer_lsn) = layers
3378 28 : .iter_historic_layers()
3379 125 : .filter(|desc| {
3380 125 : if compact_lsn_range.start == Lsn::INVALID {
3381 102 : true // select all layers below if start == Lsn(0)
3382 : } else {
3383 23 : desc.get_lsn_range().end > compact_lsn_range.start // strictly larger than compact_above_lsn
3384 : }
3385 125 : })
3386 116 : .map(|desc| desc.get_lsn_range().start)
3387 28 : .min()
3388 : else {
3389 0 : info!(
3390 0 : "no layers to compact with gc: no historic layers above compact_above_lsn, compact_above_lsn={}",
3391 : compact_lsn_range.end
3392 : );
3393 0 : return Ok(CompactionOutcome::Done);
3394 : };
3395 : // Then, pick all the layers that are below the max_layer_lsn. This is to ensure we can pick all single-key
3396 : // layers to compact.
3397 28 : let mut rewrite_layers = Vec::new();
3398 125 : for desc in layers.iter_historic_layers() {
3399 125 : if desc.get_lsn_range().end <= max_layer_lsn
3400 107 : && desc.get_lsn_range().start >= min_layer_lsn
3401 98 : && overlaps_with(&desc.get_key_range(), &compact_key_range)
3402 : {
3403 : // If the layer overlaps with the compaction key range, we need to read it to obtain all keys within the range,
3404 : // even if it might contain extra keys
3405 79 : selected_layers.push(guard.get_from_desc(&desc));
3406 : // 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
3407 : // to overlap image layers)
3408 79 : if desc.is_delta() && !fully_contains(&compact_key_range, &desc.get_key_range())
3409 1 : {
3410 1 : rewrite_layers.push(desc);
3411 78 : }
3412 46 : }
3413 : }
3414 28 : if selected_layers.is_empty() {
3415 1 : info!(
3416 0 : "no layers to compact with gc: no layers within the key range, gc_cutoff={}, key_range={}..{}",
3417 : gc_cutoff, compact_key_range.start, compact_key_range.end
3418 : );
3419 1 : return Ok(CompactionOutcome::Done);
3420 27 : }
3421 27 : retain_lsns_below_horizon.sort();
3422 27 : GcCompactionJobDescription {
3423 27 : selected_layers,
3424 27 : gc_cutoff,
3425 27 : retain_lsns_below_horizon,
3426 27 : min_layer_lsn,
3427 27 : max_layer_lsn,
3428 27 : compaction_key_range: compact_key_range,
3429 27 : rewrite_layers,
3430 27 : }
3431 : };
3432 27 : let (has_data_below, lowest_retain_lsn) = if compact_lsn_range.start != Lsn::INVALID {
3433 : // If we only compact above some LSN, we should get the history from the current branch below the specified LSN.
3434 : // We use job_desc.min_layer_lsn as if it's the lowest branch point.
3435 4 : (true, job_desc.min_layer_lsn)
3436 23 : } else if self.ancestor_timeline.is_some() {
3437 : // In theory, we can also use min_layer_lsn here, but using ancestor LSN makes sure the delta layers cover the
3438 : // LSN ranges all the way to the ancestor timeline.
3439 1 : (true, self.ancestor_lsn)
3440 : } else {
3441 22 : let res = job_desc
3442 22 : .retain_lsns_below_horizon
3443 22 : .first()
3444 22 : .copied()
3445 22 : .unwrap_or(job_desc.gc_cutoff);
3446 22 : if debug_mode {
3447 22 : assert_eq!(
3448 : res,
3449 22 : job_desc
3450 22 : .retain_lsns_below_horizon
3451 22 : .iter()
3452 22 : .min()
3453 22 : .copied()
3454 22 : .unwrap_or(job_desc.gc_cutoff)
3455 : );
3456 0 : }
3457 22 : (false, res)
3458 : };
3459 :
3460 27 : let verification = self.get_gc_compaction_settings().gc_compaction_verification;
3461 :
3462 27 : info!(
3463 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={}",
3464 0 : job_desc.selected_layers.len(),
3465 0 : job_desc.rewrite_layers.len(),
3466 : job_desc.max_layer_lsn,
3467 : job_desc.min_layer_lsn,
3468 : job_desc.gc_cutoff,
3469 : lowest_retain_lsn,
3470 : job_desc.compaction_key_range.start,
3471 : job_desc.compaction_key_range.end,
3472 : has_data_below,
3473 : );
3474 :
3475 27 : let time_analyze = timer.elapsed();
3476 27 : let timer = Instant::now();
3477 :
3478 106 : for layer in &job_desc.selected_layers {
3479 79 : debug!("read layer: {}", layer.layer_desc().key());
3480 : }
3481 28 : for layer in &job_desc.rewrite_layers {
3482 1 : debug!("rewrite layer: {}", layer.key());
3483 : }
3484 :
3485 27 : self.check_compaction_space(&job_desc.selected_layers)
3486 27 : .await?;
3487 :
3488 27 : self.check_memory_usage(&job_desc.selected_layers).await?;
3489 27 : if job_desc.selected_layers.len() > 100
3490 0 : && job_desc.rewrite_layers.len() as f64 >= job_desc.selected_layers.len() as f64 * 0.7
3491 : {
3492 0 : return Err(CompactionError::Other(anyhow!(
3493 0 : "too many layers to rewrite: {} / {}, giving up compaction",
3494 0 : job_desc.rewrite_layers.len(),
3495 0 : job_desc.selected_layers.len()
3496 0 : )));
3497 27 : }
3498 :
3499 : // Generate statistics for the compaction
3500 106 : for layer in &job_desc.selected_layers {
3501 79 : let desc = layer.layer_desc();
3502 79 : if desc.is_delta() {
3503 44 : stat.visit_delta_layer(desc.file_size());
3504 44 : } else {
3505 35 : stat.visit_image_layer(desc.file_size());
3506 35 : }
3507 : }
3508 :
3509 : // Step 1: construct a k-merge iterator over all layers.
3510 : // Also, verify if the layer map can be split by drawing a horizontal line at every LSN start/end split point.
3511 27 : let layer_names = job_desc
3512 27 : .selected_layers
3513 27 : .iter()
3514 79 : .map(|layer| layer.layer_desc().layer_name())
3515 27 : .collect_vec();
3516 27 : if let Some(err) = check_valid_layermap(&layer_names) {
3517 0 : return Err(CompactionError::Other(anyhow!(
3518 0 : "gc-compaction layer map check failed because {}, cannot proceed with compaction due to potential data loss",
3519 0 : err
3520 0 : )));
3521 27 : }
3522 : // The maximum LSN we are processing in this compaction loop
3523 27 : let end_lsn = job_desc
3524 27 : .selected_layers
3525 27 : .iter()
3526 79 : .map(|l| l.layer_desc().lsn_range.end)
3527 27 : .max()
3528 27 : .unwrap();
3529 27 : let mut delta_layers = Vec::new();
3530 27 : let mut image_layers = Vec::new();
3531 27 : let mut downloaded_layers = Vec::new();
3532 27 : let mut total_downloaded_size = 0;
3533 27 : let mut total_layer_size = 0;
3534 106 : for layer in &job_desc.selected_layers {
3535 79 : if layer
3536 79 : .needs_download()
3537 79 : .await
3538 79 : .context("failed to check if layer needs download")
3539 79 : .map_err(CompactionError::Other)?
3540 79 : .is_some()
3541 0 : {
3542 0 : total_downloaded_size += layer.layer_desc().file_size;
3543 79 : }
3544 79 : total_layer_size += layer.layer_desc().file_size;
3545 79 : if cancel.is_cancelled() {
3546 0 : return Err(CompactionError::new_cancelled());
3547 79 : }
3548 79 : let should_yield = yield_for_l0
3549 0 : && self
3550 0 : .l0_compaction_trigger
3551 0 : .notified()
3552 0 : .now_or_never()
3553 0 : .is_some();
3554 79 : if should_yield {
3555 0 : tracing::info!("preempt gc-compaction when downloading layers: too many L0 layers");
3556 0 : return Ok(CompactionOutcome::YieldForL0);
3557 79 : }
3558 79 : let resident_layer = layer
3559 79 : .download_and_keep_resident(ctx)
3560 79 : .await
3561 79 : .context("failed to download and keep resident layer")
3562 79 : .map_err(CompactionError::Other)?;
3563 79 : downloaded_layers.push(resident_layer);
3564 : }
3565 27 : info!(
3566 0 : "finish downloading layers, downloaded={}, total={}, ratio={:.2}",
3567 : total_downloaded_size,
3568 : total_layer_size,
3569 0 : total_downloaded_size as f64 / total_layer_size as f64
3570 : );
3571 106 : for resident_layer in &downloaded_layers {
3572 79 : if resident_layer.layer_desc().is_delta() {
3573 44 : let layer = resident_layer
3574 44 : .get_as_delta(ctx)
3575 44 : .await
3576 44 : .context("failed to get delta layer")
3577 44 : .map_err(CompactionError::Other)?;
3578 44 : delta_layers.push(layer);
3579 : } else {
3580 35 : let layer = resident_layer
3581 35 : .get_as_image(ctx)
3582 35 : .await
3583 35 : .context("failed to get image layer")
3584 35 : .map_err(CompactionError::Other)?;
3585 35 : image_layers.push(layer);
3586 : }
3587 : }
3588 27 : let (dense_ks, sparse_ks) = self
3589 27 : .collect_gc_compaction_keyspace()
3590 27 : .await
3591 27 : .context("failed to collect gc compaction keyspace")
3592 27 : .map_err(CompactionError::Other)?;
3593 27 : let mut merge_iter = FilterIterator::create(
3594 27 : MergeIterator::create_with_options(
3595 27 : &delta_layers,
3596 27 : &image_layers,
3597 27 : ctx,
3598 27 : 128 * 8192, /* 1MB buffer for each of the inner iterators */
3599 : 128,
3600 : ),
3601 27 : dense_ks,
3602 27 : sparse_ks,
3603 : )
3604 27 : .context("failed to create filter iterator")
3605 27 : .map_err(CompactionError::Other)?;
3606 :
3607 27 : let time_download_layer = timer.elapsed();
3608 27 : let mut timer = Instant::now();
3609 :
3610 : // Step 2: Produce images+deltas.
3611 27 : let mut accumulated_values = Vec::new();
3612 27 : let mut accumulated_values_estimated_size = 0;
3613 27 : let mut last_key: Option<Key> = None;
3614 :
3615 : // Only create image layers when there is no ancestor branches. TODO: create covering image layer
3616 : // when some condition meet.
3617 27 : let mut image_layer_writer = if !has_data_below {
3618 22 : Some(SplitImageLayerWriter::new(
3619 22 : self.conf,
3620 22 : self.timeline_id,
3621 22 : self.tenant_shard_id,
3622 22 : job_desc.compaction_key_range.start,
3623 22 : lowest_retain_lsn,
3624 22 : self.get_compaction_target_size(),
3625 22 : &self.gate,
3626 22 : self.cancel.clone(),
3627 22 : ))
3628 : } else {
3629 5 : None
3630 : };
3631 :
3632 27 : let mut delta_layer_writer = SplitDeltaLayerWriter::new(
3633 27 : self.conf,
3634 27 : self.timeline_id,
3635 27 : self.tenant_shard_id,
3636 27 : lowest_retain_lsn..end_lsn,
3637 27 : self.get_compaction_target_size(),
3638 27 : &self.gate,
3639 27 : self.cancel.clone(),
3640 : );
3641 :
3642 : #[derive(Default)]
3643 : struct RewritingLayers {
3644 : before: Option<DeltaLayerWriter>,
3645 : after: Option<DeltaLayerWriter>,
3646 : }
3647 27 : let mut delta_layer_rewriters = HashMap::<Arc<PersistentLayerKey>, RewritingLayers>::new();
3648 :
3649 : /// When compacting not at a bottom range (=`[0,X)`) of the root branch, we "have data below" (`has_data_below=true`).
3650 : /// The two cases are compaction in ancestor branches and when `compact_lsn_range.start` is set.
3651 : /// In those cases, we need to pull up data from below the LSN range we're compaction.
3652 : ///
3653 : /// This function unifies the cases so that later code doesn't have to think about it.
3654 : ///
3655 : /// Currently, we always get the ancestor image for each key in the child branch no matter whether the image
3656 : /// is needed for reconstruction. This should be fixed in the future.
3657 : ///
3658 : /// Furthermore, we should do vectored get instead of a single get, or better, use k-merge for ancestor
3659 : /// images.
3660 320 : async fn get_ancestor_image(
3661 320 : this_tline: &Arc<Timeline>,
3662 320 : key: Key,
3663 320 : ctx: &RequestContext,
3664 320 : has_data_below: bool,
3665 320 : history_lsn_point: Lsn,
3666 320 : ) -> anyhow::Result<Option<(Key, Lsn, Bytes)>> {
3667 320 : if !has_data_below {
3668 301 : return Ok(None);
3669 19 : };
3670 : // This function is implemented as a get of the current timeline at ancestor LSN, therefore reusing
3671 : // as much existing code as possible.
3672 19 : let img = this_tline.get(key, history_lsn_point, ctx).await?;
3673 19 : Ok(Some((key, history_lsn_point, img)))
3674 320 : }
3675 :
3676 : // Actually, we can decide not to write to the image layer at all at this point because
3677 : // the key and LSN range are determined. However, to keep things simple here, we still
3678 : // create this writer, and discard the writer in the end.
3679 27 : let mut time_to_first_kv_pair = None;
3680 :
3681 496 : while let Some(((key, lsn, val), desc)) = merge_iter
3682 496 : .next_with_trace()
3683 496 : .await
3684 496 : .context("failed to get next key-value pair")
3685 496 : .map_err(CompactionError::Other)?
3686 : {
3687 470 : if time_to_first_kv_pair.is_none() {
3688 27 : time_to_first_kv_pair = Some(timer.elapsed());
3689 27 : timer = Instant::now();
3690 443 : }
3691 :
3692 470 : if cancel.is_cancelled() {
3693 0 : return Err(CompactionError::new_cancelled());
3694 470 : }
3695 :
3696 470 : let should_yield = yield_for_l0
3697 0 : && self
3698 0 : .l0_compaction_trigger
3699 0 : .notified()
3700 0 : .now_or_never()
3701 0 : .is_some();
3702 470 : if should_yield {
3703 0 : tracing::info!("preempt gc-compaction in the main loop: too many L0 layers");
3704 0 : return Ok(CompactionOutcome::YieldForL0);
3705 470 : }
3706 470 : if self.shard_identity.is_key_disposable(&key) {
3707 : // If this shard does not need to store this key, simply skip it.
3708 : //
3709 : // This is not handled in the filter iterator because shard is determined by hash.
3710 : // Therefore, it does not give us any performance benefit to do things like skip
3711 : // a whole layer file as handling key spaces (ranges).
3712 0 : if cfg!(debug_assertions) {
3713 0 : let shard = self.shard_identity.shard_index();
3714 0 : let owner = self.shard_identity.get_shard_number(&key);
3715 0 : panic!("key {key} does not belong on shard {shard}, owned by {owner}");
3716 0 : }
3717 0 : continue;
3718 470 : }
3719 470 : if !job_desc.compaction_key_range.contains(&key) {
3720 32 : if !desc.is_delta {
3721 30 : continue;
3722 2 : }
3723 2 : let rewriter = delta_layer_rewriters.entry(desc.clone()).or_default();
3724 2 : let rewriter = if key < job_desc.compaction_key_range.start {
3725 0 : if rewriter.before.is_none() {
3726 0 : rewriter.before = Some(
3727 0 : DeltaLayerWriter::new(
3728 0 : self.conf,
3729 0 : self.timeline_id,
3730 0 : self.tenant_shard_id,
3731 0 : desc.key_range.start,
3732 0 : desc.lsn_range.clone(),
3733 0 : &self.gate,
3734 0 : self.cancel.clone(),
3735 0 : ctx,
3736 0 : )
3737 0 : .await
3738 0 : .context("failed to create delta layer writer")
3739 0 : .map_err(CompactionError::Other)?,
3740 : );
3741 0 : }
3742 0 : rewriter.before.as_mut().unwrap()
3743 2 : } else if key >= job_desc.compaction_key_range.end {
3744 2 : if rewriter.after.is_none() {
3745 1 : rewriter.after = Some(
3746 1 : DeltaLayerWriter::new(
3747 1 : self.conf,
3748 1 : self.timeline_id,
3749 1 : self.tenant_shard_id,
3750 1 : job_desc.compaction_key_range.end,
3751 1 : desc.lsn_range.clone(),
3752 1 : &self.gate,
3753 1 : self.cancel.clone(),
3754 1 : ctx,
3755 1 : )
3756 1 : .await
3757 1 : .context("failed to create delta layer writer")
3758 1 : .map_err(CompactionError::Other)?,
3759 : );
3760 1 : }
3761 2 : rewriter.after.as_mut().unwrap()
3762 : } else {
3763 0 : unreachable!()
3764 : };
3765 2 : rewriter
3766 2 : .put_value(key, lsn, val, ctx)
3767 2 : .await
3768 2 : .context("failed to put value")
3769 2 : .map_err(CompactionError::Other)?;
3770 2 : continue;
3771 438 : }
3772 438 : match val {
3773 315 : Value::Image(_) => stat.visit_image_key(&val),
3774 123 : Value::WalRecord(_) => stat.visit_wal_key(&val),
3775 : }
3776 438 : if last_key.is_none() || last_key.as_ref() == Some(&key) {
3777 144 : if last_key.is_none() {
3778 27 : last_key = Some(key);
3779 117 : }
3780 144 : accumulated_values_estimated_size += val.estimated_size();
3781 144 : accumulated_values.push((key, lsn, val));
3782 :
3783 : // Accumulated values should never exceed 512MB.
3784 144 : if accumulated_values_estimated_size >= 1024 * 1024 * 512 {
3785 0 : return Err(CompactionError::Other(anyhow!(
3786 0 : "too many values for a single key: {} for key {}, {} items",
3787 0 : accumulated_values_estimated_size,
3788 0 : key,
3789 0 : accumulated_values.len()
3790 0 : )));
3791 144 : }
3792 : } else {
3793 294 : let last_key: &mut Key = last_key.as_mut().unwrap();
3794 294 : stat.on_unique_key_visited(); // TODO: adjust statistics for partial compaction
3795 294 : let retention = self
3796 294 : .generate_key_retention(
3797 294 : *last_key,
3798 294 : &accumulated_values,
3799 294 : job_desc.gc_cutoff,
3800 294 : &job_desc.retain_lsns_below_horizon,
3801 : COMPACTION_DELTA_THRESHOLD,
3802 294 : get_ancestor_image(self, *last_key, ctx, has_data_below, lowest_retain_lsn)
3803 294 : .await
3804 294 : .context("failed to get ancestor image")
3805 294 : .map_err(CompactionError::Other)?,
3806 294 : verification,
3807 : )
3808 294 : .await
3809 294 : .context("failed to generate key retention")
3810 294 : .map_err(CompactionError::Other)?;
3811 293 : retention
3812 293 : .pipe_to(
3813 293 : *last_key,
3814 293 : &mut delta_layer_writer,
3815 293 : image_layer_writer.as_mut(),
3816 293 : &mut stat,
3817 293 : ctx,
3818 293 : )
3819 293 : .await
3820 293 : .context("failed to pipe to delta layer writer")
3821 293 : .map_err(CompactionError::Other)?;
3822 293 : accumulated_values.clear();
3823 293 : *last_key = key;
3824 293 : accumulated_values_estimated_size = val.estimated_size();
3825 293 : accumulated_values.push((key, lsn, val));
3826 : }
3827 : }
3828 :
3829 : // TODO: move the below part to the loop body
3830 26 : let Some(last_key) = last_key else {
3831 0 : return Err(CompactionError::Other(anyhow!(
3832 0 : "no keys produced during compaction"
3833 0 : )));
3834 : };
3835 26 : stat.on_unique_key_visited();
3836 :
3837 26 : let retention = self
3838 26 : .generate_key_retention(
3839 26 : last_key,
3840 26 : &accumulated_values,
3841 26 : job_desc.gc_cutoff,
3842 26 : &job_desc.retain_lsns_below_horizon,
3843 : COMPACTION_DELTA_THRESHOLD,
3844 26 : get_ancestor_image(self, last_key, ctx, has_data_below, lowest_retain_lsn)
3845 26 : .await
3846 26 : .context("failed to get ancestor image")
3847 26 : .map_err(CompactionError::Other)?,
3848 26 : verification,
3849 : )
3850 26 : .await
3851 26 : .context("failed to generate key retention")
3852 26 : .map_err(CompactionError::Other)?;
3853 26 : retention
3854 26 : .pipe_to(
3855 26 : last_key,
3856 26 : &mut delta_layer_writer,
3857 26 : image_layer_writer.as_mut(),
3858 26 : &mut stat,
3859 26 : ctx,
3860 26 : )
3861 26 : .await
3862 26 : .context("failed to pipe to delta layer writer")
3863 26 : .map_err(CompactionError::Other)?;
3864 : // end: move the above part to the loop body
3865 :
3866 26 : let time_main_loop = timer.elapsed();
3867 26 : let timer = Instant::now();
3868 :
3869 26 : let mut rewrote_delta_layers = Vec::new();
3870 27 : for (key, writers) in delta_layer_rewriters {
3871 1 : if let Some(delta_writer_before) = writers.before {
3872 0 : let (desc, path) = delta_writer_before
3873 0 : .finish(job_desc.compaction_key_range.start, ctx)
3874 0 : .await
3875 0 : .context("failed to finish delta layer writer")
3876 0 : .map_err(CompactionError::Other)?;
3877 0 : let layer = Layer::finish_creating(self.conf, self, desc, &path)
3878 0 : .context("failed to finish creating delta layer")
3879 0 : .map_err(CompactionError::Other)?;
3880 0 : rewrote_delta_layers.push(layer);
3881 1 : }
3882 1 : if let Some(delta_writer_after) = writers.after {
3883 1 : let (desc, path) = delta_writer_after
3884 1 : .finish(key.key_range.end, ctx)
3885 1 : .await
3886 1 : .context("failed to finish delta layer writer")
3887 1 : .map_err(CompactionError::Other)?;
3888 1 : let layer = Layer::finish_creating(self.conf, self, desc, &path)
3889 1 : .context("failed to finish creating delta layer")
3890 1 : .map_err(CompactionError::Other)?;
3891 1 : rewrote_delta_layers.push(layer);
3892 0 : }
3893 : }
3894 :
3895 37 : let discard = |key: &PersistentLayerKey| {
3896 37 : let key = key.clone();
3897 37 : async move { KeyHistoryRetention::discard_key(&key, self, dry_run).await }
3898 37 : };
3899 :
3900 26 : let produced_image_layers = if let Some(writer) = image_layer_writer {
3901 21 : if !dry_run {
3902 19 : let end_key = job_desc.compaction_key_range.end;
3903 19 : writer
3904 19 : .finish_with_discard_fn(self, ctx, end_key, discard)
3905 19 : .await
3906 19 : .context("failed to finish image layer writer")
3907 19 : .map_err(CompactionError::Other)?
3908 : } else {
3909 2 : drop(writer);
3910 2 : Vec::new()
3911 : }
3912 : } else {
3913 5 : Vec::new()
3914 : };
3915 :
3916 26 : let produced_delta_layers = if !dry_run {
3917 24 : delta_layer_writer
3918 24 : .finish_with_discard_fn(self, ctx, discard)
3919 24 : .await
3920 24 : .context("failed to finish delta layer writer")
3921 24 : .map_err(CompactionError::Other)?
3922 : } else {
3923 2 : drop(delta_layer_writer);
3924 2 : Vec::new()
3925 : };
3926 :
3927 : // TODO: make image/delta/rewrote_delta layers generation atomic. At this point, we already generated resident layers, and if
3928 : // compaction is cancelled at this point, we might have some layers that are not cleaned up.
3929 26 : let mut compact_to = Vec::new();
3930 26 : let mut keep_layers = HashSet::new();
3931 26 : let produced_delta_layers_len = produced_delta_layers.len();
3932 26 : let produced_image_layers_len = produced_image_layers.len();
3933 :
3934 26 : let layer_selection_by_key = job_desc
3935 26 : .selected_layers
3936 26 : .iter()
3937 76 : .map(|l| (l.layer_desc().key(), l.layer_desc().clone()))
3938 26 : .collect::<HashMap<_, _>>();
3939 :
3940 44 : for action in produced_delta_layers {
3941 18 : match action {
3942 11 : BatchWriterResult::Produced(layer) => {
3943 11 : if cfg!(debug_assertions) {
3944 11 : info!("produced delta layer: {}", layer.layer_desc().key());
3945 0 : }
3946 11 : stat.produce_delta_layer(layer.layer_desc().file_size());
3947 11 : compact_to.push(layer);
3948 : }
3949 7 : BatchWriterResult::Discarded(l) => {
3950 7 : if cfg!(debug_assertions) {
3951 7 : info!("discarded delta layer: {}", l);
3952 0 : }
3953 7 : if let Some(layer_desc) = layer_selection_by_key.get(&l) {
3954 7 : stat.discard_delta_layer(layer_desc.file_size());
3955 7 : } else {
3956 0 : tracing::warn!(
3957 0 : "discarded delta layer not in layer_selection: {}, produced a layer outside of the compaction key range?",
3958 : l
3959 : );
3960 0 : stat.discard_delta_layer(0);
3961 : }
3962 7 : keep_layers.insert(l);
3963 : }
3964 : }
3965 : }
3966 27 : for layer in &rewrote_delta_layers {
3967 1 : debug!(
3968 0 : "produced rewritten delta layer: {}",
3969 0 : layer.layer_desc().key()
3970 : );
3971 : // For now, we include rewritten delta layer size in the "produce_delta_layer". We could
3972 : // make it a separate statistics in the future.
3973 1 : stat.produce_delta_layer(layer.layer_desc().file_size());
3974 : }
3975 26 : compact_to.extend(rewrote_delta_layers);
3976 45 : for action in produced_image_layers {
3977 19 : match action {
3978 15 : BatchWriterResult::Produced(layer) => {
3979 15 : debug!("produced image layer: {}", layer.layer_desc().key());
3980 15 : stat.produce_image_layer(layer.layer_desc().file_size());
3981 15 : compact_to.push(layer);
3982 : }
3983 4 : BatchWriterResult::Discarded(l) => {
3984 4 : debug!("discarded image layer: {}", l);
3985 4 : if let Some(layer_desc) = layer_selection_by_key.get(&l) {
3986 4 : stat.discard_image_layer(layer_desc.file_size());
3987 4 : } else {
3988 0 : tracing::warn!(
3989 0 : "discarded image layer not in layer_selection: {}, produced a layer outside of the compaction key range?",
3990 : l
3991 : );
3992 0 : stat.discard_image_layer(0);
3993 : }
3994 4 : keep_layers.insert(l);
3995 : }
3996 : }
3997 : }
3998 :
3999 26 : let mut layer_selection = job_desc.selected_layers;
4000 :
4001 : // Partial compaction might select more data than it processes, e.g., if
4002 : // the compaction_key_range only partially overlaps:
4003 : //
4004 : // [---compaction_key_range---]
4005 : // [---A----][----B----][----C----][----D----]
4006 : //
4007 : // For delta layers, we will rewrite the layers so that it is cut exactly at
4008 : // the compaction key range, so we can always discard them. However, for image
4009 : // layers, as we do not rewrite them for now, we need to handle them differently.
4010 : // Assume image layers A, B, C, D are all in the `layer_selection`.
4011 : //
4012 : // The created image layers contain whatever is needed from B, C, and from
4013 : // `----]` of A, and from `[---` of D.
4014 : //
4015 : // In contrast, `[---A` and `D----]` have not been processed, so, we must
4016 : // keep that data.
4017 : //
4018 : // The solution for now is to keep A and D completely if they are image layers.
4019 : // (layer_selection is what we'll remove from the layer map, so, retain what
4020 : // is _not_ fully covered by compaction_key_range).
4021 102 : for layer in &layer_selection {
4022 76 : if !layer.layer_desc().is_delta() {
4023 33 : if !overlaps_with(
4024 33 : &layer.layer_desc().key_range,
4025 33 : &job_desc.compaction_key_range,
4026 33 : ) {
4027 0 : return Err(CompactionError::Other(anyhow!(
4028 0 : "violated constraint: image layer outside of compaction key range"
4029 0 : )));
4030 33 : }
4031 33 : if !fully_contains(
4032 33 : &job_desc.compaction_key_range,
4033 33 : &layer.layer_desc().key_range,
4034 33 : ) {
4035 4 : keep_layers.insert(layer.layer_desc().key());
4036 29 : }
4037 43 : }
4038 : }
4039 :
4040 76 : layer_selection.retain(|x| !keep_layers.contains(&x.layer_desc().key()));
4041 :
4042 26 : let time_final_phase = timer.elapsed();
4043 :
4044 26 : stat.time_final_phase_secs = time_final_phase.as_secs_f64();
4045 26 : stat.time_to_first_kv_pair_secs = time_to_first_kv_pair
4046 26 : .unwrap_or(Duration::ZERO)
4047 26 : .as_secs_f64();
4048 26 : stat.time_main_loop_secs = time_main_loop.as_secs_f64();
4049 26 : stat.time_acquire_lock_secs = time_acquire_lock.as_secs_f64();
4050 26 : stat.time_download_layer_secs = time_download_layer.as_secs_f64();
4051 26 : stat.time_analyze_secs = time_analyze.as_secs_f64();
4052 26 : stat.time_total_secs = begin_timer.elapsed().as_secs_f64();
4053 26 : stat.finalize();
4054 :
4055 26 : info!(
4056 0 : "gc-compaction statistics: {}",
4057 0 : serde_json::to_string(&stat)
4058 0 : .context("failed to serialize gc-compaction statistics")
4059 0 : .map_err(CompactionError::Other)?
4060 : );
4061 :
4062 26 : if dry_run {
4063 2 : return Ok(CompactionOutcome::Done);
4064 24 : }
4065 :
4066 24 : info!(
4067 0 : "produced {} delta layers and {} image layers, {} layers are kept",
4068 : produced_delta_layers_len,
4069 : produced_image_layers_len,
4070 0 : keep_layers.len()
4071 : );
4072 :
4073 : // Step 3: Place back to the layer map.
4074 :
4075 : // First, do a sanity check to ensure the newly-created layer map does not contain overlaps.
4076 24 : let all_layers = {
4077 24 : let guard = self
4078 24 : .layers
4079 24 : .read(LayerManagerLockHolder::GarbageCollection)
4080 24 : .await;
4081 24 : let layer_map = guard.layer_map()?;
4082 24 : layer_map.iter_historic_layers().collect_vec()
4083 : };
4084 :
4085 24 : let mut final_layers = all_layers
4086 24 : .iter()
4087 107 : .map(|layer| layer.layer_name())
4088 24 : .collect::<HashSet<_>>();
4089 76 : for layer in &layer_selection {
4090 52 : final_layers.remove(&layer.layer_desc().layer_name());
4091 52 : }
4092 51 : for layer in &compact_to {
4093 27 : final_layers.insert(layer.layer_desc().layer_name());
4094 27 : }
4095 24 : let final_layers = final_layers.into_iter().collect_vec();
4096 :
4097 : // 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
4098 : // the writer, so potentially, we will need a function like `ImageLayerBatchWriter::get_all_pending_layer_keys` to get all the keys that are
4099 : // in the writer before finalizing the persistent layers. Now we would leave some dangling layers on the disk if the check fails.
4100 24 : if let Some(err) = check_valid_layermap(&final_layers) {
4101 0 : return Err(CompactionError::Other(anyhow!(
4102 0 : "gc-compaction layer map check failed after compaction because {}, compaction result not applied to the layer map due to potential data loss",
4103 0 : err
4104 0 : )));
4105 24 : }
4106 :
4107 : // Between the sanity check and this compaction update, there could be new layers being flushed, but it should be fine because we only
4108 : // operate on L1 layers.
4109 : {
4110 : // Gc-compaction will rewrite the history of a key. This could happen in two ways:
4111 : //
4112 : // 1. We create an image layer to replace all the deltas below the compact LSN. In this case, assume
4113 : // we have 2 delta layers A and B, both below the compact LSN. We create an image layer I to replace
4114 : // A and B at the compact LSN. If the read path finishes reading A, yields, and now we update the layer
4115 : // map, the read path then cannot find any keys below A, reporting a missing key error, while the key
4116 : // now gets stored in I at the compact LSN.
4117 : //
4118 : // --------------- ---------------
4119 : // delta1@LSN20 image1@LSN20
4120 : // --------------- (read path collects delta@LSN20, => --------------- (read path cannot find anything
4121 : // delta1@LSN10 yields) below LSN 20)
4122 : // ---------------
4123 : //
4124 : // 2. We create a delta layer to replace all the deltas below the compact LSN, and in the delta layers,
4125 : // we combines the history of a key into a single image. For example, we have deltas at LSN 1, 2, 3, 4,
4126 : // Assume one delta layer contains LSN 1, 2, 3 and the other contains LSN 4.
4127 : //
4128 : // We let gc-compaction combine delta 2, 3, 4 into an image at LSN 4, which produces a delta layer that
4129 : // contains the delta at LSN 1, the image at LSN 4. If the read path finishes reading the original delta
4130 : // layer containing 4, yields, and we update the layer map to put the delta layer.
4131 : //
4132 : // --------------- ---------------
4133 : // delta1@LSN4 image1@LSN4
4134 : // --------------- (read path collects delta@LSN4, => --------------- (read path collects LSN4 and LSN1,
4135 : // delta1@LSN1-3 yields) delta1@LSN1 which is an invalid history)
4136 : // --------------- ---------------
4137 : //
4138 : // Therefore, the gc-compaction layer update operation should wait for all ongoing reads, block all pending reads,
4139 : // and only allow reads to continue after the update is finished.
4140 :
4141 24 : let update_guard = self.gc_compaction_layer_update_lock.write().await;
4142 : // Acquiring the update guard ensures current read operations end and new read operations are blocked.
4143 : // TODO: can we use `latest_gc_cutoff` Rcu to achieve the same effect?
4144 24 : let mut guard = self
4145 24 : .layers
4146 24 : .write(LayerManagerLockHolder::GarbageCollection)
4147 24 : .await;
4148 24 : guard
4149 24 : .open_mut()?
4150 24 : .finish_gc_compaction(&layer_selection, &compact_to, &self.metrics);
4151 24 : drop(update_guard); // Allow new reads to start ONLY after we finished updating the layer map.
4152 : };
4153 :
4154 : // Schedule an index-only upload to update the `latest_gc_cutoff` in the index_part.json.
4155 : // Otherwise, after restart, the index_part only contains the old `latest_gc_cutoff` and
4156 : // find_gc_cutoffs will try accessing things below the cutoff. TODO: ideally, this should
4157 : // be batched into `schedule_compaction_update`.
4158 24 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
4159 24 : self.schedule_uploads(disk_consistent_lsn, None)
4160 24 : .context("failed to schedule uploads")
4161 24 : .map_err(CompactionError::Other)?;
4162 : // If a layer gets rewritten throughout gc-compaction, we need to keep that layer only in `compact_to` instead
4163 : // of `compact_from`.
4164 24 : let compact_from = {
4165 24 : let mut compact_from = Vec::new();
4166 24 : let mut compact_to_set = HashMap::new();
4167 51 : for layer in &compact_to {
4168 27 : compact_to_set.insert(layer.layer_desc().key(), layer);
4169 27 : }
4170 76 : for layer in &layer_selection {
4171 52 : if let Some(to) = compact_to_set.get(&layer.layer_desc().key()) {
4172 0 : tracing::info!(
4173 0 : "skipping delete {} because found same layer key at different generation {}",
4174 : layer,
4175 : to
4176 : );
4177 52 : } else {
4178 52 : compact_from.push(layer.clone());
4179 52 : }
4180 : }
4181 24 : compact_from
4182 : };
4183 24 : self.remote_client
4184 24 : .schedule_compaction_update(&compact_from, &compact_to)?;
4185 :
4186 24 : drop(gc_lock);
4187 :
4188 24 : Ok(CompactionOutcome::Done)
4189 28 : }
4190 : }
4191 :
4192 : struct TimelineAdaptor {
4193 : timeline: Arc<Timeline>,
4194 :
4195 : keyspace: (Lsn, KeySpace),
4196 :
4197 : new_deltas: Vec<ResidentLayer>,
4198 : new_images: Vec<ResidentLayer>,
4199 : layers_to_delete: Vec<Arc<PersistentLayerDesc>>,
4200 : }
4201 :
4202 : impl TimelineAdaptor {
4203 0 : pub fn new(timeline: &Arc<Timeline>, keyspace: (Lsn, KeySpace)) -> Self {
4204 0 : Self {
4205 0 : timeline: timeline.clone(),
4206 0 : keyspace,
4207 0 : new_images: Vec::new(),
4208 0 : new_deltas: Vec::new(),
4209 0 : layers_to_delete: Vec::new(),
4210 0 : }
4211 0 : }
4212 :
4213 0 : pub async fn flush_updates(&mut self) -> Result<(), CompactionError> {
4214 0 : let layers_to_delete = {
4215 0 : let guard = self
4216 0 : .timeline
4217 0 : .layers
4218 0 : .read(LayerManagerLockHolder::Compaction)
4219 0 : .await;
4220 0 : self.layers_to_delete
4221 0 : .iter()
4222 0 : .map(|x| guard.get_from_desc(x))
4223 0 : .collect::<Vec<Layer>>()
4224 : };
4225 0 : self.timeline
4226 0 : .finish_compact_batch(&self.new_deltas, &self.new_images, &layers_to_delete)
4227 0 : .await?;
4228 :
4229 0 : self.timeline
4230 0 : .upload_new_image_layers(std::mem::take(&mut self.new_images))?;
4231 :
4232 0 : self.new_deltas.clear();
4233 0 : self.layers_to_delete.clear();
4234 0 : Ok(())
4235 0 : }
4236 : }
4237 :
4238 : #[derive(Clone)]
4239 : struct ResidentDeltaLayer(ResidentLayer);
4240 : #[derive(Clone)]
4241 : struct ResidentImageLayer(ResidentLayer);
4242 :
4243 : impl CompactionJobExecutor for TimelineAdaptor {
4244 : type Key = pageserver_api::key::Key;
4245 :
4246 : type Layer = OwnArc<PersistentLayerDesc>;
4247 : type DeltaLayer = ResidentDeltaLayer;
4248 : type ImageLayer = ResidentImageLayer;
4249 :
4250 : type RequestContext = crate::context::RequestContext;
4251 :
4252 0 : fn get_shard_identity(&self) -> &ShardIdentity {
4253 0 : self.timeline.get_shard_identity()
4254 0 : }
4255 :
4256 0 : async fn get_layers(
4257 0 : &mut self,
4258 0 : key_range: &Range<Key>,
4259 0 : lsn_range: &Range<Lsn>,
4260 0 : _ctx: &RequestContext,
4261 0 : ) -> anyhow::Result<Vec<OwnArc<PersistentLayerDesc>>> {
4262 0 : self.flush_updates().await?;
4263 :
4264 0 : let guard = self
4265 0 : .timeline
4266 0 : .layers
4267 0 : .read(LayerManagerLockHolder::Compaction)
4268 0 : .await;
4269 0 : let layer_map = guard.layer_map()?;
4270 :
4271 0 : let result = layer_map
4272 0 : .iter_historic_layers()
4273 0 : .filter(|l| {
4274 0 : overlaps_with(&l.lsn_range, lsn_range) && overlaps_with(&l.key_range, key_range)
4275 0 : })
4276 0 : .map(OwnArc)
4277 0 : .collect();
4278 0 : Ok(result)
4279 0 : }
4280 :
4281 0 : async fn get_keyspace(
4282 0 : &mut self,
4283 0 : key_range: &Range<Key>,
4284 0 : lsn: Lsn,
4285 0 : _ctx: &RequestContext,
4286 0 : ) -> anyhow::Result<Vec<Range<Key>>> {
4287 0 : if lsn == self.keyspace.0 {
4288 0 : Ok(pageserver_compaction::helpers::intersect_keyspace(
4289 0 : &self.keyspace.1.ranges,
4290 0 : key_range,
4291 0 : ))
4292 : } else {
4293 : // The current compaction implementation only ever requests the key space
4294 : // at the compaction end LSN.
4295 0 : anyhow::bail!("keyspace not available for requested lsn");
4296 : }
4297 0 : }
4298 :
4299 0 : async fn downcast_delta_layer(
4300 0 : &self,
4301 0 : layer: &OwnArc<PersistentLayerDesc>,
4302 0 : ctx: &RequestContext,
4303 0 : ) -> anyhow::Result<Option<ResidentDeltaLayer>> {
4304 : // this is a lot more complex than a simple downcast...
4305 0 : if layer.is_delta() {
4306 0 : let l = {
4307 0 : let guard = self
4308 0 : .timeline
4309 0 : .layers
4310 0 : .read(LayerManagerLockHolder::Compaction)
4311 0 : .await;
4312 0 : guard.get_from_desc(layer)
4313 : };
4314 0 : let result = l.download_and_keep_resident(ctx).await?;
4315 :
4316 0 : Ok(Some(ResidentDeltaLayer(result)))
4317 : } else {
4318 0 : Ok(None)
4319 : }
4320 0 : }
4321 :
4322 0 : async fn create_image(
4323 0 : &mut self,
4324 0 : lsn: Lsn,
4325 0 : key_range: &Range<Key>,
4326 0 : ctx: &RequestContext,
4327 0 : ) -> anyhow::Result<()> {
4328 0 : Ok(self.create_image_impl(lsn, key_range, ctx).await?)
4329 0 : }
4330 :
4331 0 : async fn create_delta(
4332 0 : &mut self,
4333 0 : lsn_range: &Range<Lsn>,
4334 0 : key_range: &Range<Key>,
4335 0 : input_layers: &[ResidentDeltaLayer],
4336 0 : ctx: &RequestContext,
4337 0 : ) -> anyhow::Result<()> {
4338 0 : debug!("Create new layer {}..{}", lsn_range.start, lsn_range.end);
4339 :
4340 0 : let mut all_entries = Vec::new();
4341 0 : for dl in input_layers.iter() {
4342 0 : all_entries.extend(dl.load_keys(ctx).await?);
4343 : }
4344 :
4345 : // The current stdlib sorting implementation is designed in a way where it is
4346 : // particularly fast where the slice is made up of sorted sub-ranges.
4347 0 : all_entries.sort_by_key(|DeltaEntry { key, lsn, .. }| (*key, *lsn));
4348 :
4349 0 : let mut writer = DeltaLayerWriter::new(
4350 0 : self.timeline.conf,
4351 0 : self.timeline.timeline_id,
4352 0 : self.timeline.tenant_shard_id,
4353 0 : key_range.start,
4354 0 : lsn_range.clone(),
4355 0 : &self.timeline.gate,
4356 0 : self.timeline.cancel.clone(),
4357 0 : ctx,
4358 0 : )
4359 0 : .await?;
4360 :
4361 0 : let mut dup_values = 0;
4362 :
4363 : // This iterator walks through all key-value pairs from all the layers
4364 : // we're compacting, in key, LSN order.
4365 0 : let mut prev: Option<(Key, Lsn)> = None;
4366 : for &DeltaEntry {
4367 0 : key, lsn, ref val, ..
4368 0 : } in all_entries.iter()
4369 : {
4370 0 : if prev == Some((key, lsn)) {
4371 : // This is a duplicate. Skip it.
4372 : //
4373 : // It can happen if compaction is interrupted after writing some
4374 : // layers but not all, and we are compacting the range again.
4375 : // The calculations in the algorithm assume that there are no
4376 : // duplicates, so the math on targeted file size is likely off,
4377 : // and we will create smaller files than expected.
4378 0 : dup_values += 1;
4379 0 : continue;
4380 0 : }
4381 :
4382 0 : let value = val.load(ctx).await?;
4383 :
4384 0 : writer.put_value(key, lsn, value, ctx).await?;
4385 :
4386 0 : prev = Some((key, lsn));
4387 : }
4388 :
4389 0 : if dup_values > 0 {
4390 0 : warn!("delta layer created with {} duplicate values", dup_values);
4391 0 : }
4392 :
4393 0 : fail_point!("delta-layer-writer-fail-before-finish", |_| {
4394 0 : Err(anyhow::anyhow!(
4395 0 : "failpoint delta-layer-writer-fail-before-finish"
4396 0 : ))
4397 0 : });
4398 :
4399 0 : let (desc, path) = writer.finish(prev.unwrap().0.next(), ctx).await?;
4400 0 : let new_delta_layer =
4401 0 : Layer::finish_creating(self.timeline.conf, &self.timeline, desc, &path)?;
4402 :
4403 0 : self.new_deltas.push(new_delta_layer);
4404 0 : Ok(())
4405 0 : }
4406 :
4407 0 : async fn delete_layer(
4408 0 : &mut self,
4409 0 : layer: &OwnArc<PersistentLayerDesc>,
4410 0 : _ctx: &RequestContext,
4411 0 : ) -> anyhow::Result<()> {
4412 0 : self.layers_to_delete.push(layer.clone().0);
4413 0 : Ok(())
4414 0 : }
4415 : }
4416 :
4417 : impl TimelineAdaptor {
4418 0 : async fn create_image_impl(
4419 0 : &mut self,
4420 0 : lsn: Lsn,
4421 0 : key_range: &Range<Key>,
4422 0 : ctx: &RequestContext,
4423 0 : ) -> Result<(), CreateImageLayersError> {
4424 0 : let timer = self.timeline.metrics.create_images_time_histo.start_timer();
4425 :
4426 0 : let image_layer_writer = ImageLayerWriter::new(
4427 0 : self.timeline.conf,
4428 0 : self.timeline.timeline_id,
4429 0 : self.timeline.tenant_shard_id,
4430 0 : key_range,
4431 0 : lsn,
4432 0 : &self.timeline.gate,
4433 0 : self.timeline.cancel.clone(),
4434 0 : ctx,
4435 0 : )
4436 0 : .await
4437 0 : .map_err(CreateImageLayersError::Other)?;
4438 :
4439 0 : fail_point!("image-layer-writer-fail-before-finish", |_| {
4440 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
4441 0 : "failpoint image-layer-writer-fail-before-finish"
4442 0 : )))
4443 0 : });
4444 :
4445 0 : let keyspace = KeySpace {
4446 0 : ranges: self
4447 0 : .get_keyspace(key_range, lsn, ctx)
4448 0 : .await
4449 0 : .map_err(CreateImageLayersError::Other)?,
4450 : };
4451 : // TODO set proper (stateful) start. The create_image_layer_for_rel_blocks function mostly
4452 0 : let outcome = self
4453 0 : .timeline
4454 0 : .create_image_layer_for_rel_blocks(
4455 0 : &keyspace,
4456 0 : image_layer_writer,
4457 0 : lsn,
4458 0 : ctx,
4459 0 : key_range.clone(),
4460 0 : IoConcurrency::sequential(),
4461 0 : None,
4462 0 : )
4463 0 : .await?;
4464 :
4465 : if let ImageLayerCreationOutcome::Generated {
4466 0 : unfinished_image_layer,
4467 0 : } = outcome
4468 : {
4469 0 : let (desc, path) = unfinished_image_layer
4470 0 : .finish(ctx)
4471 0 : .await
4472 0 : .map_err(CreateImageLayersError::Other)?;
4473 0 : let image_layer =
4474 0 : Layer::finish_creating(self.timeline.conf, &self.timeline, desc, &path)
4475 0 : .map_err(CreateImageLayersError::Other)?;
4476 0 : self.new_images.push(image_layer);
4477 0 : }
4478 :
4479 0 : timer.stop_and_record();
4480 :
4481 0 : Ok(())
4482 0 : }
4483 : }
4484 :
4485 : impl CompactionRequestContext for crate::context::RequestContext {}
4486 :
4487 : #[derive(Debug, Clone)]
4488 : pub struct OwnArc<T>(pub Arc<T>);
4489 :
4490 : impl<T> Deref for OwnArc<T> {
4491 : type Target = <Arc<T> as Deref>::Target;
4492 0 : fn deref(&self) -> &Self::Target {
4493 0 : &self.0
4494 0 : }
4495 : }
4496 :
4497 : impl<T> AsRef<T> for OwnArc<T> {
4498 0 : fn as_ref(&self) -> &T {
4499 0 : self.0.as_ref()
4500 0 : }
4501 : }
4502 :
4503 : impl CompactionLayer<Key> for OwnArc<PersistentLayerDesc> {
4504 0 : fn key_range(&self) -> &Range<Key> {
4505 0 : &self.key_range
4506 0 : }
4507 0 : fn lsn_range(&self) -> &Range<Lsn> {
4508 0 : &self.lsn_range
4509 0 : }
4510 0 : fn file_size(&self) -> u64 {
4511 0 : self.file_size
4512 0 : }
4513 0 : fn short_id(&self) -> std::string::String {
4514 0 : self.as_ref().short_id().to_string()
4515 0 : }
4516 0 : fn is_delta(&self) -> bool {
4517 0 : self.as_ref().is_delta()
4518 0 : }
4519 : }
4520 :
4521 : impl CompactionLayer<Key> for OwnArc<DeltaLayer> {
4522 0 : fn key_range(&self) -> &Range<Key> {
4523 0 : &self.layer_desc().key_range
4524 0 : }
4525 0 : fn lsn_range(&self) -> &Range<Lsn> {
4526 0 : &self.layer_desc().lsn_range
4527 0 : }
4528 0 : fn file_size(&self) -> u64 {
4529 0 : self.layer_desc().file_size
4530 0 : }
4531 0 : fn short_id(&self) -> std::string::String {
4532 0 : self.layer_desc().short_id().to_string()
4533 0 : }
4534 0 : fn is_delta(&self) -> bool {
4535 0 : true
4536 0 : }
4537 : }
4538 :
4539 : impl CompactionLayer<Key> for ResidentDeltaLayer {
4540 0 : fn key_range(&self) -> &Range<Key> {
4541 0 : &self.0.layer_desc().key_range
4542 0 : }
4543 0 : fn lsn_range(&self) -> &Range<Lsn> {
4544 0 : &self.0.layer_desc().lsn_range
4545 0 : }
4546 0 : fn file_size(&self) -> u64 {
4547 0 : self.0.layer_desc().file_size
4548 0 : }
4549 0 : fn short_id(&self) -> std::string::String {
4550 0 : self.0.layer_desc().short_id().to_string()
4551 0 : }
4552 0 : fn is_delta(&self) -> bool {
4553 0 : true
4554 0 : }
4555 : }
4556 :
4557 : impl CompactionDeltaLayer<TimelineAdaptor> for ResidentDeltaLayer {
4558 : type DeltaEntry<'a> = DeltaEntry<'a>;
4559 :
4560 0 : async fn load_keys(&self, ctx: &RequestContext) -> anyhow::Result<Vec<DeltaEntry<'_>>> {
4561 0 : self.0.get_as_delta(ctx).await?.index_entries(ctx).await
4562 0 : }
4563 : }
4564 :
4565 : impl CompactionLayer<Key> for ResidentImageLayer {
4566 0 : fn key_range(&self) -> &Range<Key> {
4567 0 : &self.0.layer_desc().key_range
4568 0 : }
4569 0 : fn lsn_range(&self) -> &Range<Lsn> {
4570 0 : &self.0.layer_desc().lsn_range
4571 0 : }
4572 0 : fn file_size(&self) -> u64 {
4573 0 : self.0.layer_desc().file_size
4574 0 : }
4575 0 : fn short_id(&self) -> std::string::String {
4576 0 : self.0.layer_desc().short_id().to_string()
4577 0 : }
4578 0 : fn is_delta(&self) -> bool {
4579 0 : false
4580 0 : }
4581 : }
4582 : impl CompactionImageLayer<TimelineAdaptor> for ResidentImageLayer {}
|