Line data Source code
1 : pub(crate) mod analysis;
2 : pub(crate) mod compaction;
3 : pub mod delete;
4 : pub(crate) mod detach_ancestor;
5 : mod eviction_task;
6 : pub(crate) mod handle;
7 : mod heatmap_layers_downloader;
8 : pub(crate) mod import_pgdata;
9 : mod init;
10 : pub mod layer_manager;
11 : pub(crate) mod logical_size;
12 : pub mod offload;
13 : pub mod span;
14 : pub mod uninit;
15 : mod walreceiver;
16 :
17 : use hashlink::LruCache;
18 : use std::array;
19 : use std::cmp::{max, min};
20 : use std::collections::btree_map::Entry;
21 : use std::collections::{BTreeMap, HashMap, HashSet};
22 : use std::ops::{ControlFlow, Deref, Range};
23 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
24 : use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
25 : use std::time::{Duration, Instant, SystemTime};
26 :
27 : use anyhow::{Context, Result, anyhow, bail, ensure};
28 : use arc_swap::{ArcSwap, ArcSwapOption};
29 : use bytes::Bytes;
30 : use camino::Utf8Path;
31 : use chrono::{DateTime, Utc};
32 : use compaction::{CompactionOutcome, GcCompactionCombinedSettings};
33 : use enumset::EnumSet;
34 : use fail::fail_point;
35 : use futures::stream::FuturesUnordered;
36 : use futures::{FutureExt, StreamExt};
37 : use handle::ShardTimelineId;
38 : use layer_manager::{
39 : LayerManagerLockHolder, LayerManagerReadGuard, LayerManagerWriteGuard, LockedLayerManager,
40 : Shutdown,
41 : };
42 :
43 : use once_cell::sync::Lazy;
44 : use pageserver_api::config::tenant_conf_defaults::DEFAULT_PITR_INTERVAL;
45 : use pageserver_api::key::{
46 : KEY_SIZE, Key, METADATA_KEY_BEGIN_PREFIX, METADATA_KEY_END_PREFIX, NON_INHERITED_RANGE,
47 : SPARSE_RANGE,
48 : };
49 : use pageserver_api::keyspace::{KeySpaceAccum, KeySpaceRandomAccum, SparseKeyPartitioning};
50 : use pageserver_api::models::{
51 : CompactKeyRange, CompactLsnRange, CompactionAlgorithm, CompactionAlgorithmSettings,
52 : DetachBehavior, DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskSpawnRequest,
53 : EvictionPolicy, InMemoryLayerInfo, LayerMapInfo, LsnLease, PageTraceEvent, RelSizeMigration,
54 : TimelineState,
55 : };
56 : use pageserver_api::reltag::{BlockNumber, RelTag};
57 : use pageserver_api::shard::{ShardIdentity, ShardIndex, ShardNumber, TenantShardId};
58 : use postgres_connection::PgConnectionConfig;
59 : use postgres_ffi::v14::xlog_utils;
60 : use postgres_ffi::{PgMajorVersion, WAL_SEGMENT_SIZE, to_pg_timestamp};
61 : use rand::Rng;
62 : use remote_storage::DownloadError;
63 : use serde_with::serde_as;
64 : use storage_broker::BrokerClientChannel;
65 : use tokio::runtime::Handle;
66 : use tokio::sync::mpsc::Sender;
67 : use tokio::sync::{Notify, oneshot, watch};
68 : use tokio_util::sync::CancellationToken;
69 : use tracing::*;
70 : use utils::generation::Generation;
71 : use utils::guard_arc_swap::GuardArcSwap;
72 : use utils::id::TimelineId;
73 : use utils::logging::{MonitorSlowFutureCallback, monitor_slow_future};
74 : use utils::lsn::{AtomicLsn, Lsn, RecordLsn};
75 : use utils::postgres_client::PostgresClientProtocol;
76 : use utils::rate_limit::RateLimit;
77 : use utils::seqwait::SeqWait;
78 : use utils::simple_rcu::{Rcu, RcuReadGuard};
79 : use utils::sync::gate::{Gate, GateGuard};
80 : use utils::{completion, critical_timeline, fs_ext, pausable_failpoint};
81 : #[cfg(test)]
82 : use wal_decoder::models::value::Value;
83 : use wal_decoder::serialized_batch::{SerializedValueBatch, ValueMeta};
84 :
85 : use self::delete::DeleteTimelineFlow;
86 : pub(super) use self::eviction_task::EvictionTaskTenantState;
87 : use self::eviction_task::EvictionTaskTimelineState;
88 : use self::logical_size::LogicalSize;
89 : use self::walreceiver::{WalReceiver, WalReceiverConf};
90 : use super::remote_timeline_client::RemoteTimelineClient;
91 : use super::remote_timeline_client::index::{GcCompactionState, IndexPart};
92 : use super::secondary::heatmap::HeatMapLayer;
93 : use super::storage_layer::{LayerFringe, LayerVisibilityHint, ReadableLayer};
94 : use super::tasks::log_compaction_error;
95 : use super::upload_queue::NotInitialized;
96 : use super::{
97 : AttachedTenantConf, GcError, HeatMapTimeline, MaybeOffloaded,
98 : debug_assert_current_span_has_tenant_and_timeline_id,
99 : };
100 : use crate::PERF_TRACE_TARGET;
101 : use crate::aux_file::AuxFileSizeEstimator;
102 : use crate::basebackup_cache::BasebackupCache;
103 : use crate::config::PageServerConf;
104 : use crate::context::{
105 : DownloadBehavior, PerfInstrumentFutureExt, RequestContext, RequestContextBuilder,
106 : };
107 : use crate::disk_usage_eviction_task::{DiskUsageEvictionInfo, EvictionCandidate, finite_f32};
108 : use crate::feature_resolver::TenantFeatureResolver;
109 : use crate::keyspace::{KeyPartitioning, KeySpace};
110 : use crate::l0_flush::{self, L0FlushGlobalState};
111 : use crate::metrics::{
112 : DELTAS_PER_READ_GLOBAL, LAYERS_PER_READ_AMORTIZED_GLOBAL, LAYERS_PER_READ_BATCH_GLOBAL,
113 : LAYERS_PER_READ_GLOBAL, ScanLatencyOngoingRecording, TimelineMetrics,
114 : };
115 : use crate::page_service::TenantManagerTypes;
116 : use crate::pgdatadir_mapping::{
117 : CalculateLogicalSizeError, CollectKeySpaceError, DirectoryKind, LsnForTimestamp,
118 : MAX_AUX_FILE_V2_DELTAS, MetricsUpdate,
119 : };
120 : use crate::task_mgr::TaskKind;
121 : use crate::tenant::config::AttachmentMode;
122 : use crate::tenant::gc_result::GcResult;
123 : use crate::tenant::layer_map::LayerMap;
124 : use crate::tenant::metadata::TimelineMetadata;
125 : use crate::tenant::storage_layer::delta_layer::DeltaEntry;
126 : use crate::tenant::storage_layer::inmemory_layer::IndexEntry;
127 : use crate::tenant::storage_layer::{
128 : AsLayerDesc, BatchLayerWriter, DeltaLayerWriter, EvictionError, ImageLayerName,
129 : ImageLayerWriter, InMemoryLayer, IoConcurrency, Layer, LayerAccessStatsReset, LayerName,
130 : PersistentLayerDesc, PersistentLayerKey, ResidentLayer, ValueReconstructSituation,
131 : ValueReconstructState, ValuesReconstructState,
132 : };
133 : use crate::tenant::tasks::BackgroundLoopKind;
134 : use crate::tenant::timeline::logical_size::CurrentLogicalSize;
135 : use crate::virtual_file::{MaybeFatalIo, VirtualFile};
136 : use crate::walingest::WalLagCooldown;
137 : use crate::walredo::RedoAttemptType;
138 : use crate::{ZERO_PAGE, task_mgr, walredo};
139 :
140 : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
141 : pub(crate) enum FlushLoopState {
142 : NotStarted,
143 : Running {
144 : #[cfg(test)]
145 : expect_initdb_optimization: bool,
146 : #[cfg(test)]
147 : initdb_optimization_count: usize,
148 : },
149 : Exited,
150 : }
151 :
152 : #[derive(Debug, Copy, Clone, PartialEq, Eq)]
153 : pub enum ImageLayerCreationMode {
154 : /// Try to create image layers based on `time_for_new_image_layer`. Used in compaction code path.
155 : Try,
156 : /// Force creating the image layers if possible. For now, no image layers will be created
157 : /// for metadata keys. Used in compaction code path with force flag enabled.
158 : Force,
159 : /// Initial ingestion of the data, and no data should be dropped in this function. This
160 : /// means that no metadata keys should be included in the partitions. Used in flush frozen layer
161 : /// code path.
162 : Initial,
163 : }
164 :
165 : #[derive(Clone, Debug, Default)]
166 : pub enum LastImageLayerCreationStatus {
167 : Incomplete {
168 : /// The last key of the partition (exclusive) that was processed in the last
169 : /// image layer creation attempt. We will continue from this key in the next
170 : /// attempt.
171 : last_key: Key,
172 : },
173 : Complete,
174 : #[default]
175 : Initial,
176 : }
177 :
178 : impl std::fmt::Display for ImageLayerCreationMode {
179 190 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 190 : write!(f, "{self:?}")
181 190 : }
182 : }
183 :
184 : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
185 : /// Can be removed after all refactors are done.
186 23 : fn drop_layer_manager_rlock(rlock: LayerManagerReadGuard<'_>) {
187 23 : drop(rlock)
188 23 : }
189 :
190 : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
191 : /// Can be removed after all refactors are done.
192 213 : fn drop_layer_manager_wlock(rlock: LayerManagerWriteGuard<'_>) {
193 213 : drop(rlock)
194 213 : }
195 :
196 : /// The outward-facing resources required to build a Timeline
197 : pub struct TimelineResources {
198 : pub remote_client: RemoteTimelineClient,
199 : pub pagestream_throttle: Arc<crate::tenant::throttle::Throttle>,
200 : pub pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
201 : pub l0_compaction_trigger: Arc<Notify>,
202 : pub l0_flush_global_state: l0_flush::L0FlushGlobalState,
203 : pub basebackup_cache: Arc<BasebackupCache>,
204 : pub feature_resolver: Arc<TenantFeatureResolver>,
205 : }
206 :
207 : pub struct Timeline {
208 : pub(crate) conf: &'static PageServerConf,
209 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
210 :
211 : myself: Weak<Self>,
212 :
213 : pub(crate) tenant_shard_id: TenantShardId,
214 : pub timeline_id: TimelineId,
215 :
216 : /// The generation of the tenant that instantiated us: this is used for safety when writing remote objects.
217 : /// Never changes for the lifetime of this [`Timeline`] object.
218 : ///
219 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
220 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
221 : pub(crate) generation: Generation,
222 :
223 : /// The detailed sharding information from our parent Tenant. This enables us to map keys
224 : /// to shards, and is constant through the lifetime of this Timeline.
225 : shard_identity: ShardIdentity,
226 :
227 : pub pg_version: PgMajorVersion,
228 :
229 : /// The tuple has two elements.
230 : /// 1. `LayerFileManager` keeps track of the various physical representations of the layer files (inmem, local, remote).
231 : /// 2. `LayerMap`, the acceleration data structure for `get_reconstruct_data`.
232 : ///
233 : /// `LayerMap` maps out the `(PAGE,LSN) / (KEY,LSN)` space, which is composed of `(KeyRange, LsnRange)` rectangles.
234 : /// We describe these rectangles through the `PersistentLayerDesc` struct.
235 : ///
236 : /// When we want to reconstruct a page, we first find the `PersistentLayerDesc`'s that we need for page reconstruction,
237 : /// using `LayerMap`. Then, we use `LayerFileManager` to get the `PersistentLayer`'s that correspond to the
238 : /// `PersistentLayerDesc`'s.
239 : ///
240 : /// Hence, it's important to keep things coherent. The `LayerFileManager` must always have an entry for all
241 : /// `PersistentLayerDesc`'s in the `LayerMap`. If it doesn't, `LayerFileManager::get_from_desc` will panic at
242 : /// runtime, e.g., during page reconstruction.
243 : ///
244 : /// In the future, we'll be able to split up the tuple of LayerMap and `LayerFileManager`,
245 : /// so that e.g. on-demand-download/eviction, and layer spreading, can operate just on `LayerFileManager`.
246 : pub(crate) layers: LockedLayerManager,
247 :
248 : last_freeze_at: AtomicLsn,
249 : // Atomic would be more appropriate here.
250 : last_freeze_ts: RwLock<Instant>,
251 :
252 : pub(crate) standby_horizon: AtomicLsn,
253 :
254 : // WAL redo manager. `None` only for broken tenants.
255 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
256 :
257 : /// Remote storage client.
258 : /// See [`remote_timeline_client`](super::remote_timeline_client) module comment for details.
259 : pub(crate) remote_client: Arc<RemoteTimelineClient>,
260 :
261 : // What page versions do we hold in the repository? If we get a
262 : // request > last_record_lsn, we need to wait until we receive all
263 : // the WAL up to the request. The SeqWait provides functions for
264 : // that. TODO: If we get a request for an old LSN, such that the
265 : // versions have already been garbage collected away, we should
266 : // throw an error, but we don't track that currently.
267 : //
268 : // last_record_lsn.load().last points to the end of last processed WAL record.
269 : //
270 : // We also remember the starting point of the previous record in
271 : // 'last_record_lsn.load().prev'. It's used to set the xl_prev pointer of the
272 : // first WAL record when the node is started up. But here, we just
273 : // keep track of it.
274 : last_record_lsn: SeqWait<RecordLsn, Lsn>,
275 :
276 : // All WAL records have been processed and stored durably on files on
277 : // local disk, up to this LSN. On crash and restart, we need to re-process
278 : // the WAL starting from this point.
279 : //
280 : // Some later WAL records might have been processed and also flushed to disk
281 : // already, so don't be surprised to see some, but there's no guarantee on
282 : // them yet.
283 : disk_consistent_lsn: AtomicLsn,
284 :
285 : // Parent timeline that this timeline was branched from, and the LSN
286 : // of the branch point.
287 : ancestor_timeline: Option<Arc<Timeline>>,
288 : ancestor_lsn: Lsn,
289 :
290 : // The LSN of gc-compaction that was last applied to this timeline.
291 : gc_compaction_state: ArcSwap<Option<GcCompactionState>>,
292 :
293 : pub(crate) metrics: Arc<TimelineMetrics>,
294 :
295 : // `Timeline` doesn't write these metrics itself, but it manages the lifetime. Code
296 : // in `crate::page_service` writes these metrics.
297 : pub(crate) query_metrics: crate::metrics::SmgrQueryTimePerTimeline,
298 :
299 : directory_metrics_inited: [AtomicBool; DirectoryKind::KINDS_NUM],
300 : directory_metrics: [AtomicU64; DirectoryKind::KINDS_NUM],
301 :
302 : /// Ensures layers aren't frozen by checkpointer between
303 : /// [`Timeline::get_layer_for_write`] and layer reads.
304 : /// Locked automatically by [`TimelineWriter`] and checkpointer.
305 : /// Must always be acquired before the layer map/individual layer lock
306 : /// to avoid deadlock.
307 : ///
308 : /// The state is cleared upon freezing.
309 : write_lock: tokio::sync::Mutex<Option<TimelineWriterState>>,
310 :
311 : /// Used to avoid multiple `flush_loop` tasks running
312 : pub(super) flush_loop_state: Mutex<FlushLoopState>,
313 :
314 : /// layer_flush_start_tx can be used to wake up the layer-flushing task.
315 : /// - The u64 value is a counter, incremented every time a new flush cycle is requested.
316 : /// The flush cycle counter is sent back on the layer_flush_done channel when
317 : /// the flush finishes. You can use that to wait for the flush to finish.
318 : /// - The LSN is updated to max() of its current value and the latest disk_consistent_lsn
319 : /// read by whoever sends an update
320 : layer_flush_start_tx: tokio::sync::watch::Sender<(u64, Lsn)>,
321 : /// to be notified when layer flushing has finished, subscribe to the layer_flush_done channel
322 : layer_flush_done_tx: tokio::sync::watch::Sender<(u64, Result<(), FlushLayerError>)>,
323 :
324 : // The LSN at which we have executed GC: whereas [`Self::gc_info`] records the LSN at which
325 : // we _intend_ to GC (i.e. the PITR cutoff), this LSN records where we actually last did it.
326 : // Because PITR interval is mutable, it's possible for this LSN to be earlier or later than
327 : // the planned GC cutoff.
328 : pub applied_gc_cutoff_lsn: Rcu<Lsn>,
329 :
330 : pub(crate) gc_compaction_layer_update_lock: tokio::sync::RwLock<()>,
331 :
332 : // List of child timelines and their branch points. This is needed to avoid
333 : // garbage collecting data that is still needed by the child timelines.
334 : pub(crate) gc_info: std::sync::RwLock<GcInfo>,
335 :
336 : pub(crate) last_image_layer_creation_status: ArcSwap<LastImageLayerCreationStatus>,
337 :
338 : // It may change across major versions so for simplicity
339 : // keep it after running initdb for a timeline.
340 : // It is needed in checks when we want to error on some operations
341 : // when they are requested for pre-initdb lsn.
342 : // It can be unified with latest_gc_cutoff_lsn under some "first_valid_lsn",
343 : // though let's keep them both for better error visibility.
344 : pub initdb_lsn: Lsn,
345 :
346 : /// The repartitioning result. Allows a single writer and multiple readers.
347 : pub(crate) partitioning: GuardArcSwap<((KeyPartitioning, SparseKeyPartitioning), Lsn)>,
348 :
349 : /// Configuration: how often should the partitioning be recalculated.
350 : repartition_threshold: u64,
351 :
352 : last_image_layer_creation_check_at: AtomicLsn,
353 : last_image_layer_creation_check_instant: std::sync::Mutex<Option<Instant>>,
354 :
355 : /// Current logical size of the "datadir", at the last LSN.
356 : current_logical_size: LogicalSize,
357 :
358 : /// Information about the last processed message by the WAL receiver,
359 : /// or None if WAL receiver has not received anything for this timeline
360 : /// yet.
361 : pub last_received_wal: Mutex<Option<WalReceiverInfo>>,
362 : pub walreceiver: Mutex<Option<WalReceiver>>,
363 :
364 : /// Relation size cache
365 : pub(crate) rel_size_latest_cache: RwLock<HashMap<RelTag, (Lsn, BlockNumber)>>,
366 : pub(crate) rel_size_snapshot_cache: Mutex<LruCache<(Lsn, RelTag), BlockNumber>>,
367 :
368 : download_all_remote_layers_task_info: RwLock<Option<DownloadRemoteLayersTaskInfo>>,
369 :
370 : state: watch::Sender<TimelineState>,
371 :
372 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
373 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
374 : pub delete_progress: TimelineDeleteProgress,
375 :
376 : eviction_task_timeline_state: tokio::sync::Mutex<EvictionTaskTimelineState>,
377 :
378 : /// Load or creation time information about the disk_consistent_lsn and when the loading
379 : /// happened. Used for consumption metrics.
380 : pub(crate) loaded_at: (Lsn, SystemTime),
381 :
382 : /// Gate to prevent shutdown completing while I/O is still happening to this timeline's data
383 : pub(crate) gate: Gate,
384 :
385 : /// Cancellation token scoped to this timeline: anything doing long-running work relating
386 : /// to the timeline should drop out when this token fires.
387 : pub(crate) cancel: CancellationToken,
388 :
389 : /// Make sure we only have one running compaction at a time in tests.
390 : ///
391 : /// Must only be taken in two places:
392 : /// - [`Timeline::compact`] (this file)
393 : /// - [`delete::delete_local_timeline_directory`]
394 : ///
395 : /// Timeline deletion will acquire both compaction and gc locks in whatever order.
396 : compaction_lock: tokio::sync::Mutex<()>,
397 :
398 : /// If true, the last compaction failed.
399 : compaction_failed: AtomicBool,
400 :
401 : /// Notifies the tenant compaction loop that there is pending L0 compaction work.
402 : l0_compaction_trigger: Arc<Notify>,
403 :
404 : /// Make sure we only have one running gc at a time.
405 : ///
406 : /// Must only be taken in two places:
407 : /// - [`Timeline::gc`] (this file)
408 : /// - [`delete::delete_local_timeline_directory`]
409 : ///
410 : /// Timeline deletion will acquire both compaction and gc locks in whatever order.
411 : gc_lock: tokio::sync::Mutex<()>,
412 :
413 : /// Cloned from [`super::TenantShard::pagestream_throttle`] on construction.
414 : pub(crate) pagestream_throttle: Arc<crate::tenant::throttle::Throttle>,
415 :
416 : /// Size estimator for aux file v2
417 : pub(crate) aux_file_size_estimator: AuxFileSizeEstimator,
418 :
419 : /// Some test cases directly place keys into the timeline without actually modifying the directory
420 : /// keys (i.e., DB_DIR). The test cases creating such keys will put the keyspaces here, so that
421 : /// these keys won't get garbage-collected during compaction/GC. This field only modifies the dense
422 : /// keyspace return value of `collect_keyspace`. For sparse keyspaces, use AUX keys for testing, and
423 : /// in the future, add `extra_test_sparse_keyspace` if necessary.
424 : #[cfg(test)]
425 : pub(crate) extra_test_dense_keyspace: ArcSwap<KeySpace>,
426 :
427 : pub(crate) l0_flush_global_state: L0FlushGlobalState,
428 :
429 : pub(crate) handles: handle::PerTimelineState<TenantManagerTypes>,
430 :
431 : pub(crate) attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
432 :
433 : /// Cf. [`crate::tenant::CreateTimelineIdempotency`].
434 : pub(crate) create_idempotency: crate::tenant::CreateTimelineIdempotency,
435 :
436 : /// If Some, collects GetPage metadata for an ongoing PageTrace.
437 : pub(crate) page_trace: ArcSwapOption<Sender<PageTraceEvent>>,
438 :
439 : pub(super) previous_heatmap: ArcSwapOption<PreviousHeatmap>,
440 :
441 : /// May host a background Tokio task which downloads all the layers from the current
442 : /// heatmap on demand.
443 : heatmap_layers_downloader: Mutex<Option<heatmap_layers_downloader::HeatmapLayersDownloader>>,
444 :
445 : pub(crate) rel_size_v2_status: ArcSwapOption<RelSizeMigration>,
446 :
447 : wait_lsn_log_slow: tokio::sync::Semaphore,
448 :
449 : /// A channel to send async requests to prepare a basebackup for the basebackup cache.
450 : basebackup_cache: Arc<BasebackupCache>,
451 :
452 : feature_resolver: Arc<TenantFeatureResolver>,
453 : }
454 :
455 : pub(crate) enum PreviousHeatmap {
456 : Active {
457 : heatmap: HeatMapTimeline,
458 : read_at: std::time::Instant,
459 : // End LSN covered by the heatmap if known
460 : end_lsn: Option<Lsn>,
461 : },
462 : Obsolete,
463 : }
464 :
465 : pub type TimelineDeleteProgress = Arc<tokio::sync::Mutex<DeleteTimelineFlow>>;
466 :
467 : pub struct WalReceiverInfo {
468 : pub wal_source_connconf: PgConnectionConfig,
469 : pub last_received_msg_lsn: Lsn,
470 : pub last_received_msg_ts: u128,
471 : }
472 :
473 : /// Information about how much history needs to be retained, needed by
474 : /// Garbage Collection.
475 : #[derive(Default)]
476 : pub(crate) struct GcInfo {
477 : /// Specific LSNs that are needed.
478 : ///
479 : /// Currently, this includes all points where child branches have
480 : /// been forked off from. In the future, could also include
481 : /// explicit user-defined snapshot points.
482 : pub(crate) retain_lsns: Vec<(Lsn, TimelineId, MaybeOffloaded)>,
483 :
484 : /// The cutoff coordinates, which are combined by selecting the minimum.
485 : pub(crate) cutoffs: GcCutoffs,
486 :
487 : /// Leases granted to particular LSNs.
488 : pub(crate) leases: BTreeMap<Lsn, LsnLease>,
489 :
490 : /// Whether our branch point is within our ancestor's PITR interval (for cost estimation)
491 : pub(crate) within_ancestor_pitr: bool,
492 : }
493 :
494 : impl GcInfo {
495 154 : pub(crate) fn min_cutoff(&self) -> Lsn {
496 154 : self.cutoffs.select_min()
497 154 : }
498 :
499 119 : pub(super) fn insert_child(
500 119 : &mut self,
501 119 : child_id: TimelineId,
502 119 : child_lsn: Lsn,
503 119 : is_offloaded: MaybeOffloaded,
504 119 : ) {
505 119 : self.retain_lsns.push((child_lsn, child_id, is_offloaded));
506 119 : self.retain_lsns.sort_by_key(|i| i.0);
507 119 : }
508 :
509 2 : pub(super) fn remove_child_maybe_offloaded(
510 2 : &mut self,
511 2 : child_id: TimelineId,
512 2 : maybe_offloaded: MaybeOffloaded,
513 2 : ) -> bool {
514 : // Remove at most one element. Needed for correctness if there is two live `Timeline` objects referencing
515 : // the same timeline. Shouldn't but maybe can occur when Arc's live longer than intended.
516 2 : let mut removed = false;
517 3 : self.retain_lsns.retain(|i| {
518 3 : if removed {
519 1 : return true;
520 2 : }
521 2 : let remove = i.1 == child_id && i.2 == maybe_offloaded;
522 2 : removed |= remove;
523 2 : !remove
524 3 : });
525 2 : removed
526 2 : }
527 :
528 2 : pub(super) fn remove_child_not_offloaded(&mut self, child_id: TimelineId) -> bool {
529 2 : self.remove_child_maybe_offloaded(child_id, MaybeOffloaded::No)
530 2 : }
531 :
532 0 : pub(super) fn remove_child_offloaded(&mut self, child_id: TimelineId) -> bool {
533 0 : self.remove_child_maybe_offloaded(child_id, MaybeOffloaded::Yes)
534 0 : }
535 119 : pub(crate) fn lsn_covered_by_lease(&self, lsn: Lsn) -> bool {
536 119 : self.leases.contains_key(&lsn)
537 119 : }
538 : }
539 :
540 : /// The `GcInfo` component describing which Lsns need to be retained. Functionally, this
541 : /// is a single number (the oldest LSN which we must retain), but it internally distinguishes
542 : /// between time-based and space-based retention for observability and consumption metrics purposes.
543 : #[derive(Clone, Debug, Default)]
544 : pub(crate) struct GcCutoffs {
545 : /// Calculated from the [`pageserver_api::models::TenantConfig::gc_horizon`], this LSN indicates how much
546 : /// history we must keep to retain a specified number of bytes of WAL.
547 : pub(crate) space: Lsn,
548 :
549 : /// Calculated from [`pageserver_api::models::TenantConfig::pitr_interval`], this LSN indicates
550 : /// how much history we must keep to enable reading back at least the PITR interval duration.
551 : ///
552 : /// None indicates that the PITR cutoff has not been computed. A PITR interval of 0 will yield
553 : /// Some(last_record_lsn).
554 : pub(crate) time: Option<Lsn>,
555 : }
556 :
557 : impl GcCutoffs {
558 154 : fn select_min(&self) -> Lsn {
559 : // NB: if we haven't computed the PITR cutoff yet, we can't GC anything.
560 154 : self.space.min(self.time.unwrap_or_default())
561 154 : }
562 : }
563 :
564 : pub(crate) struct TimelineVisitOutcome {
565 : completed_keyspace: KeySpace,
566 : image_covered_keyspace: KeySpace,
567 : }
568 :
569 : /// An error happened in a get() operation.
570 : #[derive(thiserror::Error, Debug)]
571 : pub(crate) enum PageReconstructError {
572 : #[error(transparent)]
573 : Other(anyhow::Error),
574 :
575 : #[error("Ancestor LSN wait error: {0}")]
576 : AncestorLsnTimeout(WaitLsnError),
577 :
578 : #[error("timeline shutting down")]
579 : Cancelled,
580 :
581 : /// An error happened replaying WAL records
582 : #[error(transparent)]
583 : WalRedo(anyhow::Error),
584 :
585 : #[error("{0}")]
586 : MissingKey(Box<MissingKeyError>),
587 : }
588 :
589 : impl From<anyhow::Error> for PageReconstructError {
590 1 : fn from(value: anyhow::Error) -> Self {
591 : // with walingest.rs many PageReconstructError are wrapped in as anyhow::Error
592 1 : match value.downcast::<PageReconstructError>() {
593 0 : Ok(pre) => pre,
594 1 : Err(other) => PageReconstructError::Other(other),
595 : }
596 1 : }
597 : }
598 :
599 : impl From<utils::bin_ser::DeserializeError> for PageReconstructError {
600 0 : fn from(value: utils::bin_ser::DeserializeError) -> Self {
601 0 : PageReconstructError::Other(anyhow::Error::new(value).context("deserialization failure"))
602 0 : }
603 : }
604 :
605 : impl From<layer_manager::Shutdown> for PageReconstructError {
606 0 : fn from(_: layer_manager::Shutdown) -> Self {
607 0 : PageReconstructError::Cancelled
608 0 : }
609 : }
610 :
611 : impl GetVectoredError {
612 : #[cfg(test)]
613 3 : pub(crate) fn is_missing_key_error(&self) -> bool {
614 3 : matches!(self, Self::MissingKey(_))
615 3 : }
616 : }
617 :
618 : impl From<layer_manager::Shutdown> for GetVectoredError {
619 0 : fn from(_: layer_manager::Shutdown) -> Self {
620 0 : GetVectoredError::Cancelled
621 0 : }
622 : }
623 :
624 : /// A layer identifier when used in the [`ReadPath`] structure. This enum is for observability purposes
625 : /// only and not used by the "real read path".
626 : pub enum ReadPathLayerId {
627 : PersistentLayer(PersistentLayerKey),
628 : InMemoryLayer(Range<Lsn>),
629 : }
630 :
631 : impl std::fmt::Display for ReadPathLayerId {
632 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
633 0 : match self {
634 0 : ReadPathLayerId::PersistentLayer(key) => write!(f, "{key}"),
635 0 : ReadPathLayerId::InMemoryLayer(range) => {
636 0 : write!(f, "in-mem {}..{}", range.start, range.end)
637 : }
638 : }
639 0 : }
640 : }
641 : pub struct ReadPath {
642 : keyspace: KeySpace,
643 : lsn: Lsn,
644 : path: Vec<(ReadPathLayerId, KeySpace, Range<Lsn>)>,
645 : }
646 :
647 : impl ReadPath {
648 312344 : pub fn new(keyspace: KeySpace, lsn: Lsn) -> Self {
649 312344 : Self {
650 312344 : keyspace,
651 312344 : lsn,
652 312344 : path: Vec::new(),
653 312344 : }
654 312344 : }
655 :
656 445674 : pub fn record_layer_visit(
657 445674 : &mut self,
658 445674 : layer_to_read: &ReadableLayer,
659 445674 : keyspace_to_read: &KeySpace,
660 445674 : lsn_range: &Range<Lsn>,
661 445674 : ) {
662 445674 : let id = match layer_to_read {
663 138471 : ReadableLayer::PersistentLayer(layer) => {
664 138471 : ReadPathLayerId::PersistentLayer(layer.layer_desc().key())
665 : }
666 307203 : ReadableLayer::InMemoryLayer(layer) => {
667 307203 : ReadPathLayerId::InMemoryLayer(layer.get_lsn_range())
668 : }
669 : };
670 445674 : self.path
671 445674 : .push((id, keyspace_to_read.clone(), lsn_range.clone()));
672 445674 : }
673 : }
674 :
675 : impl std::fmt::Display for ReadPath {
676 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
677 0 : writeln!(f, "Read path for {} at lsn {}:", self.keyspace, self.lsn)?;
678 0 : for (idx, (layer_id, keyspace, lsn_range)) in self.path.iter().enumerate() {
679 0 : writeln!(
680 0 : f,
681 0 : "{}: {} {}..{} {}",
682 : idx, layer_id, lsn_range.start, lsn_range.end, keyspace
683 0 : )?;
684 : }
685 0 : Ok(())
686 0 : }
687 : }
688 :
689 : #[derive(thiserror::Error)]
690 : pub struct MissingKeyError {
691 : keyspace: KeySpace,
692 : shard: ShardNumber,
693 : query: Option<VersionedKeySpaceQuery>,
694 : // This is largest request LSN from the get page request batch
695 : original_hwm_lsn: Lsn,
696 : ancestor_lsn: Option<Lsn>,
697 : /// Debug information about the read path if there's an error
698 : read_path: Option<ReadPath>,
699 : backtrace: Option<std::backtrace::Backtrace>,
700 : }
701 :
702 : impl MissingKeyError {
703 7 : fn enrich(&mut self, query: VersionedKeySpaceQuery) {
704 7 : self.query = Some(query);
705 7 : }
706 : }
707 :
708 : impl std::fmt::Debug for MissingKeyError {
709 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
710 0 : write!(f, "{self}")
711 0 : }
712 : }
713 :
714 : impl std::fmt::Display for MissingKeyError {
715 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716 0 : write!(
717 0 : f,
718 0 : "could not find data for key {} (shard {:?}), original HWM LSN {}",
719 : self.keyspace, self.shard, self.original_hwm_lsn
720 0 : )?;
721 :
722 0 : if let Some(ref ancestor_lsn) = self.ancestor_lsn {
723 0 : write!(f, ", ancestor {ancestor_lsn}")?;
724 0 : }
725 :
726 0 : if let Some(ref query) = self.query {
727 0 : write!(f, ", query {query}")?;
728 0 : }
729 :
730 0 : if let Some(ref read_path) = self.read_path {
731 0 : write!(f, "\n{read_path}")?;
732 0 : }
733 :
734 0 : if let Some(ref backtrace) = self.backtrace {
735 0 : write!(f, "\n{backtrace}")?;
736 0 : }
737 :
738 0 : Ok(())
739 0 : }
740 : }
741 :
742 : impl PageReconstructError {
743 : /// Returns true if this error indicates a tenant/timeline shutdown alike situation
744 0 : pub(crate) fn is_stopping(&self) -> bool {
745 : use PageReconstructError::*;
746 0 : match self {
747 0 : Cancelled => true,
748 0 : Other(_) | AncestorLsnTimeout(_) | WalRedo(_) | MissingKey(_) => false,
749 : }
750 0 : }
751 : }
752 :
753 : #[derive(thiserror::Error, Debug)]
754 : pub(crate) enum CreateImageLayersError {
755 : #[error("timeline shutting down")]
756 : Cancelled,
757 :
758 : #[error("read failed")]
759 : GetVectoredError(#[source] GetVectoredError),
760 :
761 : #[error("reconstruction failed")]
762 : PageReconstructError(#[source] PageReconstructError),
763 :
764 : #[error(transparent)]
765 : Other(anyhow::Error),
766 : }
767 :
768 : impl From<layer_manager::Shutdown> for CreateImageLayersError {
769 0 : fn from(_: layer_manager::Shutdown) -> Self {
770 0 : CreateImageLayersError::Cancelled
771 0 : }
772 : }
773 :
774 : #[derive(thiserror::Error, Debug, Clone)]
775 : pub(crate) enum FlushLayerError {
776 : /// Timeline cancellation token was cancelled
777 : #[error("timeline shutting down")]
778 : Cancelled,
779 :
780 : /// We tried to flush a layer while the Timeline is in an unexpected state
781 : #[error("cannot flush frozen layers when flush_loop is not running, state is {0:?}")]
782 : NotRunning(FlushLoopState),
783 :
784 : // Arc<> the following non-clonable error types: we must be Clone-able because the flush error is propagated from the flush
785 : // loop via a watch channel, where we can only borrow it.
786 : #[error("create image layers (shared)")]
787 : CreateImageLayersError(Arc<CreateImageLayersError>),
788 :
789 : #[error("other (shared)")]
790 : Other(#[from] Arc<anyhow::Error>),
791 : }
792 :
793 : impl FlushLayerError {
794 : // When crossing from generic anyhow errors to this error type, we explicitly check
795 : // for timeline cancellation to avoid logging inoffensive shutdown errors as warn/err.
796 0 : fn from_anyhow(timeline: &Timeline, err: anyhow::Error) -> Self {
797 0 : let cancelled = timeline.cancel.is_cancelled()
798 : // The upload queue might have been shut down before the official cancellation of the timeline.
799 0 : || err
800 0 : .downcast_ref::<NotInitialized>()
801 0 : .map(NotInitialized::is_stopping)
802 0 : .unwrap_or_default();
803 0 : if cancelled {
804 0 : Self::Cancelled
805 : } else {
806 0 : Self::Other(Arc::new(err))
807 : }
808 0 : }
809 : }
810 :
811 : impl From<layer_manager::Shutdown> for FlushLayerError {
812 0 : fn from(_: layer_manager::Shutdown) -> Self {
813 0 : FlushLayerError::Cancelled
814 0 : }
815 : }
816 :
817 : #[derive(thiserror::Error, Debug)]
818 : pub enum GetVectoredError {
819 : #[error("timeline shutting down")]
820 : Cancelled,
821 :
822 : #[error("requested too many keys: {0} > {1}")]
823 : Oversized(u64, u64),
824 :
825 : #[error("requested at invalid LSN: {0}")]
826 : InvalidLsn(Lsn),
827 :
828 : #[error("requested key not found: {0}")]
829 : MissingKey(Box<MissingKeyError>),
830 :
831 : #[error("ancestry walk")]
832 : GetReadyAncestorError(#[source] GetReadyAncestorError),
833 :
834 : #[error(transparent)]
835 : Other(#[from] anyhow::Error),
836 : }
837 :
838 : impl From<GetReadyAncestorError> for GetVectoredError {
839 1 : fn from(value: GetReadyAncestorError) -> Self {
840 : use GetReadyAncestorError::*;
841 1 : match value {
842 0 : Cancelled => GetVectoredError::Cancelled,
843 : AncestorLsnTimeout(_) | BadState { .. } => {
844 1 : GetVectoredError::GetReadyAncestorError(value)
845 : }
846 : }
847 1 : }
848 : }
849 :
850 : #[derive(thiserror::Error, Debug)]
851 : pub enum GetReadyAncestorError {
852 : #[error("ancestor LSN wait error")]
853 : AncestorLsnTimeout(#[from] WaitLsnError),
854 :
855 : #[error("bad state on timeline {timeline_id}: {state:?}")]
856 : BadState {
857 : timeline_id: TimelineId,
858 : state: TimelineState,
859 : },
860 :
861 : #[error("cancelled")]
862 : Cancelled,
863 : }
864 :
865 : #[derive(Clone, Copy)]
866 : pub enum LogicalSizeCalculationCause {
867 : Initial,
868 : ConsumptionMetricsSyntheticSize,
869 : EvictionTaskImitation,
870 : TenantSizeHandler,
871 : }
872 :
873 : pub enum GetLogicalSizePriority {
874 : User,
875 : Background,
876 : }
877 :
878 : #[derive(Debug, enumset::EnumSetType)]
879 : pub(crate) enum CompactFlags {
880 : ForceRepartition,
881 : ForceImageLayerCreation,
882 : ForceL0Compaction,
883 : OnlyL0Compaction,
884 : EnhancedGcBottomMostCompaction,
885 : DryRun,
886 : /// Makes image compaction yield if there's pending L0 compaction. This should always be used in
887 : /// the background compaction task, since we want to aggressively compact down L0 to bound
888 : /// read amplification.
889 : ///
890 : /// It only makes sense to use this when `compaction_l0_first` is enabled (such that we yield to
891 : /// an L0 compaction pass), and without `OnlyL0Compaction` (L0 compaction shouldn't yield for L0
892 : /// compaction).
893 : YieldForL0,
894 : }
895 :
896 : #[serde_with::serde_as]
897 0 : #[derive(Debug, Clone, serde::Deserialize)]
898 : pub(crate) struct CompactRequest {
899 : pub compact_key_range: Option<CompactKeyRange>,
900 : pub compact_lsn_range: Option<CompactLsnRange>,
901 : /// Whether the compaction job should be scheduled.
902 : #[serde(default)]
903 : pub scheduled: bool,
904 : /// Whether the compaction job should be split across key ranges.
905 : #[serde(default)]
906 : pub sub_compaction: bool,
907 : /// Max job size for each subcompaction job.
908 : pub sub_compaction_max_job_size_mb: Option<u64>,
909 : }
910 :
911 0 : #[derive(Debug, Clone, serde::Deserialize)]
912 : pub(crate) struct MarkInvisibleRequest {
913 : #[serde(default)]
914 : pub is_visible: Option<bool>,
915 : }
916 :
917 : #[derive(Debug, Clone, Default)]
918 : pub(crate) struct CompactOptions {
919 : pub flags: EnumSet<CompactFlags>,
920 : /// If set, the compaction will only compact the key range specified by this option.
921 : /// This option is only used by GC compaction. For the full explanation, see [`compaction::GcCompactJob`].
922 : pub compact_key_range: Option<CompactKeyRange>,
923 : /// If set, the compaction will only compact the LSN within this value.
924 : /// This option is only used by GC compaction. For the full explanation, see [`compaction::GcCompactJob`].
925 : pub compact_lsn_range: Option<CompactLsnRange>,
926 : /// Enable sub-compaction (split compaction job across key ranges).
927 : /// This option is only used by GC compaction.
928 : pub sub_compaction: bool,
929 : /// Set job size for the GC compaction.
930 : /// This option is only used by GC compaction.
931 : pub sub_compaction_max_job_size_mb: Option<u64>,
932 : }
933 :
934 : impl std::fmt::Debug for Timeline {
935 0 : fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
936 0 : write!(f, "Timeline<{}>", self.timeline_id)
937 0 : }
938 : }
939 :
940 : #[derive(thiserror::Error, Debug, Clone)]
941 : pub enum WaitLsnError {
942 : // Called on a timeline which is shutting down
943 : #[error("Shutdown")]
944 : Shutdown,
945 :
946 : // Called on an timeline not in active state or shutting down
947 : #[error("Bad timeline state: {0:?}")]
948 : BadState(TimelineState),
949 :
950 : // Timeout expired while waiting for LSN to catch up with goal.
951 : #[error("{0}")]
952 : Timeout(String),
953 : }
954 :
955 : impl From<WaitLsnError> for tonic::Status {
956 0 : fn from(err: WaitLsnError) -> Self {
957 : use tonic::Code;
958 0 : let code = match &err {
959 0 : WaitLsnError::Timeout(_) => Code::Internal,
960 0 : WaitLsnError::BadState(_) => Code::Internal,
961 0 : WaitLsnError::Shutdown => Code::Unavailable,
962 : };
963 0 : tonic::Status::new(code, err.to_string())
964 0 : }
965 : }
966 :
967 : // The impls below achieve cancellation mapping for errors.
968 : // Perhaps there's a way of achieving this with less cruft.
969 :
970 : impl From<CreateImageLayersError> for CompactionError {
971 0 : fn from(e: CreateImageLayersError) -> Self {
972 0 : match e {
973 0 : CreateImageLayersError::Cancelled => CompactionError::ShuttingDown,
974 0 : CreateImageLayersError::Other(e) => {
975 0 : CompactionError::Other(e.context("create image layers"))
976 : }
977 0 : _ => CompactionError::Other(e.into()),
978 : }
979 0 : }
980 : }
981 :
982 : impl From<CreateImageLayersError> for FlushLayerError {
983 0 : fn from(e: CreateImageLayersError) -> Self {
984 0 : match e {
985 0 : CreateImageLayersError::Cancelled => FlushLayerError::Cancelled,
986 0 : any => FlushLayerError::CreateImageLayersError(Arc::new(any)),
987 : }
988 0 : }
989 : }
990 :
991 : impl From<PageReconstructError> for CreateImageLayersError {
992 0 : fn from(e: PageReconstructError) -> Self {
993 0 : match e {
994 0 : PageReconstructError::Cancelled => CreateImageLayersError::Cancelled,
995 0 : _ => CreateImageLayersError::PageReconstructError(e),
996 : }
997 0 : }
998 : }
999 :
1000 : impl From<super::storage_layer::errors::PutError> for CreateImageLayersError {
1001 0 : fn from(e: super::storage_layer::errors::PutError) -> Self {
1002 0 : if e.is_cancel() {
1003 0 : CreateImageLayersError::Cancelled
1004 : } else {
1005 0 : CreateImageLayersError::Other(e.into_anyhow())
1006 : }
1007 0 : }
1008 : }
1009 :
1010 : impl From<GetVectoredError> for CreateImageLayersError {
1011 0 : fn from(e: GetVectoredError) -> Self {
1012 0 : match e {
1013 0 : GetVectoredError::Cancelled => CreateImageLayersError::Cancelled,
1014 0 : _ => CreateImageLayersError::GetVectoredError(e),
1015 : }
1016 0 : }
1017 : }
1018 :
1019 : impl From<GetVectoredError> for PageReconstructError {
1020 3 : fn from(e: GetVectoredError) -> Self {
1021 3 : match e {
1022 0 : GetVectoredError::Cancelled => PageReconstructError::Cancelled,
1023 0 : GetVectoredError::InvalidLsn(_) => PageReconstructError::Other(anyhow!("Invalid LSN")),
1024 0 : err @ GetVectoredError::Oversized(_, _) => PageReconstructError::Other(err.into()),
1025 2 : GetVectoredError::MissingKey(err) => PageReconstructError::MissingKey(err),
1026 1 : GetVectoredError::GetReadyAncestorError(err) => PageReconstructError::from(err),
1027 0 : GetVectoredError::Other(err) => PageReconstructError::Other(err),
1028 : }
1029 3 : }
1030 : }
1031 :
1032 : impl From<GetReadyAncestorError> for PageReconstructError {
1033 1 : fn from(e: GetReadyAncestorError) -> Self {
1034 : use GetReadyAncestorError::*;
1035 1 : match e {
1036 0 : AncestorLsnTimeout(wait_err) => PageReconstructError::AncestorLsnTimeout(wait_err),
1037 1 : bad_state @ BadState { .. } => PageReconstructError::Other(anyhow::anyhow!(bad_state)),
1038 0 : Cancelled => PageReconstructError::Cancelled,
1039 : }
1040 1 : }
1041 : }
1042 :
1043 : pub(crate) enum WaitLsnTimeout {
1044 : Custom(Duration),
1045 : // Use the [`PageServerConf::wait_lsn_timeout`] default
1046 : Default,
1047 : }
1048 :
1049 : pub(crate) enum WaitLsnWaiter<'a> {
1050 : Timeline(&'a Timeline),
1051 : Tenant,
1052 : PageService,
1053 : HttpEndpoint,
1054 : BaseBackupCache,
1055 : }
1056 :
1057 : /// Argument to [`Timeline::shutdown`].
1058 : #[derive(Debug, Clone, Copy)]
1059 : pub(crate) enum ShutdownMode {
1060 : /// Graceful shutdown, may do a lot of I/O as we flush any open layers to disk. This method can
1061 : /// take multiple seconds for a busy timeline.
1062 : ///
1063 : /// While we are flushing, we continue to accept read I/O for LSNs ingested before
1064 : /// the call to [`Timeline::shutdown`].
1065 : FreezeAndFlush,
1066 : /// Only flush the layers to the remote storage without freezing any open layers. Flush the deletion
1067 : /// queue. This is the mode used by ancestor detach and any other operations that reloads a tenant
1068 : /// but not increasing the generation number. Note that this mode cannot be used at tenant shutdown,
1069 : /// as flushing the deletion queue at that time will cause shutdown-in-progress errors.
1070 : Reload,
1071 : /// Shut down immediately, without waiting for any open layers to flush.
1072 : Hard,
1073 : }
1074 :
1075 : #[allow(clippy::large_enum_variant, reason = "TODO")]
1076 : enum ImageLayerCreationOutcome {
1077 : /// We generated an image layer
1078 : Generated {
1079 : unfinished_image_layer: ImageLayerWriter,
1080 : },
1081 : /// The key range is empty
1082 : Empty,
1083 : /// (Only used in metadata image layer creation), after reading the metadata keys, we decide to skip
1084 : /// the image layer creation.
1085 : Skip,
1086 : }
1087 :
1088 : /// Public interface functions
1089 : impl Timeline {
1090 : /// Get the LSN where this branch was created
1091 23 : pub(crate) fn get_ancestor_lsn(&self) -> Lsn {
1092 23 : self.ancestor_lsn
1093 23 : }
1094 :
1095 : /// Get the ancestor's timeline id
1096 416 : pub(crate) fn get_ancestor_timeline_id(&self) -> Option<TimelineId> {
1097 416 : self.ancestor_timeline
1098 416 : .as_ref()
1099 416 : .map(|ancestor| ancestor.timeline_id)
1100 416 : }
1101 :
1102 : /// Get the ancestor timeline
1103 1 : pub(crate) fn ancestor_timeline(&self) -> Option<&Arc<Timeline>> {
1104 1 : self.ancestor_timeline.as_ref()
1105 1 : }
1106 :
1107 : /// Get the bytes written since the PITR cutoff on this branch, and
1108 : /// whether this branch's ancestor_lsn is within its parent's PITR.
1109 0 : pub(crate) fn get_pitr_history_stats(&self) -> (u64, bool) {
1110 : // TODO: for backwards compatibility, we return the full history back to 0 when the PITR
1111 : // cutoff has not yet been initialized. This should return None instead, but this is exposed
1112 : // in external HTTP APIs and callers may not handle a null value.
1113 0 : let gc_info = self.gc_info.read().unwrap();
1114 0 : let history = self
1115 0 : .get_last_record_lsn()
1116 0 : .checked_sub(gc_info.cutoffs.time.unwrap_or_default())
1117 0 : .unwrap_or_default()
1118 0 : .0;
1119 0 : (history, gc_info.within_ancestor_pitr)
1120 0 : }
1121 :
1122 : /// Read timeline's GC cutoff: this is the LSN at which GC has started to happen
1123 425460 : pub(crate) fn get_applied_gc_cutoff_lsn(&self) -> RcuReadGuard<Lsn> {
1124 425460 : self.applied_gc_cutoff_lsn.read()
1125 425460 : }
1126 :
1127 : /// Read timeline's planned GC cutoff: this is the logical end of history that users are allowed
1128 : /// to read (based on configured PITR), even if physically we have more history. Returns None
1129 : /// if the PITR cutoff has not yet been initialized.
1130 0 : pub(crate) fn get_gc_cutoff_lsn(&self) -> Option<Lsn> {
1131 0 : self.gc_info.read().unwrap().cutoffs.time
1132 0 : }
1133 :
1134 : /// Look up given page version.
1135 : ///
1136 : /// If a remote layer file is needed, it is downloaded as part of this
1137 : /// call.
1138 : ///
1139 : /// This method enforces [`Self::pagestream_throttle`] internally.
1140 : ///
1141 : /// NOTE: It is considered an error to 'get' a key that doesn't exist. The
1142 : /// abstraction above this needs to store suitable metadata to track what
1143 : /// data exists with what keys, in separate metadata entries. If a
1144 : /// non-existent key is requested, we may incorrectly return a value from
1145 : /// an ancestor branch, for example, or waste a lot of cycles chasing the
1146 : /// non-existing key.
1147 : ///
1148 : /// # Cancel-Safety
1149 : ///
1150 : /// This method is cancellation-safe.
1151 : #[inline(always)]
1152 301263 : pub(crate) async fn get(
1153 301263 : &self,
1154 301263 : key: Key,
1155 301263 : lsn: Lsn,
1156 301263 : ctx: &RequestContext,
1157 301263 : ) -> Result<Bytes, PageReconstructError> {
1158 301263 : if !lsn.is_valid() {
1159 0 : return Err(PageReconstructError::Other(anyhow::anyhow!("Invalid LSN")));
1160 301263 : }
1161 :
1162 : // This check is debug-only because of the cost of hashing, and because it's a double-check: we
1163 : // already checked the key against the shard_identity when looking up the Timeline from
1164 : // page_service.
1165 301263 : debug_assert!(!self.shard_identity.is_key_disposable(&key));
1166 :
1167 301263 : let mut reconstruct_state = ValuesReconstructState::new(IoConcurrency::sequential());
1168 :
1169 301263 : let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
1170 :
1171 301263 : let vectored_res = self
1172 301263 : .get_vectored_impl(query, &mut reconstruct_state, ctx)
1173 301263 : .await;
1174 :
1175 301263 : let key_value = vectored_res?.pop_first();
1176 301260 : match key_value {
1177 301254 : Some((got_key, value)) => {
1178 301254 : if got_key != key {
1179 0 : error!(
1180 0 : "Expected {}, but singular vectored get returned {}",
1181 : key, got_key
1182 : );
1183 0 : Err(PageReconstructError::Other(anyhow!(
1184 0 : "Singular vectored get returned wrong key"
1185 0 : )))
1186 : } else {
1187 301254 : value
1188 : }
1189 : }
1190 6 : None => Err(PageReconstructError::MissingKey(Box::new(
1191 6 : MissingKeyError {
1192 6 : keyspace: KeySpace::single(key..key.next()),
1193 6 : shard: self.shard_identity.get_shard_number(&key),
1194 6 : original_hwm_lsn: lsn,
1195 6 : ancestor_lsn: None,
1196 6 : backtrace: None,
1197 6 : read_path: None,
1198 6 : query: None,
1199 6 : },
1200 6 : ))),
1201 : }
1202 301263 : }
1203 :
1204 : pub(crate) const LAYERS_VISITED_WARN_THRESHOLD: u32 = 100;
1205 :
1206 : /// Look up multiple page versions at a given LSN
1207 : ///
1208 : /// This naive implementation will be replaced with a more efficient one
1209 : /// which actually vectorizes the read path.
1210 10888 : pub(crate) async fn get_vectored(
1211 10888 : &self,
1212 10888 : query: VersionedKeySpaceQuery,
1213 10888 : io_concurrency: super::storage_layer::IoConcurrency,
1214 10888 : ctx: &RequestContext,
1215 10888 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1216 10888 : let total_keyspace = query.total_keyspace();
1217 :
1218 10888 : let key_count = total_keyspace.total_raw_size();
1219 10888 : if key_count > self.conf.max_get_vectored_keys.get() {
1220 0 : return Err(GetVectoredError::Oversized(
1221 0 : key_count as u64,
1222 0 : self.conf.max_get_vectored_keys.get() as u64,
1223 0 : ));
1224 10888 : }
1225 :
1226 34195 : for range in &total_keyspace.ranges {
1227 23307 : let mut key = range.start;
1228 65329 : while key != range.end {
1229 42022 : assert!(!self.shard_identity.is_key_disposable(&key));
1230 42022 : key = key.next();
1231 : }
1232 : }
1233 :
1234 10888 : trace!(
1235 0 : "get vectored query {} from task kind {:?}",
1236 : query,
1237 0 : ctx.task_kind(),
1238 : );
1239 :
1240 10888 : let start = crate::metrics::GET_VECTORED_LATENCY
1241 10888 : .for_task_kind(ctx.task_kind())
1242 10888 : .map(|metric| (metric, Instant::now()));
1243 :
1244 10888 : let res = self
1245 10888 : .get_vectored_impl(query, &mut ValuesReconstructState::new(io_concurrency), ctx)
1246 10888 : .await;
1247 :
1248 10888 : if let Some((metric, start)) = start {
1249 0 : let elapsed = start.elapsed();
1250 0 : metric.observe(elapsed.as_secs_f64());
1251 10888 : }
1252 :
1253 10888 : res
1254 10888 : }
1255 :
1256 : /// Scan the keyspace and return all existing key-values in the keyspace. This currently uses vectored
1257 : /// get underlying. Normal vectored get would throw an error when a key in the keyspace is not found
1258 : /// during the search, but for the scan interface, it returns all existing key-value pairs, and does
1259 : /// not expect each single key in the key space will be found. The semantics is closer to the RocksDB
1260 : /// scan iterator interface. We could optimize this interface later to avoid some checks in the vectored
1261 : /// get path to maintain and split the probing and to-be-probe keyspace. We also need to ensure that
1262 : /// the scan operation will not cause OOM in the future.
1263 8 : pub(crate) async fn scan(
1264 8 : &self,
1265 8 : keyspace: KeySpace,
1266 8 : lsn: Lsn,
1267 8 : ctx: &RequestContext,
1268 8 : io_concurrency: super::storage_layer::IoConcurrency,
1269 8 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1270 8 : if !lsn.is_valid() {
1271 0 : return Err(GetVectoredError::InvalidLsn(lsn));
1272 8 : }
1273 :
1274 8 : trace!(
1275 0 : "key-value scan request for {:?}@{} from task kind {:?}",
1276 : keyspace,
1277 : lsn,
1278 0 : ctx.task_kind()
1279 : );
1280 :
1281 : // We should generalize this into Keyspace::contains in the future.
1282 16 : for range in &keyspace.ranges {
1283 8 : if range.start.field1 < METADATA_KEY_BEGIN_PREFIX
1284 8 : || range.end.field1 > METADATA_KEY_END_PREFIX
1285 : {
1286 0 : return Err(GetVectoredError::Other(anyhow::anyhow!(
1287 0 : "only metadata keyspace can be scanned"
1288 0 : )));
1289 8 : }
1290 : }
1291 :
1292 8 : let start = crate::metrics::SCAN_LATENCY
1293 8 : .for_task_kind(ctx.task_kind())
1294 8 : .map(ScanLatencyOngoingRecording::start_recording);
1295 :
1296 8 : let query = VersionedKeySpaceQuery::uniform(keyspace, lsn);
1297 :
1298 8 : let vectored_res = self
1299 8 : .get_vectored_impl(query, &mut ValuesReconstructState::new(io_concurrency), ctx)
1300 8 : .await;
1301 :
1302 8 : if let Some(recording) = start {
1303 0 : recording.observe();
1304 8 : }
1305 :
1306 8 : vectored_res
1307 8 : }
1308 :
1309 312344 : pub(super) async fn get_vectored_impl(
1310 312344 : &self,
1311 312344 : query: VersionedKeySpaceQuery,
1312 312344 : reconstruct_state: &mut ValuesReconstructState,
1313 312344 : ctx: &RequestContext,
1314 312344 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1315 312344 : if query.is_empty() {
1316 0 : return Ok(BTreeMap::default());
1317 312344 : }
1318 :
1319 312344 : let read_path = if self.conf.enable_read_path_debugging || ctx.read_path_debug() {
1320 312344 : Some(ReadPath::new(
1321 312344 : query.total_keyspace(),
1322 312344 : query.high_watermark_lsn()?,
1323 : ))
1324 : } else {
1325 0 : None
1326 : };
1327 :
1328 312344 : reconstruct_state.read_path = read_path;
1329 :
1330 312344 : let redo_attempt_type = if ctx.task_kind() == TaskKind::Compaction {
1331 0 : RedoAttemptType::LegacyCompaction
1332 : } else {
1333 312344 : RedoAttemptType::ReadPage
1334 : };
1335 :
1336 312344 : let traversal_res: Result<(), _> = {
1337 312344 : let ctx = RequestContextBuilder::from(ctx)
1338 312344 : .perf_span(|crnt_perf_span| {
1339 0 : info_span!(
1340 : target: PERF_TRACE_TARGET,
1341 0 : parent: crnt_perf_span,
1342 : "PLAN_IO",
1343 : )
1344 0 : })
1345 312344 : .attached_child();
1346 :
1347 312344 : self.get_vectored_reconstruct_data(query.clone(), reconstruct_state, &ctx)
1348 312344 : .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
1349 312344 : .await
1350 : };
1351 :
1352 312344 : if let Err(err) = traversal_res {
1353 : // Wait for all the spawned IOs to complete.
1354 : // See comments on `spawn_io` inside `storage_layer` for more details.
1355 8 : let mut collect_futs = std::mem::take(&mut reconstruct_state.keys)
1356 8 : .into_values()
1357 8 : .map(|state| state.collect_pending_ios())
1358 8 : .collect::<FuturesUnordered<_>>();
1359 8 : while collect_futs.next().await.is_some() {}
1360 :
1361 : // Enrich the missing key error with the original query.
1362 8 : if let GetVectoredError::MissingKey(mut missing_err) = err {
1363 7 : missing_err.enrich(query.clone());
1364 7 : return Err(GetVectoredError::MissingKey(missing_err));
1365 1 : }
1366 :
1367 1 : return Err(err);
1368 312336 : };
1369 :
1370 312336 : let layers_visited = reconstruct_state.get_layers_visited();
1371 :
1372 312336 : let ctx = RequestContextBuilder::from(ctx)
1373 312336 : .perf_span(|crnt_perf_span| {
1374 0 : info_span!(
1375 : target: PERF_TRACE_TARGET,
1376 0 : parent: crnt_perf_span,
1377 : "RECONSTRUCT",
1378 : )
1379 0 : })
1380 312336 : .attached_child();
1381 :
1382 312336 : let futs = FuturesUnordered::new();
1383 363515 : for (key, state) in std::mem::take(&mut reconstruct_state.keys) {
1384 363515 : let req_lsn_for_key = query.map_key_to_lsn(&key);
1385 :
1386 363515 : futs.push({
1387 363515 : let walredo_self = self.myself.upgrade().expect("&self method holds the arc");
1388 363515 : let ctx = RequestContextBuilder::from(&ctx)
1389 363515 : .perf_span(|crnt_perf_span| {
1390 0 : info_span!(
1391 : target: PERF_TRACE_TARGET,
1392 0 : parent: crnt_perf_span,
1393 : "RECONSTRUCT_KEY",
1394 : key = %key,
1395 : )
1396 0 : })
1397 363515 : .attached_child();
1398 :
1399 363515 : async move {
1400 363515 : assert_eq!(state.situation, ValueReconstructSituation::Complete);
1401 :
1402 363515 : let res = state
1403 363515 : .collect_pending_ios()
1404 363515 : .maybe_perf_instrument(&ctx, |crnt_perf_span| {
1405 0 : info_span!(
1406 : target: PERF_TRACE_TARGET,
1407 0 : parent: crnt_perf_span,
1408 : "WAIT_FOR_IO_COMPLETIONS",
1409 : )
1410 0 : })
1411 363515 : .await;
1412 :
1413 363515 : let converted = match res {
1414 363515 : Ok(ok) => ok,
1415 0 : Err(err) => {
1416 0 : return (key, Err(err));
1417 : }
1418 : };
1419 363515 : DELTAS_PER_READ_GLOBAL.observe(converted.num_deltas() as f64);
1420 :
1421 : // The walredo module expects the records to be descending in terms of Lsn.
1422 : // And we submit the IOs in that order, so, there shuold be no need to sort here.
1423 363515 : debug_assert!(
1424 363515 : converted
1425 363515 : .records
1426 1403254 : .is_sorted_by_key(|(lsn, _)| std::cmp::Reverse(*lsn)),
1427 0 : "{converted:?}"
1428 : );
1429 :
1430 363515 : let walredo_deltas = converted.num_deltas();
1431 363515 : let walredo_res = walredo_self
1432 363515 : .reconstruct_value(key, req_lsn_for_key, converted, redo_attempt_type)
1433 363515 : .maybe_perf_instrument(&ctx, |crnt_perf_span| {
1434 0 : info_span!(
1435 : target: PERF_TRACE_TARGET,
1436 0 : parent: crnt_perf_span,
1437 : "WALREDO",
1438 : deltas = %walredo_deltas,
1439 : )
1440 0 : })
1441 363515 : .await;
1442 :
1443 363515 : (key, walredo_res)
1444 363515 : }
1445 : });
1446 : }
1447 :
1448 312336 : let results = futs
1449 312336 : .collect::<BTreeMap<Key, Result<Bytes, PageReconstructError>>>()
1450 312336 : .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
1451 312336 : .await;
1452 :
1453 : // For aux file keys (v1 or v2) the vectored read path does not return an error
1454 : // when they're missing. Instead they are omitted from the resulting btree
1455 : // (this is a requirement, not a bug). Skip updating the metric in these cases
1456 : // to avoid infinite results.
1457 312336 : if !results.is_empty() {
1458 312208 : if layers_visited >= Self::LAYERS_VISITED_WARN_THRESHOLD {
1459 0 : let total_keyspace = query.total_keyspace();
1460 0 : let max_request_lsn = query.high_watermark_lsn().expect("Validated previously");
1461 :
1462 : static LOG_PACER: Lazy<Mutex<RateLimit>> =
1463 0 : Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(60))));
1464 0 : LOG_PACER.lock().unwrap().call(|| {
1465 0 : let num_keys = total_keyspace.total_raw_size();
1466 0 : let num_pages = results.len();
1467 0 : tracing::info!(
1468 0 : shard_id = %self.tenant_shard_id.shard_slug(),
1469 : lsn = %max_request_lsn,
1470 0 : "Vectored read for {total_keyspace} visited {layers_visited} layers. Returned {num_pages}/{num_keys} pages.",
1471 : );
1472 0 : });
1473 312208 : }
1474 :
1475 : // Records the number of layers visited in a few different ways:
1476 : //
1477 : // * LAYERS_PER_READ: all layers count towards every read in the batch, because each
1478 : // layer directly affects its observed latency.
1479 : //
1480 : // * LAYERS_PER_READ_BATCH: all layers count towards each batch, to get the per-batch
1481 : // layer visits and access cost.
1482 : //
1483 : // * LAYERS_PER_READ_AMORTIZED: the average layer count per read, to get the amortized
1484 : // read amplification after batching.
1485 312208 : let layers_visited = layers_visited as f64;
1486 312208 : let avg_layers_visited = layers_visited / results.len() as f64;
1487 312208 : LAYERS_PER_READ_BATCH_GLOBAL.observe(layers_visited);
1488 675723 : for _ in &results {
1489 363515 : self.metrics.layers_per_read.observe(layers_visited);
1490 363515 : LAYERS_PER_READ_GLOBAL.observe(layers_visited);
1491 363515 : LAYERS_PER_READ_AMORTIZED_GLOBAL.observe(avg_layers_visited);
1492 363515 : }
1493 128 : }
1494 :
1495 312336 : Ok(results)
1496 312344 : }
1497 :
1498 : /// Get last or prev record separately. Same as get_last_record_rlsn().last/prev.
1499 138197 : pub(crate) fn get_last_record_lsn(&self) -> Lsn {
1500 138197 : self.last_record_lsn.load().last
1501 138197 : }
1502 :
1503 0 : pub(crate) fn get_prev_record_lsn(&self) -> Lsn {
1504 0 : self.last_record_lsn.load().prev
1505 0 : }
1506 :
1507 : /// Atomically get both last and prev.
1508 117 : pub(crate) fn get_last_record_rlsn(&self) -> RecordLsn {
1509 117 : self.last_record_lsn.load()
1510 117 : }
1511 :
1512 : /// Subscribe to callers of wait_lsn(). The value of the channel is None if there are no
1513 : /// wait_lsn() calls in progress, and Some(Lsn) if there is an active waiter for wait_lsn().
1514 0 : pub(crate) fn subscribe_for_wait_lsn_updates(&self) -> watch::Receiver<Option<Lsn>> {
1515 0 : self.last_record_lsn.status_receiver()
1516 0 : }
1517 :
1518 609 : pub(crate) fn get_disk_consistent_lsn(&self) -> Lsn {
1519 609 : self.disk_consistent_lsn.load()
1520 609 : }
1521 :
1522 : /// remote_consistent_lsn from the perspective of the tenant's current generation,
1523 : /// not validated with control plane yet.
1524 : /// See [`Self::get_remote_consistent_lsn_visible`].
1525 2 : pub(crate) fn get_remote_consistent_lsn_projected(&self) -> Option<Lsn> {
1526 2 : self.remote_client.remote_consistent_lsn_projected()
1527 2 : }
1528 :
1529 : /// remote_consistent_lsn which the tenant is guaranteed not to go backward from,
1530 : /// i.e. a value of remote_consistent_lsn_projected which has undergone
1531 : /// generation validation in the deletion queue.
1532 0 : pub(crate) fn get_remote_consistent_lsn_visible(&self) -> Option<Lsn> {
1533 0 : self.remote_client.remote_consistent_lsn_visible()
1534 0 : }
1535 :
1536 : /// The sum of the file size of all historic layers in the layer map.
1537 : /// This method makes no distinction between local and remote layers.
1538 : /// Hence, the result **does not represent local filesystem usage**.
1539 0 : pub(crate) async fn layer_size_sum(&self) -> u64 {
1540 0 : let guard = self
1541 0 : .layers
1542 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
1543 0 : .await;
1544 0 : guard.layer_size_sum()
1545 0 : }
1546 :
1547 0 : pub(crate) fn resident_physical_size(&self) -> u64 {
1548 0 : self.metrics.resident_physical_size_get()
1549 0 : }
1550 :
1551 0 : pub(crate) fn get_directory_metrics(&self) -> [u64; DirectoryKind::KINDS_NUM] {
1552 0 : array::from_fn(|idx| self.directory_metrics[idx].load(AtomicOrdering::Relaxed))
1553 0 : }
1554 :
1555 : ///
1556 : /// Wait until WAL has been received and processed up to this LSN.
1557 : ///
1558 : /// You should call this before any of the other get_* or list_* functions. Calling
1559 : /// those functions with an LSN that has been processed yet is an error.
1560 : ///
1561 112578 : pub(crate) async fn wait_lsn(
1562 112578 : &self,
1563 112578 : lsn: Lsn,
1564 112578 : who_is_waiting: WaitLsnWaiter<'_>,
1565 112578 : timeout: WaitLsnTimeout,
1566 112578 : ctx: &RequestContext, /* Prepare for use by cancellation */
1567 112578 : ) -> Result<(), WaitLsnError> {
1568 112578 : let state = self.current_state();
1569 112578 : if self.cancel.is_cancelled() || matches!(state, TimelineState::Stopping) {
1570 0 : return Err(WaitLsnError::Shutdown);
1571 112578 : } else if !matches!(state, TimelineState::Active) {
1572 0 : return Err(WaitLsnError::BadState(state));
1573 112578 : }
1574 :
1575 112578 : if cfg!(debug_assertions) {
1576 112578 : match ctx.task_kind() {
1577 : TaskKind::WalReceiverManager
1578 : | TaskKind::WalReceiverConnectionHandler
1579 : | TaskKind::WalReceiverConnectionPoller => {
1580 0 : let is_myself = match who_is_waiting {
1581 0 : WaitLsnWaiter::Timeline(waiter) => {
1582 0 : Weak::ptr_eq(&waiter.myself, &self.myself)
1583 : }
1584 : WaitLsnWaiter::Tenant
1585 : | WaitLsnWaiter::PageService
1586 : | WaitLsnWaiter::HttpEndpoint
1587 0 : | WaitLsnWaiter::BaseBackupCache => unreachable!(
1588 : "tenant or page_service context are not expected to have task kind {:?}",
1589 0 : ctx.task_kind()
1590 : ),
1591 : };
1592 0 : if is_myself {
1593 0 : if let Err(current) = self.last_record_lsn.would_wait_for(lsn) {
1594 : // walingest is the only one that can advance last_record_lsn; it should make sure to never reach here
1595 0 : panic!(
1596 0 : "this timeline's walingest task is calling wait_lsn({lsn}) but we only have last_record_lsn={current}; would deadlock"
1597 : );
1598 0 : }
1599 0 : } else {
1600 0 : // if another timeline's is waiting for us, there's no deadlock risk because
1601 0 : // our walreceiver task can make progress independent of theirs
1602 0 : }
1603 : }
1604 112578 : _ => {}
1605 : }
1606 0 : }
1607 :
1608 112578 : let timeout = match timeout {
1609 0 : WaitLsnTimeout::Custom(t) => t,
1610 112578 : WaitLsnTimeout::Default => self.conf.wait_lsn_timeout,
1611 : };
1612 :
1613 112578 : let timer = crate::metrics::WAIT_LSN_TIME.start_timer();
1614 112578 : let start_finish_counterpair_guard = self.metrics.wait_lsn_start_finish_counterpair.guard();
1615 :
1616 112578 : let wait_for_timeout = self.last_record_lsn.wait_for_timeout(lsn, timeout);
1617 112578 : let wait_for_timeout = std::pin::pin!(wait_for_timeout);
1618 : // Use threshold of 1 because even 1 second of wait for ingest is very much abnormal.
1619 112578 : let log_slow_threshold = Duration::from_secs(1);
1620 : // Use period of 10 to avoid flooding logs during an outage that affects all timelines.
1621 112578 : let log_slow_period = Duration::from_secs(10);
1622 112578 : let mut logging_permit = None;
1623 112578 : let wait_for_timeout = monitor_slow_future(
1624 112578 : log_slow_threshold,
1625 112578 : log_slow_period,
1626 112578 : wait_for_timeout,
1627 : |MonitorSlowFutureCallback {
1628 : ready,
1629 : is_slow,
1630 : elapsed_total,
1631 : elapsed_since_last_callback,
1632 112578 : }| {
1633 112578 : self.metrics
1634 112578 : .wait_lsn_in_progress_micros
1635 112578 : .inc_by(u64::try_from(elapsed_since_last_callback.as_micros()).unwrap());
1636 112578 : if !is_slow {
1637 112578 : return;
1638 0 : }
1639 : // It's slow, see if we should log it.
1640 : // (We limit the logging to one per invocation per timeline to avoid excessive
1641 : // logging during an extended broker / networking outage that affects all timelines.)
1642 0 : if logging_permit.is_none() {
1643 0 : logging_permit = self.wait_lsn_log_slow.try_acquire().ok();
1644 0 : }
1645 0 : if logging_permit.is_none() {
1646 0 : return;
1647 0 : }
1648 : // We log it.
1649 0 : if ready {
1650 0 : info!(
1651 0 : "slow wait_lsn completed after {:.3}s",
1652 0 : elapsed_total.as_secs_f64()
1653 : );
1654 : } else {
1655 0 : info!(
1656 0 : "slow wait_lsn still running for {:.3}s",
1657 0 : elapsed_total.as_secs_f64()
1658 : );
1659 : }
1660 112578 : },
1661 : );
1662 112578 : let res = wait_for_timeout.await;
1663 : // don't count the time spent waiting for lock below, and also in walreceiver.status(), towards the wait_lsn_time_histo
1664 112578 : drop(logging_permit);
1665 112578 : drop(start_finish_counterpair_guard);
1666 112578 : drop(timer);
1667 112578 : match res {
1668 112578 : Ok(()) => Ok(()),
1669 0 : Err(e) => {
1670 : use utils::seqwait::SeqWaitError::*;
1671 0 : match e {
1672 0 : Shutdown => Err(WaitLsnError::Shutdown),
1673 : Timeout => {
1674 0 : let walreceiver_status = self.walreceiver_status();
1675 0 : Err(WaitLsnError::Timeout(format!(
1676 0 : "Timed out while waiting for WAL record at LSN {} to arrive, last_record_lsn {} disk consistent LSN={}, WalReceiver status: {}",
1677 0 : lsn,
1678 0 : self.get_last_record_lsn(),
1679 0 : self.get_disk_consistent_lsn(),
1680 0 : walreceiver_status,
1681 0 : )))
1682 : }
1683 : }
1684 : }
1685 : }
1686 112578 : }
1687 :
1688 0 : pub(crate) fn walreceiver_status(&self) -> String {
1689 0 : match &*self.walreceiver.lock().unwrap() {
1690 0 : None => "stopping or stopped".to_string(),
1691 0 : Some(walreceiver) => match walreceiver.status() {
1692 0 : Some(status) => status.to_human_readable_string(),
1693 0 : None => "Not active".to_string(),
1694 : },
1695 : }
1696 0 : }
1697 :
1698 : /// Check that it is valid to request operations with that lsn.
1699 119 : pub(crate) fn check_lsn_is_in_scope(
1700 119 : &self,
1701 119 : lsn: Lsn,
1702 119 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
1703 119 : ) -> anyhow::Result<()> {
1704 119 : ensure!(
1705 119 : lsn >= **latest_gc_cutoff_lsn,
1706 2 : "LSN {} is earlier than latest GC cutoff {} (we might've already garbage collected needed data)",
1707 : lsn,
1708 2 : **latest_gc_cutoff_lsn,
1709 : );
1710 117 : Ok(())
1711 119 : }
1712 :
1713 : /// Initializes an LSN lease. The function will return an error if the requested LSN is less than the `latest_gc_cutoff_lsn`.
1714 5 : pub(crate) fn init_lsn_lease(
1715 5 : &self,
1716 5 : lsn: Lsn,
1717 5 : length: Duration,
1718 5 : ctx: &RequestContext,
1719 5 : ) -> anyhow::Result<LsnLease> {
1720 5 : self.make_lsn_lease(lsn, length, true, ctx)
1721 5 : }
1722 :
1723 : /// Renews a lease at a particular LSN. The requested LSN is not validated against the `latest_gc_cutoff_lsn` when we are in the grace period.
1724 2 : pub(crate) fn renew_lsn_lease(
1725 2 : &self,
1726 2 : lsn: Lsn,
1727 2 : length: Duration,
1728 2 : ctx: &RequestContext,
1729 2 : ) -> anyhow::Result<LsnLease> {
1730 2 : self.make_lsn_lease(lsn, length, false, ctx)
1731 2 : }
1732 :
1733 : /// Obtains a temporary lease blocking garbage collection for the given LSN.
1734 : ///
1735 : /// If we are in `AttachedSingle` mode and is not blocked by the lsn lease deadline, this function will error
1736 : /// if the requesting LSN is less than the `latest_gc_cutoff_lsn` and there is no existing request present.
1737 : ///
1738 : /// If there is an existing lease in the map, the lease will be renewed only if the request extends the lease.
1739 : /// The returned lease is therefore the maximum between the existing lease and the requesting lease.
1740 7 : fn make_lsn_lease(
1741 7 : &self,
1742 7 : lsn: Lsn,
1743 7 : length: Duration,
1744 7 : init: bool,
1745 7 : _ctx: &RequestContext,
1746 7 : ) -> anyhow::Result<LsnLease> {
1747 6 : let lease = {
1748 : // Normalize the requested LSN to be aligned, and move to the first record
1749 : // if it points to the beginning of the page (header).
1750 7 : let lsn = xlog_utils::normalize_lsn(lsn, WAL_SEGMENT_SIZE);
1751 :
1752 7 : let mut gc_info = self.gc_info.write().unwrap();
1753 7 : let planned_cutoff = gc_info.min_cutoff();
1754 :
1755 7 : let valid_until = SystemTime::now() + length;
1756 :
1757 7 : let entry = gc_info.leases.entry(lsn);
1758 :
1759 7 : match entry {
1760 3 : Entry::Occupied(mut occupied) => {
1761 3 : let existing_lease = occupied.get_mut();
1762 3 : if valid_until > existing_lease.valid_until {
1763 1 : existing_lease.valid_until = valid_until;
1764 1 : let dt: DateTime<Utc> = valid_until.into();
1765 1 : info!("lease extended to {}", dt);
1766 : } else {
1767 2 : let dt: DateTime<Utc> = existing_lease.valid_until.into();
1768 2 : info!("existing lease covers greater length, valid until {}", dt);
1769 : }
1770 :
1771 3 : existing_lease.clone()
1772 : }
1773 4 : Entry::Vacant(vacant) => {
1774 : // Reject already GC-ed LSN if we are in AttachedSingle and
1775 : // not blocked by the lsn lease deadline.
1776 4 : let validate = {
1777 4 : let conf = self.tenant_conf.load();
1778 4 : conf.location.attach_mode == AttachmentMode::Single
1779 4 : && !conf.is_gc_blocked_by_lsn_lease_deadline()
1780 : };
1781 :
1782 4 : if init || validate {
1783 4 : let latest_gc_cutoff_lsn = self.get_applied_gc_cutoff_lsn();
1784 4 : if lsn < *latest_gc_cutoff_lsn {
1785 1 : bail!(
1786 1 : "tried to request an lsn lease for an lsn below the latest gc cutoff. requested at {} gc cutoff {}",
1787 : lsn,
1788 1 : *latest_gc_cutoff_lsn
1789 : );
1790 3 : }
1791 3 : if lsn < planned_cutoff {
1792 0 : bail!(
1793 0 : "tried to request an lsn lease for an lsn below the planned gc cutoff. requested at {} planned gc cutoff {}",
1794 : lsn,
1795 : planned_cutoff
1796 : );
1797 3 : }
1798 0 : }
1799 :
1800 3 : let dt: DateTime<Utc> = valid_until.into();
1801 3 : info!("lease created, valid until {}", dt);
1802 3 : vacant.insert(LsnLease { valid_until }).clone()
1803 : }
1804 : }
1805 : };
1806 :
1807 6 : Ok(lease)
1808 7 : }
1809 :
1810 : /// Freeze the current open in-memory layer. It will be written to disk on next iteration.
1811 : /// Returns the flush request ID which can be awaited with wait_flush_completion().
1812 : #[instrument(skip(self), fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id))]
1813 : pub(crate) async fn freeze(&self) -> Result<u64, FlushLayerError> {
1814 : self.freeze0().await
1815 : }
1816 :
1817 : /// Freeze and flush the open in-memory layer, waiting for it to be written to disk.
1818 : #[instrument(skip(self), fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id))]
1819 : pub(crate) async fn freeze_and_flush(&self) -> Result<(), FlushLayerError> {
1820 : self.freeze_and_flush0().await
1821 : }
1822 :
1823 : /// Freeze the current open in-memory layer. It will be written to disk on next iteration.
1824 : /// Returns the flush request ID which can be awaited with wait_flush_completion().
1825 570 : pub(crate) async fn freeze0(&self) -> Result<u64, FlushLayerError> {
1826 570 : let mut g = self.write_lock.lock().await;
1827 570 : let to_lsn = self.get_last_record_lsn();
1828 570 : self.freeze_inmem_layer_at(to_lsn, &mut g).await
1829 570 : }
1830 :
1831 : // This exists to provide a non-span creating version of `freeze_and_flush` we can call without
1832 : // polluting the span hierarchy.
1833 570 : pub(crate) async fn freeze_and_flush0(&self) -> Result<(), FlushLayerError> {
1834 570 : let token = self.freeze0().await?;
1835 570 : self.wait_flush_completion(token).await
1836 570 : }
1837 :
1838 : // Check if an open ephemeral layer should be closed: this provides
1839 : // background enforcement of checkpoint interval if there is no active WAL receiver, to avoid keeping
1840 : // an ephemeral layer open forever when idle. It also freezes layers if the global limit on
1841 : // ephemeral layer bytes has been breached.
1842 0 : pub(super) async fn maybe_freeze_ephemeral_layer(&self) {
1843 0 : let Ok(mut write_guard) = self.write_lock.try_lock() else {
1844 : // If the write lock is held, there is an active wal receiver: rolling open layers
1845 : // is their responsibility while they hold this lock.
1846 0 : return;
1847 : };
1848 :
1849 : // FIXME: why not early exit? because before #7927 the state would had been cleared every
1850 : // time, and this was missed.
1851 : // if write_guard.is_none() { return; }
1852 :
1853 0 : let Ok(layers_guard) = self.layers.try_read(LayerManagerLockHolder::TryFreezeLayer) else {
1854 : // Don't block if the layer lock is busy
1855 0 : return;
1856 : };
1857 :
1858 0 : let Ok(lm) = layers_guard.layer_map() else {
1859 0 : return;
1860 : };
1861 :
1862 0 : let Some(open_layer) = &lm.open_layer else {
1863 : // If there is no open layer, we have no layer freezing to do. However, we might need to generate
1864 : // some updates to disk_consistent_lsn and remote_consistent_lsn, in case we ingested some WAL regions
1865 : // that didn't result in writes to this shard.
1866 :
1867 : // Must not hold the layers lock while waiting for a flush.
1868 0 : drop(layers_guard);
1869 :
1870 0 : let last_record_lsn = self.get_last_record_lsn();
1871 0 : let disk_consistent_lsn = self.get_disk_consistent_lsn();
1872 0 : if last_record_lsn > disk_consistent_lsn {
1873 : // We have no open layer, but disk_consistent_lsn is behind the last record: this indicates
1874 : // we are a sharded tenant and have skipped some WAL
1875 0 : let last_freeze_ts = *self.last_freeze_ts.read().unwrap();
1876 0 : if last_freeze_ts.elapsed() >= self.get_checkpoint_timeout() {
1877 : // Only do this if have been layer-less longer than get_checkpoint_timeout, so that a shard
1878 : // without any data ingested (yet) doesn't write a remote index as soon as it
1879 : // sees its LSN advance: we only do this if we've been layer-less
1880 : // for some time.
1881 0 : tracing::debug!(
1882 0 : "Advancing disk_consistent_lsn past WAL ingest gap {} -> {}",
1883 : disk_consistent_lsn,
1884 : last_record_lsn
1885 : );
1886 :
1887 : // The flush loop will update remote consistent LSN as well as disk consistent LSN.
1888 : // We know there is no open layer, so we can request freezing without actually
1889 : // freezing anything. This is true even if we have dropped the layers_guard, we
1890 : // still hold the write_guard.
1891 0 : let _ = async {
1892 0 : let token = self
1893 0 : .freeze_inmem_layer_at(last_record_lsn, &mut write_guard)
1894 0 : .await?;
1895 0 : self.wait_flush_completion(token).await
1896 0 : }
1897 0 : .await;
1898 0 : }
1899 0 : }
1900 :
1901 0 : return;
1902 : };
1903 :
1904 0 : let current_size = open_layer.len();
1905 :
1906 0 : let current_lsn = self.get_last_record_lsn();
1907 :
1908 0 : let checkpoint_distance_override = open_layer.tick();
1909 :
1910 0 : if let Some(size_override) = checkpoint_distance_override {
1911 0 : if current_size > size_override {
1912 : // This is not harmful, but it only happens in relatively rare cases where
1913 : // time-based checkpoints are not happening fast enough to keep the amount of
1914 : // ephemeral data within configured limits. It's a sign of stress on the system.
1915 0 : tracing::info!(
1916 0 : "Early-rolling open layer at size {current_size} (limit {size_override}) due to dirty data pressure"
1917 : );
1918 0 : }
1919 0 : }
1920 :
1921 0 : let checkpoint_distance =
1922 0 : checkpoint_distance_override.unwrap_or(self.get_checkpoint_distance());
1923 :
1924 0 : if self.should_roll(
1925 0 : current_size,
1926 0 : current_size,
1927 0 : checkpoint_distance,
1928 0 : self.get_last_record_lsn(),
1929 0 : self.last_freeze_at.load(),
1930 0 : open_layer.get_opened_at(),
1931 : ) {
1932 0 : match open_layer.info() {
1933 0 : InMemoryLayerInfo::Frozen { lsn_start, lsn_end } => {
1934 : // We may reach this point if the layer was already frozen by not yet flushed: flushing
1935 : // happens asynchronously in the background.
1936 0 : tracing::debug!(
1937 0 : "Not freezing open layer, it's already frozen ({lsn_start}..{lsn_end})"
1938 : );
1939 : }
1940 : InMemoryLayerInfo::Open { .. } => {
1941 : // Upgrade to a write lock and freeze the layer
1942 0 : drop(layers_guard);
1943 0 : let res = self
1944 0 : .freeze_inmem_layer_at(current_lsn, &mut write_guard)
1945 0 : .await;
1946 :
1947 0 : if let Err(e) = res {
1948 0 : tracing::info!(
1949 0 : "failed to flush frozen layer after background freeze: {e:#}"
1950 : );
1951 0 : }
1952 : }
1953 : }
1954 0 : }
1955 0 : }
1956 :
1957 : /// Checks if the internal state of the timeline is consistent with it being able to be offloaded.
1958 : ///
1959 : /// This is neccessary but not sufficient for offloading of the timeline as it might have
1960 : /// child timelines that are not offloaded yet.
1961 0 : pub(crate) fn can_offload(&self) -> (bool, &'static str) {
1962 0 : if self.remote_client.is_archived() != Some(true) {
1963 0 : return (false, "the timeline is not archived");
1964 0 : }
1965 0 : if !self.remote_client.no_pending_work() {
1966 : // if the remote client is still processing some work, we can't offload
1967 0 : return (false, "the upload queue is not drained yet");
1968 0 : }
1969 :
1970 0 : (true, "ok")
1971 0 : }
1972 :
1973 : /// Outermost timeline compaction operation; downloads needed layers. Returns whether we have pending
1974 : /// compaction tasks.
1975 192 : pub(crate) async fn compact(
1976 192 : self: &Arc<Self>,
1977 192 : cancel: &CancellationToken,
1978 192 : flags: EnumSet<CompactFlags>,
1979 192 : ctx: &RequestContext,
1980 192 : ) -> Result<CompactionOutcome, CompactionError> {
1981 192 : let res = self
1982 192 : .compact_with_options(
1983 192 : cancel,
1984 192 : CompactOptions {
1985 192 : flags,
1986 192 : compact_key_range: None,
1987 192 : compact_lsn_range: None,
1988 192 : sub_compaction: false,
1989 192 : sub_compaction_max_job_size_mb: None,
1990 192 : },
1991 192 : ctx,
1992 192 : )
1993 192 : .await;
1994 192 : if let Err(err) = &res {
1995 0 : log_compaction_error(err, None, cancel.is_cancelled(), false);
1996 192 : }
1997 192 : res
1998 192 : }
1999 :
2000 : /// Outermost timeline compaction operation; downloads needed layers.
2001 : ///
2002 : /// NB: the cancellation token is usually from a background task, but can also come from a
2003 : /// request task.
2004 192 : pub(crate) async fn compact_with_options(
2005 192 : self: &Arc<Self>,
2006 192 : cancel: &CancellationToken,
2007 192 : options: CompactOptions,
2008 192 : ctx: &RequestContext,
2009 192 : ) -> Result<CompactionOutcome, CompactionError> {
2010 : // Acquire the compaction lock and task semaphore.
2011 : //
2012 : // L0-only compaction uses a separate semaphore (if enabled) to make sure it isn't starved
2013 : // out by other background tasks (including image compaction). We request this via
2014 : // `BackgroundLoopKind::L0Compaction`.
2015 : //
2016 : // Yield for pending L0 compaction while waiting for the semaphore.
2017 192 : let is_l0_only = options.flags.contains(CompactFlags::OnlyL0Compaction);
2018 192 : let semaphore_kind = match is_l0_only && self.get_compaction_l0_semaphore() {
2019 0 : true => BackgroundLoopKind::L0Compaction,
2020 192 : false => BackgroundLoopKind::Compaction,
2021 : };
2022 192 : let yield_for_l0 = options.flags.contains(CompactFlags::YieldForL0);
2023 192 : if yield_for_l0 {
2024 : // If this is an L0 pass, it doesn't make sense to yield for L0.
2025 0 : debug_assert!(!is_l0_only, "YieldForL0 during L0 pass");
2026 : // If `compaction_l0_first` is disabled, there's no point yielding.
2027 0 : debug_assert!(self.get_compaction_l0_first(), "YieldForL0 without L0 pass");
2028 192 : }
2029 :
2030 192 : let acquire = async move {
2031 192 : let guard = self.compaction_lock.lock().await;
2032 192 : let permit = super::tasks::acquire_concurrency_permit(semaphore_kind, ctx).await;
2033 192 : (guard, permit)
2034 192 : };
2035 :
2036 192 : let (_guard, _permit) = tokio::select! {
2037 192 : (guard, permit) = acquire => (guard, permit),
2038 192 : _ = self.l0_compaction_trigger.notified(), if yield_for_l0 => {
2039 0 : return Ok(CompactionOutcome::YieldForL0);
2040 : }
2041 192 : _ = self.cancel.cancelled() => return Ok(CompactionOutcome::Skipped),
2042 192 : _ = cancel.cancelled() => return Ok(CompactionOutcome::Skipped),
2043 : };
2044 :
2045 192 : let last_record_lsn = self.get_last_record_lsn();
2046 :
2047 : // Last record Lsn could be zero in case the timeline was just created
2048 192 : if !last_record_lsn.is_valid() {
2049 0 : warn!(
2050 0 : "Skipping compaction for potentially just initialized timeline, it has invalid last record lsn: {last_record_lsn}"
2051 : );
2052 0 : return Ok(CompactionOutcome::Skipped);
2053 192 : }
2054 :
2055 192 : let result = match self.get_compaction_algorithm_settings().kind {
2056 : CompactionAlgorithm::Tiered => {
2057 0 : self.compact_tiered(cancel, ctx).await?;
2058 0 : Ok(CompactionOutcome::Done)
2059 : }
2060 192 : CompactionAlgorithm::Legacy => self.compact_legacy(cancel, options, ctx).await,
2061 : };
2062 :
2063 : // Signal compaction failure to avoid L0 flush stalls when it's broken.
2064 0 : match &result {
2065 192 : Ok(_) => self.compaction_failed.store(false, AtomicOrdering::Relaxed),
2066 0 : Err(e) if e.is_cancel() => {}
2067 0 : Err(CompactionError::ShuttingDown) => {
2068 0 : // Covered by the `Err(e) if e.is_cancel()` branch.
2069 0 : }
2070 : Err(CompactionError::Other(_)) => {
2071 0 : self.compaction_failed.store(true, AtomicOrdering::Relaxed)
2072 : }
2073 : Err(CompactionError::CollectKeySpaceError(_)) => {
2074 : // Cancelled errors are covered by the `Err(e) if e.is_cancel()` branch.
2075 0 : self.compaction_failed.store(true, AtomicOrdering::Relaxed)
2076 : }
2077 : };
2078 :
2079 192 : result
2080 192 : }
2081 :
2082 : /// Mutate the timeline with a [`TimelineWriter`].
2083 2566607 : pub(crate) async fn writer(&self) -> TimelineWriter<'_> {
2084 : TimelineWriter {
2085 2566607 : tl: self,
2086 2566607 : write_guard: self.write_lock.lock().await,
2087 : }
2088 2566607 : }
2089 :
2090 0 : pub(crate) fn activate(
2091 0 : self: &Arc<Self>,
2092 0 : parent: Arc<crate::tenant::TenantShard>,
2093 0 : broker_client: BrokerClientChannel,
2094 0 : background_jobs_can_start: Option<&completion::Barrier>,
2095 0 : ctx: &RequestContext,
2096 0 : ) {
2097 0 : if self.tenant_shard_id.is_shard_zero() {
2098 0 : // Logical size is only maintained accurately on shard zero.
2099 0 : self.spawn_initial_logical_size_computation_task(ctx);
2100 0 : }
2101 0 : self.launch_wal_receiver(ctx, broker_client);
2102 0 : self.set_state(TimelineState::Active);
2103 0 : self.launch_eviction_task(parent, background_jobs_can_start);
2104 0 : }
2105 :
2106 : /// After this function returns, there are no timeline-scoped tasks are left running.
2107 : ///
2108 : /// The preferred pattern for is:
2109 : /// - in any spawned tasks, keep Timeline::guard open + Timeline::cancel / child token
2110 : /// - if early shutdown (not just cancellation) of a sub-tree of tasks is required,
2111 : /// go the extra mile and keep track of JoinHandles
2112 : /// - Keep track of JoinHandles using a passed-down `Arc<Mutex<Option<JoinSet>>>` or similar,
2113 : /// instead of spawning directly on a runtime. It is a more composable / testable pattern.
2114 : ///
2115 : /// For legacy reasons, we still have multiple tasks spawned using
2116 : /// `task_mgr::spawn(X, Some(tenant_id), Some(timeline_id))`.
2117 : /// We refer to these as "timeline-scoped task_mgr tasks".
2118 : /// Some of these tasks are already sensitive to Timeline::cancel while others are
2119 : /// not sensitive to Timeline::cancel and instead respect [`task_mgr::shutdown_token`]
2120 : /// or [`task_mgr::shutdown_watcher`].
2121 : /// We want to gradually convert the code base away from these.
2122 : ///
2123 : /// Here is an inventory of timeline-scoped task_mgr tasks that are still sensitive to
2124 : /// `task_mgr::shutdown_{token,watcher}` (there are also tenant-scoped and global-scoped
2125 : /// ones that aren't mentioned here):
2126 : /// - [`TaskKind::TimelineDeletionWorker`]
2127 : /// - NB: also used for tenant deletion
2128 : /// - [`TaskKind::RemoteUploadTask`]`
2129 : /// - [`TaskKind::InitialLogicalSizeCalculation`]
2130 : /// - [`TaskKind::DownloadAllRemoteLayers`] (can we get rid of it?)
2131 : // Inventory of timeline-scoped task_mgr tasks that use spawn but aren't sensitive:
2132 : /// - [`TaskKind::Eviction`]
2133 : /// - [`TaskKind::LayerFlushTask`]
2134 : /// - [`TaskKind::OndemandLogicalSizeCalculation`]
2135 : /// - [`TaskKind::GarbageCollector`] (immediate_gc is timeline-scoped)
2136 5 : pub(crate) async fn shutdown(&self, mode: ShutdownMode) {
2137 5 : debug_assert_current_span_has_tenant_and_timeline_id();
2138 :
2139 : // Regardless of whether we're going to try_freeze_and_flush
2140 : // cancel walreceiver to stop ingesting more data asap.
2141 : //
2142 : // Note that we're accepting a race condition here where we may
2143 : // do the final flush below, before walreceiver observes the
2144 : // cancellation and exits.
2145 : // This means we may open a new InMemoryLayer after the final flush below.
2146 : // Flush loop is also still running for a short while, so, in theory, it
2147 : // could also make its way into the upload queue.
2148 : //
2149 : // If we wait for the shutdown of the walreceiver before moving on to the
2150 : // flush, then that would be avoided. But we don't do it because the
2151 : // walreceiver entertains reads internally, which means that it possibly
2152 : // depends on the download of layers. Layer download is only sensitive to
2153 : // the cancellation of the entire timeline, so cancelling the walreceiver
2154 : // will have no effect on the individual get requests.
2155 : // This would cause problems when there is a lot of ongoing downloads or
2156 : // there is S3 unavailabilities, i.e. detach, deletion, etc would hang,
2157 : // and we can't deallocate resources of the timeline, etc.
2158 5 : let walreceiver = self.walreceiver.lock().unwrap().take();
2159 5 : tracing::debug!(
2160 0 : is_some = walreceiver.is_some(),
2161 0 : "Waiting for WalReceiverManager..."
2162 : );
2163 5 : if let Some(walreceiver) = walreceiver {
2164 0 : walreceiver.cancel().await;
2165 5 : }
2166 : // ... and inform any waiters for newer LSNs that there won't be any.
2167 5 : self.last_record_lsn.shutdown();
2168 :
2169 5 : if let ShutdownMode::FreezeAndFlush = mode {
2170 3 : let do_flush = if let Some((open, frozen)) = self
2171 3 : .layers
2172 3 : .read(LayerManagerLockHolder::Shutdown)
2173 3 : .await
2174 3 : .layer_map()
2175 3 : .map(|lm| (lm.open_layer.is_some(), lm.frozen_layers.len()))
2176 3 : .ok()
2177 3 : .filter(|(open, frozen)| *open || *frozen > 0)
2178 : {
2179 0 : if self.remote_client.is_archived() == Some(true) {
2180 : // No point flushing on shutdown for an archived timeline: it is not important
2181 : // to have it nice and fresh after our restart, and trying to flush here might
2182 : // race with trying to offload it (which also stops the flush loop)
2183 0 : false
2184 : } else {
2185 0 : tracing::info!(?open, frozen, "flushing and freezing on shutdown");
2186 0 : true
2187 : }
2188 : } else {
2189 : // this is double-shutdown, it'll be a no-op
2190 3 : true
2191 : };
2192 :
2193 : // we shut down walreceiver above, so, we won't add anything more
2194 : // to the InMemoryLayer; freeze it and wait for all frozen layers
2195 : // to reach the disk & upload queue, then shut the upload queue and
2196 : // wait for it to drain.
2197 3 : if do_flush {
2198 3 : match self.freeze_and_flush().await {
2199 : Ok(_) => {
2200 : // drain the upload queue
2201 : // if we did not wait for completion here, it might be our shutdown process
2202 : // didn't wait for remote uploads to complete at all, as new tasks can forever
2203 : // be spawned.
2204 : //
2205 : // what is problematic is the shutting down of RemoteTimelineClient, because
2206 : // obviously it does not make sense to stop while we wait for it, but what
2207 : // about corner cases like s3 suddenly hanging up?
2208 3 : self.remote_client.shutdown().await;
2209 : }
2210 : Err(FlushLayerError::Cancelled) => {
2211 : // this is likely the second shutdown, ignore silently.
2212 : // TODO: this can be removed once https://github.com/neondatabase/neon/issues/5080
2213 0 : debug_assert!(self.cancel.is_cancelled());
2214 : }
2215 0 : Err(e) => {
2216 : // Non-fatal. Shutdown is infallible. Failures to flush just mean that
2217 : // we have some extra WAL replay to do next time the timeline starts.
2218 0 : warn!("failed to freeze and flush: {e:#}");
2219 : }
2220 : }
2221 :
2222 : // `self.remote_client.shutdown().await` above should have already flushed everything from the queue, but
2223 : // we also do a final check here to ensure that the queue is empty.
2224 3 : if !self.remote_client.no_pending_work() {
2225 0 : warn!(
2226 0 : "still have pending work in remote upload queue, but continuing shutting down anyways"
2227 : );
2228 3 : }
2229 0 : }
2230 2 : }
2231 :
2232 5 : if let ShutdownMode::Reload = mode {
2233 : // drain the upload queue
2234 1 : self.remote_client.shutdown().await;
2235 1 : if !self.remote_client.no_pending_work() {
2236 0 : warn!(
2237 0 : "still have pending work in remote upload queue, but continuing shutting down anyways"
2238 : );
2239 1 : }
2240 4 : }
2241 :
2242 : // Signal any subscribers to our cancellation token to drop out
2243 5 : tracing::debug!("Cancelling CancellationToken");
2244 5 : self.cancel.cancel();
2245 :
2246 : // If we have a background task downloading heatmap layers stop it.
2247 : // The background downloads are sensitive to timeline cancellation (done above),
2248 : // so the drain will be immediate.
2249 5 : self.stop_and_drain_heatmap_layers_download().await;
2250 :
2251 : // Ensure Prevent new page service requests from starting.
2252 5 : self.handles.shutdown();
2253 :
2254 : // Transition the remote_client into a state where it's only useful for timeline deletion.
2255 : // (The deletion use case is why we can't just hook up remote_client to Self::cancel).)
2256 5 : self.remote_client.stop();
2257 :
2258 : // As documented in remote_client.stop()'s doc comment, it's our responsibility
2259 : // to shut down the upload queue tasks.
2260 : // TODO: fix that, task management should be encapsulated inside remote_client.
2261 5 : task_mgr::shutdown_tasks(
2262 5 : Some(TaskKind::RemoteUploadTask),
2263 5 : Some(self.tenant_shard_id),
2264 5 : Some(self.timeline_id),
2265 5 : )
2266 5 : .await;
2267 :
2268 : // TODO: work toward making this a no-op. See this function's doc comment for more context.
2269 5 : tracing::debug!("Waiting for tasks...");
2270 5 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), Some(self.timeline_id)).await;
2271 :
2272 : {
2273 : // Allow any remaining in-memory layers to do cleanup -- until that, they hold the gate
2274 : // open.
2275 5 : let mut write_guard = self.write_lock.lock().await;
2276 5 : self.layers
2277 5 : .write(LayerManagerLockHolder::Shutdown)
2278 5 : .await
2279 5 : .shutdown(&mut write_guard);
2280 : }
2281 :
2282 : // Finally wait until any gate-holders are complete.
2283 : //
2284 : // TODO: once above shutdown_tasks is a no-op, we can close the gate before calling shutdown_tasks
2285 : // and use a TBD variant of shutdown_tasks that asserts that there were no tasks left.
2286 5 : self.gate.close().await;
2287 :
2288 5 : self.metrics.shutdown();
2289 5 : }
2290 :
2291 235 : pub(crate) fn set_state(&self, new_state: TimelineState) {
2292 235 : match (self.current_state(), new_state) {
2293 235 : (equal_state_1, equal_state_2) if equal_state_1 == equal_state_2 => {
2294 1 : info!("Ignoring new state, equal to the existing one: {equal_state_2:?}");
2295 : }
2296 0 : (st, TimelineState::Loading) => {
2297 0 : error!("ignoring transition from {st:?} into Loading state");
2298 : }
2299 0 : (TimelineState::Broken { .. }, new_state) => {
2300 0 : error!("Ignoring state update {new_state:?} for broken timeline");
2301 : }
2302 : (TimelineState::Stopping, TimelineState::Active) => {
2303 0 : error!("Not activating a Stopping timeline");
2304 : }
2305 234 : (_, new_state) => {
2306 234 : self.state.send_replace(new_state);
2307 234 : }
2308 : }
2309 235 : }
2310 :
2311 1 : pub(crate) fn set_broken(&self, reason: String) {
2312 1 : let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
2313 1 : let broken_state = TimelineState::Broken {
2314 1 : reason,
2315 1 : backtrace: backtrace_str,
2316 1 : };
2317 1 : self.set_state(broken_state);
2318 :
2319 : // Although the Broken state is not equivalent to shutdown() (shutdown will be called
2320 : // later when this tenant is detach or the process shuts down), firing the cancellation token
2321 : // here avoids the need for other tasks to watch for the Broken state explicitly.
2322 1 : self.cancel.cancel();
2323 1 : }
2324 :
2325 113508 : pub(crate) fn current_state(&self) -> TimelineState {
2326 113508 : self.state.borrow().clone()
2327 113508 : }
2328 :
2329 3 : pub(crate) fn is_broken(&self) -> bool {
2330 3 : matches!(&*self.state.borrow(), TimelineState::Broken { .. })
2331 3 : }
2332 :
2333 126 : pub(crate) fn is_active(&self) -> bool {
2334 126 : self.current_state() == TimelineState::Active
2335 126 : }
2336 :
2337 8 : pub(crate) fn is_archived(&self) -> Option<bool> {
2338 8 : self.remote_client.is_archived()
2339 8 : }
2340 :
2341 8 : pub(crate) fn is_invisible(&self) -> Option<bool> {
2342 8 : self.remote_client.is_invisible()
2343 8 : }
2344 :
2345 569 : pub(crate) fn is_stopping(&self) -> bool {
2346 569 : self.current_state() == TimelineState::Stopping
2347 569 : }
2348 :
2349 0 : pub(crate) fn subscribe_for_state_updates(&self) -> watch::Receiver<TimelineState> {
2350 0 : self.state.subscribe()
2351 0 : }
2352 :
2353 112579 : pub(crate) async fn wait_to_become_active(
2354 112579 : &self,
2355 112579 : _ctx: &RequestContext, // Prepare for use by cancellation
2356 112579 : ) -> Result<(), TimelineState> {
2357 112579 : let mut receiver = self.state.subscribe();
2358 : loop {
2359 112579 : let current_state = receiver.borrow().clone();
2360 112579 : match current_state {
2361 : TimelineState::Loading => {
2362 0 : receiver
2363 0 : .changed()
2364 0 : .await
2365 0 : .expect("holding a reference to self");
2366 : }
2367 : TimelineState::Active => {
2368 112578 : return Ok(());
2369 : }
2370 : TimelineState::Broken { .. } | TimelineState::Stopping => {
2371 : // There's no chance the timeline can transition back into ::Active
2372 1 : return Err(current_state);
2373 : }
2374 : }
2375 : }
2376 112579 : }
2377 :
2378 0 : pub(crate) async fn layer_map_info(
2379 0 : &self,
2380 0 : reset: LayerAccessStatsReset,
2381 0 : ) -> Result<LayerMapInfo, layer_manager::Shutdown> {
2382 0 : let guard = self
2383 0 : .layers
2384 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
2385 0 : .await;
2386 0 : let layer_map = guard.layer_map()?;
2387 0 : let mut in_memory_layers = Vec::with_capacity(layer_map.frozen_layers.len() + 1);
2388 0 : if let Some(open_layer) = &layer_map.open_layer {
2389 0 : in_memory_layers.push(open_layer.info());
2390 0 : }
2391 0 : for frozen_layer in &layer_map.frozen_layers {
2392 0 : in_memory_layers.push(frozen_layer.info());
2393 0 : }
2394 :
2395 0 : let historic_layers = layer_map
2396 0 : .iter_historic_layers()
2397 0 : .map(|desc| guard.get_from_desc(&desc).info(reset))
2398 0 : .collect();
2399 :
2400 0 : Ok(LayerMapInfo {
2401 0 : in_memory_layers,
2402 0 : historic_layers,
2403 0 : })
2404 0 : }
2405 :
2406 : #[instrument(skip_all, fields(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))]
2407 : pub(crate) async fn download_layer(
2408 : &self,
2409 : layer_file_name: &LayerName,
2410 : ctx: &RequestContext,
2411 : ) -> Result<Option<bool>, super::storage_layer::layer::DownloadError> {
2412 : let Some(layer) = self
2413 : .find_layer(layer_file_name)
2414 : .await
2415 0 : .map_err(|e| match e {
2416 : layer_manager::Shutdown => {
2417 0 : super::storage_layer::layer::DownloadError::TimelineShutdown
2418 : }
2419 0 : })?
2420 : else {
2421 : return Ok(None);
2422 : };
2423 :
2424 : layer.download(ctx).await?;
2425 :
2426 : Ok(Some(true))
2427 : }
2428 :
2429 : /// Evict just one layer.
2430 : ///
2431 : /// Returns `Ok(None)` in the case where the layer could not be found by its `layer_file_name`.
2432 0 : pub(crate) async fn evict_layer(
2433 0 : &self,
2434 0 : layer_file_name: &LayerName,
2435 0 : ) -> anyhow::Result<Option<bool>> {
2436 0 : let _gate = self
2437 0 : .gate
2438 0 : .enter()
2439 0 : .map_err(|_| anyhow::anyhow!("Shutting down"))?;
2440 :
2441 0 : let Some(local_layer) = self.find_layer(layer_file_name).await? else {
2442 0 : return Ok(None);
2443 : };
2444 :
2445 : // curl has this by default
2446 0 : let timeout = std::time::Duration::from_secs(120);
2447 :
2448 0 : match local_layer.evict_and_wait(timeout).await {
2449 0 : Ok(()) => Ok(Some(true)),
2450 0 : Err(EvictionError::NotFound) => Ok(Some(false)),
2451 0 : Err(EvictionError::Downloaded) => Ok(Some(false)),
2452 0 : Err(EvictionError::Timeout) => Ok(Some(false)),
2453 : }
2454 0 : }
2455 :
2456 2401506 : fn should_roll(
2457 2401506 : &self,
2458 2401506 : layer_size: u64,
2459 2401506 : projected_layer_size: u64,
2460 2401506 : checkpoint_distance: u64,
2461 2401506 : projected_lsn: Lsn,
2462 2401506 : last_freeze_at: Lsn,
2463 2401506 : opened_at: Instant,
2464 2401506 : ) -> bool {
2465 2401506 : let distance = projected_lsn.widening_sub(last_freeze_at);
2466 :
2467 : // Rolling the open layer can be triggered by:
2468 : // 1. The distance from the last LSN we rolled at. This bounds the amount of WAL that
2469 : // the safekeepers need to store. For sharded tenants, we multiply by shard count to
2470 : // account for how writes are distributed across shards: we expect each node to consume
2471 : // 1/count of the LSN on average.
2472 : // 2. The size of the currently open layer.
2473 : // 3. The time since the last roll. It helps safekeepers to regard pageserver as caught
2474 : // up and suspend activity.
2475 2401506 : if distance >= checkpoint_distance as i128 * self.shard_identity.count.count() as i128 {
2476 0 : info!(
2477 0 : "Will roll layer at {} with layer size {} due to LSN distance ({})",
2478 : projected_lsn, layer_size, distance
2479 : );
2480 :
2481 0 : true
2482 2401506 : } else if projected_layer_size >= checkpoint_distance {
2483 : // NB: this check is relied upon by:
2484 40 : let _ = IndexEntry::validate_checkpoint_distance;
2485 40 : info!(
2486 0 : "Will roll layer at {} with layer size {} due to layer size ({})",
2487 : projected_lsn, layer_size, projected_layer_size
2488 : );
2489 :
2490 40 : true
2491 2401466 : } else if distance > 0 && opened_at.elapsed() >= self.get_checkpoint_timeout() {
2492 0 : info!(
2493 0 : "Will roll layer at {} with layer size {} due to time since first write to the layer ({:?})",
2494 : projected_lsn,
2495 : layer_size,
2496 0 : opened_at.elapsed()
2497 : );
2498 :
2499 0 : true
2500 : } else {
2501 2401466 : false
2502 : }
2503 2401506 : }
2504 :
2505 1 : pub(crate) fn is_basebackup_cache_enabled(&self) -> bool {
2506 1 : let tenant_conf = self.tenant_conf.load();
2507 1 : tenant_conf
2508 1 : .tenant_conf
2509 1 : .basebackup_cache_enabled
2510 1 : .unwrap_or(self.conf.default_tenant_conf.basebackup_cache_enabled)
2511 1 : }
2512 :
2513 : /// Try to get a basebackup from the on-disk cache.
2514 0 : pub(crate) async fn get_cached_basebackup(&self, lsn: Lsn) -> Option<tokio::fs::File> {
2515 0 : self.basebackup_cache
2516 0 : .get(self.tenant_shard_id.tenant_id, self.timeline_id, lsn)
2517 0 : .await
2518 0 : }
2519 :
2520 : /// Convenience method to attempt fetching a basebackup for the timeline if enabled and safe for
2521 : /// the given request parameters.
2522 : ///
2523 : /// TODO: consider moving this onto GrpcPageServiceHandler once the libpq handler is gone.
2524 0 : pub async fn get_cached_basebackup_if_enabled(
2525 0 : &self,
2526 0 : lsn: Option<Lsn>,
2527 0 : prev_lsn: Option<Lsn>,
2528 0 : full: bool,
2529 0 : replica: bool,
2530 0 : gzip: bool,
2531 0 : ) -> Option<tokio::fs::File> {
2532 0 : if !self.is_basebackup_cache_enabled() || !self.basebackup_cache.is_enabled() {
2533 0 : return None;
2534 0 : }
2535 : // We have to know which LSN to fetch the basebackup for.
2536 0 : let lsn = lsn?;
2537 : // We only cache gzipped, non-full basebackups for primary computes with automatic prev_lsn.
2538 0 : if prev_lsn.is_some() || full || replica || !gzip {
2539 0 : return None;
2540 0 : }
2541 0 : self.get_cached_basebackup(lsn).await
2542 0 : }
2543 :
2544 : /// Prepare basebackup for the given LSN and store it in the basebackup cache.
2545 : /// The method is asynchronous and returns immediately.
2546 : /// The actual basebackup preparation is performed in the background
2547 : /// by the basebackup cache on a best-effort basis.
2548 1 : pub(crate) fn prepare_basebackup(&self, lsn: Lsn) {
2549 1 : if !self.is_basebackup_cache_enabled() {
2550 1 : return;
2551 0 : }
2552 0 : if !self.tenant_shard_id.is_shard_zero() {
2553 : // In theory we should never get here, but just in case check it.
2554 : // Preparing basebackup doesn't make sense for shards other than shard zero.
2555 0 : return;
2556 0 : }
2557 0 : if !self.is_active() {
2558 : // May happen during initial timeline creation.
2559 : // Such timeline is not in the global timeline map yet,
2560 : // so basebackup cache will not be able to find it.
2561 : // TODO(diko): We can prepare such timelines in finish_creation().
2562 0 : return;
2563 0 : }
2564 :
2565 0 : self.basebackup_cache
2566 0 : .send_prepare(self.tenant_shard_id, self.timeline_id, lsn);
2567 1 : }
2568 : }
2569 :
2570 : /// Number of times we will compute partition within a checkpoint distance.
2571 : const REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE: u64 = 10;
2572 :
2573 : // Private functions
2574 : impl Timeline {
2575 6 : pub(crate) fn get_lsn_lease_length(&self) -> Duration {
2576 6 : let tenant_conf = self.tenant_conf.load();
2577 6 : tenant_conf
2578 6 : .tenant_conf
2579 6 : .lsn_lease_length
2580 6 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
2581 6 : }
2582 :
2583 0 : pub(crate) fn get_lsn_lease_length_for_ts(&self) -> Duration {
2584 0 : let tenant_conf = self.tenant_conf.load();
2585 0 : tenant_conf
2586 0 : .tenant_conf
2587 0 : .lsn_lease_length_for_ts
2588 0 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length_for_ts)
2589 0 : }
2590 :
2591 0 : pub(crate) fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
2592 0 : let tenant_conf = self.tenant_conf.load();
2593 0 : tenant_conf.is_gc_blocked_by_lsn_lease_deadline()
2594 0 : }
2595 :
2596 0 : pub(crate) fn get_lazy_slru_download(&self) -> bool {
2597 0 : let tenant_conf = self.tenant_conf.load();
2598 0 : tenant_conf
2599 0 : .tenant_conf
2600 0 : .lazy_slru_download
2601 0 : .unwrap_or(self.conf.default_tenant_conf.lazy_slru_download)
2602 0 : }
2603 :
2604 : /// Checks if a get page request should get perf tracing
2605 : ///
2606 : /// The configuration priority is: tenant config override, default tenant config,
2607 : /// pageserver config.
2608 0 : pub(crate) fn is_get_page_request_sampled(&self) -> bool {
2609 0 : let tenant_conf = self.tenant_conf.load();
2610 0 : let ratio = tenant_conf
2611 0 : .tenant_conf
2612 0 : .sampling_ratio
2613 0 : .flatten()
2614 0 : .or(self.conf.default_tenant_conf.sampling_ratio)
2615 0 : .or(self.conf.tracing.as_ref().map(|t| t.sampling_ratio));
2616 :
2617 0 : match ratio {
2618 0 : Some(r) => {
2619 0 : if r.numerator == 0 {
2620 0 : false
2621 : } else {
2622 0 : rand::thread_rng().gen_range(0..r.denominator) < r.numerator
2623 : }
2624 : }
2625 0 : None => false,
2626 : }
2627 0 : }
2628 :
2629 2402185 : fn get_checkpoint_distance(&self) -> u64 {
2630 2402185 : let tenant_conf = self.tenant_conf.load();
2631 2402185 : tenant_conf
2632 2402185 : .tenant_conf
2633 2402185 : .checkpoint_distance
2634 2402185 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
2635 2402185 : }
2636 :
2637 2401466 : fn get_checkpoint_timeout(&self) -> Duration {
2638 2401466 : let tenant_conf = self.tenant_conf.load();
2639 2401466 : tenant_conf
2640 2401466 : .tenant_conf
2641 2401466 : .checkpoint_timeout
2642 2401466 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
2643 2401466 : }
2644 :
2645 0 : pub(crate) fn get_pitr_interval(&self) -> Duration {
2646 0 : let tenant_conf = &self.tenant_conf.load().tenant_conf;
2647 0 : tenant_conf
2648 0 : .pitr_interval
2649 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
2650 0 : }
2651 :
2652 1271 : fn get_compaction_period(&self) -> Duration {
2653 1271 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2654 1271 : tenant_conf
2655 1271 : .compaction_period
2656 1271 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
2657 1271 : }
2658 :
2659 351 : fn get_compaction_target_size(&self) -> u64 {
2660 351 : let tenant_conf = self.tenant_conf.load();
2661 351 : tenant_conf
2662 351 : .tenant_conf
2663 351 : .compaction_target_size
2664 351 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
2665 351 : }
2666 :
2667 817 : fn get_compaction_threshold(&self) -> usize {
2668 817 : let tenant_conf = self.tenant_conf.load();
2669 817 : tenant_conf
2670 817 : .tenant_conf
2671 817 : .compaction_threshold
2672 817 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
2673 817 : }
2674 :
2675 : /// Returns `true` if the rel_size_v2 config is enabled. NOTE: the write path and read path
2676 : /// should look at `get_rel_size_v2_status()` to get the actual status of the timeline. It is
2677 : /// possible that the index part persists the state while the config doesn't get persisted.
2678 973 : pub(crate) fn get_rel_size_v2_enabled(&self) -> bool {
2679 973 : let tenant_conf = self.tenant_conf.load();
2680 973 : tenant_conf
2681 973 : .tenant_conf
2682 973 : .rel_size_v2_enabled
2683 973 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
2684 973 : }
2685 :
2686 1099 : pub(crate) fn get_rel_size_v2_status(&self) -> RelSizeMigration {
2687 1099 : self.rel_size_v2_status
2688 1099 : .load()
2689 1099 : .as_ref()
2690 1099 : .map(|s| s.as_ref().clone())
2691 1099 : .unwrap_or(RelSizeMigration::Legacy)
2692 1099 : }
2693 :
2694 23 : fn get_compaction_upper_limit(&self) -> usize {
2695 23 : let tenant_conf = self.tenant_conf.load();
2696 23 : tenant_conf
2697 23 : .tenant_conf
2698 23 : .compaction_upper_limit
2699 23 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
2700 23 : }
2701 :
2702 0 : pub fn get_compaction_l0_first(&self) -> bool {
2703 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2704 0 : tenant_conf
2705 0 : .compaction_l0_first
2706 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
2707 0 : }
2708 :
2709 0 : pub fn get_compaction_l0_semaphore(&self) -> bool {
2710 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2711 0 : tenant_conf
2712 0 : .compaction_l0_semaphore
2713 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_semaphore)
2714 0 : }
2715 :
2716 635 : fn get_l0_flush_delay_threshold(&self) -> Option<usize> {
2717 : // By default, delay L0 flushes at 3x the compaction threshold. The compaction threshold
2718 : // defaults to 10, and L0 compaction is generally able to keep L0 counts below 30.
2719 : const DEFAULT_L0_FLUSH_DELAY_FACTOR: usize = 3;
2720 :
2721 : // If compaction is disabled, don't delay.
2722 635 : if self.get_compaction_period() == Duration::ZERO {
2723 632 : return None;
2724 3 : }
2725 :
2726 3 : let compaction_threshold = self.get_compaction_threshold();
2727 3 : let tenant_conf = self.tenant_conf.load();
2728 3 : let l0_flush_delay_threshold = tenant_conf
2729 3 : .tenant_conf
2730 3 : .l0_flush_delay_threshold
2731 3 : .or(self.conf.default_tenant_conf.l0_flush_delay_threshold)
2732 3 : .unwrap_or(DEFAULT_L0_FLUSH_DELAY_FACTOR * compaction_threshold);
2733 :
2734 : // 0 disables backpressure.
2735 3 : if l0_flush_delay_threshold == 0 {
2736 0 : return None;
2737 3 : }
2738 :
2739 : // Clamp the flush delay threshold to the compaction threshold; it doesn't make sense to
2740 : // backpressure flushes below this.
2741 : // TODO: the tenant config should have validation to prevent this instead.
2742 3 : debug_assert!(l0_flush_delay_threshold >= compaction_threshold);
2743 3 : Some(max(l0_flush_delay_threshold, compaction_threshold))
2744 635 : }
2745 :
2746 636 : fn get_l0_flush_stall_threshold(&self) -> Option<usize> {
2747 : // Disable L0 stalls by default. Stalling can cause unavailability if L0 compaction isn't
2748 : // responsive, and it can e.g. block on other compaction via the compaction semaphore or
2749 : // sibling timelines. We need more confidence before enabling this.
2750 : const DEFAULT_L0_FLUSH_STALL_FACTOR: usize = 0; // TODO: default to e.g. 5
2751 :
2752 : // If compaction is disabled, don't stall.
2753 636 : if self.get_compaction_period() == Duration::ZERO {
2754 632 : return None;
2755 4 : }
2756 :
2757 : // If compaction is failing, don't stall and try to keep the tenant alive. This may not be a
2758 : // good idea: read amp can grow unbounded, leading to terrible performance, and we may take
2759 : // on unbounded compaction debt that can take a long time to fix once compaction comes back
2760 : // online. At least we'll delay flushes, slowing down the growth and buying some time.
2761 4 : if self.compaction_failed.load(AtomicOrdering::Relaxed) {
2762 0 : return None;
2763 4 : }
2764 :
2765 4 : let compaction_threshold = self.get_compaction_threshold();
2766 4 : let tenant_conf = self.tenant_conf.load();
2767 4 : let l0_flush_stall_threshold = tenant_conf
2768 4 : .tenant_conf
2769 4 : .l0_flush_stall_threshold
2770 4 : .or(self.conf.default_tenant_conf.l0_flush_stall_threshold);
2771 :
2772 : // Tests sometimes set compaction_threshold=1 to generate lots of layer files, and don't
2773 : // handle the 20-second compaction delay. Some (e.g. `test_backward_compatibility`) can't
2774 : // easily adjust the L0 backpressure settings, so just disable stalls in this case.
2775 4 : if cfg!(feature = "testing")
2776 4 : && compaction_threshold == 1
2777 0 : && l0_flush_stall_threshold.is_none()
2778 : {
2779 0 : return None;
2780 4 : }
2781 :
2782 4 : let l0_flush_stall_threshold = l0_flush_stall_threshold
2783 4 : .unwrap_or(DEFAULT_L0_FLUSH_STALL_FACTOR * compaction_threshold);
2784 :
2785 : // 0 disables backpressure.
2786 4 : if l0_flush_stall_threshold == 0 {
2787 4 : return None;
2788 0 : }
2789 :
2790 : // Clamp the flush stall threshold to the compaction threshold; it doesn't make sense to
2791 : // backpressure flushes below this.
2792 : // TODO: the tenant config should have validation to prevent this instead.
2793 0 : debug_assert!(l0_flush_stall_threshold >= compaction_threshold);
2794 0 : Some(max(l0_flush_stall_threshold, compaction_threshold))
2795 636 : }
2796 :
2797 7 : fn get_image_creation_threshold(&self) -> usize {
2798 7 : let tenant_conf = self.tenant_conf.load();
2799 7 : tenant_conf
2800 7 : .tenant_conf
2801 7 : .image_creation_threshold
2802 7 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
2803 7 : }
2804 :
2805 192 : fn get_compaction_algorithm_settings(&self) -> CompactionAlgorithmSettings {
2806 192 : let tenant_conf = &self.tenant_conf.load();
2807 192 : tenant_conf
2808 192 : .tenant_conf
2809 192 : .compaction_algorithm
2810 192 : .as_ref()
2811 192 : .unwrap_or(&self.conf.default_tenant_conf.compaction_algorithm)
2812 192 : .clone()
2813 192 : }
2814 :
2815 192 : pub fn get_compaction_shard_ancestor(&self) -> bool {
2816 192 : let tenant_conf = self.tenant_conf.load();
2817 192 : tenant_conf
2818 192 : .tenant_conf
2819 192 : .compaction_shard_ancestor
2820 192 : .unwrap_or(self.conf.default_tenant_conf.compaction_shard_ancestor)
2821 192 : }
2822 :
2823 0 : fn get_eviction_policy(&self) -> EvictionPolicy {
2824 0 : let tenant_conf = self.tenant_conf.load();
2825 0 : tenant_conf
2826 0 : .tenant_conf
2827 0 : .eviction_policy
2828 0 : .unwrap_or(self.conf.default_tenant_conf.eviction_policy)
2829 0 : }
2830 :
2831 234 : fn get_evictions_low_residence_duration_metric_threshold(
2832 234 : tenant_conf: &pageserver_api::models::TenantConfig,
2833 234 : default_tenant_conf: &pageserver_api::config::TenantConfigToml,
2834 234 : ) -> Duration {
2835 234 : tenant_conf
2836 234 : .evictions_low_residence_duration_metric_threshold
2837 234 : .unwrap_or(default_tenant_conf.evictions_low_residence_duration_metric_threshold)
2838 234 : }
2839 :
2840 190 : fn get_image_layer_creation_check_threshold(&self) -> u8 {
2841 190 : let tenant_conf = self.tenant_conf.load();
2842 190 : tenant_conf
2843 190 : .tenant_conf
2844 190 : .image_layer_creation_check_threshold
2845 190 : .unwrap_or(
2846 190 : self.conf
2847 190 : .default_tenant_conf
2848 190 : .image_layer_creation_check_threshold,
2849 : )
2850 190 : }
2851 :
2852 27 : fn get_gc_compaction_settings(&self) -> GcCompactionCombinedSettings {
2853 27 : let tenant_conf = &self.tenant_conf.load();
2854 27 : let gc_compaction_enabled = tenant_conf
2855 27 : .tenant_conf
2856 27 : .gc_compaction_enabled
2857 27 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_enabled);
2858 27 : let gc_compaction_verification = tenant_conf
2859 27 : .tenant_conf
2860 27 : .gc_compaction_verification
2861 27 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_verification);
2862 27 : let gc_compaction_initial_threshold_kb = tenant_conf
2863 27 : .tenant_conf
2864 27 : .gc_compaction_initial_threshold_kb
2865 27 : .unwrap_or(
2866 27 : self.conf
2867 27 : .default_tenant_conf
2868 27 : .gc_compaction_initial_threshold_kb,
2869 : );
2870 27 : let gc_compaction_ratio_percent = tenant_conf
2871 27 : .tenant_conf
2872 27 : .gc_compaction_ratio_percent
2873 27 : .unwrap_or(self.conf.default_tenant_conf.gc_compaction_ratio_percent);
2874 27 : GcCompactionCombinedSettings {
2875 27 : gc_compaction_enabled,
2876 27 : gc_compaction_verification,
2877 27 : gc_compaction_initial_threshold_kb,
2878 27 : gc_compaction_ratio_percent,
2879 27 : }
2880 27 : }
2881 :
2882 0 : fn get_image_creation_preempt_threshold(&self) -> usize {
2883 0 : let tenant_conf = self.tenant_conf.load();
2884 0 : tenant_conf
2885 0 : .tenant_conf
2886 0 : .image_creation_preempt_threshold
2887 0 : .unwrap_or(
2888 0 : self.conf
2889 0 : .default_tenant_conf
2890 0 : .image_creation_preempt_threshold,
2891 : )
2892 0 : }
2893 :
2894 0 : pub(super) fn tenant_conf_updated(&self, new_conf: &AttachedTenantConf) {
2895 : // NB: Most tenant conf options are read by background loops, so,
2896 : // changes will automatically be picked up.
2897 :
2898 : // The threshold is embedded in the metric. So, we need to update it.
2899 : {
2900 0 : let new_threshold = Self::get_evictions_low_residence_duration_metric_threshold(
2901 0 : &new_conf.tenant_conf,
2902 0 : &self.conf.default_tenant_conf,
2903 : );
2904 :
2905 0 : let tenant_id_str = self.tenant_shard_id.tenant_id.to_string();
2906 0 : let shard_id_str = format!("{}", self.tenant_shard_id.shard_slug());
2907 :
2908 0 : let timeline_id_str = self.timeline_id.to_string();
2909 :
2910 0 : self.remote_client.update_config(&new_conf.location);
2911 :
2912 0 : let mut rel_size_cache = self.rel_size_snapshot_cache.lock().unwrap();
2913 0 : if let Some(new_capacity) = new_conf.tenant_conf.relsize_snapshot_cache_capacity {
2914 0 : if new_capacity != rel_size_cache.capacity() {
2915 0 : rel_size_cache.set_capacity(new_capacity);
2916 0 : }
2917 0 : }
2918 :
2919 0 : self.metrics
2920 0 : .evictions_with_low_residence_duration
2921 0 : .write()
2922 0 : .unwrap()
2923 0 : .change_threshold(
2924 0 : &tenant_id_str,
2925 0 : &shard_id_str,
2926 0 : &timeline_id_str,
2927 0 : new_threshold,
2928 0 : );
2929 : }
2930 0 : }
2931 :
2932 : /// Open a Timeline handle.
2933 : ///
2934 : /// Loads the metadata for the timeline into memory, but not the layer map.
2935 : #[allow(clippy::too_many_arguments)]
2936 234 : pub(super) fn new(
2937 234 : conf: &'static PageServerConf,
2938 234 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
2939 234 : metadata: &TimelineMetadata,
2940 234 : previous_heatmap: Option<PreviousHeatmap>,
2941 234 : ancestor: Option<Arc<Timeline>>,
2942 234 : timeline_id: TimelineId,
2943 234 : tenant_shard_id: TenantShardId,
2944 234 : generation: Generation,
2945 234 : shard_identity: ShardIdentity,
2946 234 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
2947 234 : resources: TimelineResources,
2948 234 : pg_version: PgMajorVersion,
2949 234 : state: TimelineState,
2950 234 : attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
2951 234 : create_idempotency: crate::tenant::CreateTimelineIdempotency,
2952 234 : gc_compaction_state: Option<GcCompactionState>,
2953 234 : rel_size_v2_status: Option<RelSizeMigration>,
2954 234 : cancel: CancellationToken,
2955 234 : ) -> Arc<Self> {
2956 234 : let disk_consistent_lsn = metadata.disk_consistent_lsn();
2957 234 : let (state, _) = watch::channel(state);
2958 :
2959 234 : let (layer_flush_start_tx, _) = tokio::sync::watch::channel((0, disk_consistent_lsn));
2960 234 : let (layer_flush_done_tx, _) = tokio::sync::watch::channel((0, Ok(())));
2961 :
2962 234 : let evictions_low_residence_duration_metric_threshold = {
2963 234 : let loaded_tenant_conf = tenant_conf.load();
2964 234 : Self::get_evictions_low_residence_duration_metric_threshold(
2965 234 : &loaded_tenant_conf.tenant_conf,
2966 234 : &conf.default_tenant_conf,
2967 : )
2968 : };
2969 :
2970 234 : if let Some(ancestor) = &ancestor {
2971 118 : let mut ancestor_gc_info = ancestor.gc_info.write().unwrap();
2972 118 : // If we construct an explicit timeline object, it's obviously not offloaded
2973 118 : let is_offloaded = MaybeOffloaded::No;
2974 118 : ancestor_gc_info.insert_child(timeline_id, metadata.ancestor_lsn(), is_offloaded);
2975 118 : }
2976 :
2977 234 : let relsize_snapshot_cache_capacity = {
2978 234 : let loaded_tenant_conf = tenant_conf.load();
2979 234 : loaded_tenant_conf
2980 234 : .tenant_conf
2981 234 : .relsize_snapshot_cache_capacity
2982 234 : .unwrap_or(conf.default_tenant_conf.relsize_snapshot_cache_capacity)
2983 : };
2984 :
2985 234 : Arc::new_cyclic(|myself| {
2986 234 : let metrics = Arc::new(TimelineMetrics::new(
2987 234 : &tenant_shard_id,
2988 234 : &timeline_id,
2989 234 : crate::metrics::EvictionsWithLowResidenceDurationBuilder::new(
2990 : "mtime",
2991 234 : evictions_low_residence_duration_metric_threshold,
2992 : ),
2993 : ));
2994 234 : let aux_file_metrics = metrics.aux_file_size_gauge.clone();
2995 :
2996 234 : let mut result = Timeline {
2997 234 : conf,
2998 234 : tenant_conf,
2999 234 : myself: myself.clone(),
3000 234 : timeline_id,
3001 234 : tenant_shard_id,
3002 234 : generation,
3003 234 : shard_identity,
3004 234 : pg_version,
3005 234 : layers: Default::default(),
3006 234 : gc_compaction_layer_update_lock: tokio::sync::RwLock::new(()),
3007 :
3008 234 : walredo_mgr,
3009 234 : walreceiver: Mutex::new(None),
3010 :
3011 234 : remote_client: Arc::new(resources.remote_client),
3012 :
3013 : // initialize in-memory 'last_record_lsn' from 'disk_consistent_lsn'.
3014 234 : last_record_lsn: SeqWait::new(RecordLsn {
3015 234 : last: disk_consistent_lsn,
3016 234 : prev: metadata.prev_record_lsn().unwrap_or(Lsn(0)),
3017 234 : }),
3018 234 : disk_consistent_lsn: AtomicLsn::new(disk_consistent_lsn.0),
3019 :
3020 234 : gc_compaction_state: ArcSwap::new(Arc::new(gc_compaction_state)),
3021 :
3022 234 : last_freeze_at: AtomicLsn::new(disk_consistent_lsn.0),
3023 234 : last_freeze_ts: RwLock::new(Instant::now()),
3024 :
3025 234 : loaded_at: (disk_consistent_lsn, SystemTime::now()),
3026 :
3027 234 : ancestor_timeline: ancestor,
3028 234 : ancestor_lsn: metadata.ancestor_lsn(),
3029 :
3030 234 : metrics,
3031 :
3032 234 : query_metrics: crate::metrics::SmgrQueryTimePerTimeline::new(
3033 234 : &tenant_shard_id,
3034 234 : &timeline_id,
3035 234 : resources.pagestream_throttle_metrics,
3036 : ),
3037 :
3038 1872 : directory_metrics: array::from_fn(|_| AtomicU64::new(0)),
3039 1872 : directory_metrics_inited: array::from_fn(|_| AtomicBool::new(false)),
3040 :
3041 234 : flush_loop_state: Mutex::new(FlushLoopState::NotStarted),
3042 :
3043 234 : layer_flush_start_tx,
3044 234 : layer_flush_done_tx,
3045 :
3046 234 : write_lock: tokio::sync::Mutex::new(None),
3047 :
3048 234 : gc_info: std::sync::RwLock::new(GcInfo::default()),
3049 :
3050 234 : last_image_layer_creation_status: ArcSwap::new(Arc::new(
3051 234 : LastImageLayerCreationStatus::default(),
3052 : )),
3053 :
3054 234 : applied_gc_cutoff_lsn: Rcu::new(metadata.latest_gc_cutoff_lsn()),
3055 234 : initdb_lsn: metadata.initdb_lsn(),
3056 :
3057 234 : current_logical_size: if disk_consistent_lsn.is_valid() {
3058 : // we're creating timeline data with some layer files existing locally,
3059 : // need to recalculate timeline's logical size based on data in the layers.
3060 120 : LogicalSize::deferred_initial(disk_consistent_lsn)
3061 : } else {
3062 : // we're creating timeline data without any layers existing locally,
3063 : // initial logical size is 0.
3064 114 : LogicalSize::empty_initial()
3065 : },
3066 :
3067 234 : partitioning: GuardArcSwap::new((
3068 234 : (KeyPartitioning::new(), KeyPartitioning::new().into_sparse()),
3069 234 : Lsn(0),
3070 234 : )),
3071 : repartition_threshold: 0,
3072 234 : last_image_layer_creation_check_at: AtomicLsn::new(0),
3073 234 : last_image_layer_creation_check_instant: Mutex::new(None),
3074 :
3075 234 : last_received_wal: Mutex::new(None),
3076 234 : rel_size_latest_cache: RwLock::new(HashMap::new()),
3077 234 : rel_size_snapshot_cache: Mutex::new(LruCache::new(relsize_snapshot_cache_capacity)),
3078 :
3079 234 : download_all_remote_layers_task_info: RwLock::new(None),
3080 :
3081 234 : state,
3082 :
3083 234 : eviction_task_timeline_state: tokio::sync::Mutex::new(
3084 234 : EvictionTaskTimelineState::default(),
3085 : ),
3086 234 : delete_progress: TimelineDeleteProgress::default(),
3087 :
3088 234 : cancel,
3089 234 : gate: Gate::default(),
3090 :
3091 234 : compaction_lock: tokio::sync::Mutex::default(),
3092 234 : compaction_failed: AtomicBool::default(),
3093 234 : l0_compaction_trigger: resources.l0_compaction_trigger,
3094 234 : gc_lock: tokio::sync::Mutex::default(),
3095 :
3096 234 : standby_horizon: AtomicLsn::new(0),
3097 :
3098 234 : pagestream_throttle: resources.pagestream_throttle,
3099 :
3100 234 : aux_file_size_estimator: AuxFileSizeEstimator::new(aux_file_metrics),
3101 :
3102 : #[cfg(test)]
3103 234 : extra_test_dense_keyspace: ArcSwap::new(Arc::new(KeySpace::default())),
3104 :
3105 234 : l0_flush_global_state: resources.l0_flush_global_state,
3106 :
3107 234 : handles: Default::default(),
3108 :
3109 234 : attach_wal_lag_cooldown,
3110 :
3111 234 : create_idempotency,
3112 :
3113 234 : page_trace: Default::default(),
3114 :
3115 234 : previous_heatmap: ArcSwapOption::from_pointee(previous_heatmap),
3116 :
3117 234 : heatmap_layers_downloader: Mutex::new(None),
3118 :
3119 234 : rel_size_v2_status: ArcSwapOption::from_pointee(rel_size_v2_status),
3120 :
3121 234 : wait_lsn_log_slow: tokio::sync::Semaphore::new(1),
3122 :
3123 234 : basebackup_cache: resources.basebackup_cache,
3124 :
3125 234 : feature_resolver: resources.feature_resolver.clone(),
3126 : };
3127 :
3128 234 : result.repartition_threshold =
3129 234 : result.get_checkpoint_distance() / REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE;
3130 :
3131 234 : result
3132 234 : .metrics
3133 234 : .last_record_lsn_gauge
3134 234 : .set(disk_consistent_lsn.0 as i64);
3135 234 : result
3136 234 : })
3137 234 : }
3138 :
3139 341 : pub(super) fn maybe_spawn_flush_loop(self: &Arc<Self>) {
3140 341 : let Ok(guard) = self.gate.enter() else {
3141 0 : info!("cannot start flush loop when the timeline gate has already been closed");
3142 0 : return;
3143 : };
3144 341 : let mut flush_loop_state = self.flush_loop_state.lock().unwrap();
3145 341 : match *flush_loop_state {
3146 231 : FlushLoopState::NotStarted => (),
3147 : FlushLoopState::Running { .. } => {
3148 110 : info!(
3149 0 : "skipping attempt to start flush_loop twice {}/{}",
3150 0 : self.tenant_shard_id, self.timeline_id
3151 : );
3152 110 : return;
3153 : }
3154 : FlushLoopState::Exited => {
3155 0 : info!(
3156 0 : "ignoring attempt to restart exited flush_loop {}/{}",
3157 0 : self.tenant_shard_id, self.timeline_id
3158 : );
3159 0 : return;
3160 : }
3161 : }
3162 :
3163 231 : let layer_flush_start_rx = self.layer_flush_start_tx.subscribe();
3164 231 : let self_clone = Arc::clone(self);
3165 :
3166 231 : debug!("spawning flush loop");
3167 231 : *flush_loop_state = FlushLoopState::Running {
3168 231 : #[cfg(test)]
3169 231 : expect_initdb_optimization: false,
3170 231 : #[cfg(test)]
3171 231 : initdb_optimization_count: 0,
3172 231 : };
3173 231 : task_mgr::spawn(
3174 231 : task_mgr::BACKGROUND_RUNTIME.handle(),
3175 231 : task_mgr::TaskKind::LayerFlushTask,
3176 231 : self.tenant_shard_id,
3177 231 : Some(self.timeline_id),
3178 231 : "layer flush task",
3179 231 : async move {
3180 231 : let _guard = guard;
3181 231 : let background_ctx = RequestContext::todo_child(TaskKind::LayerFlushTask, DownloadBehavior::Error).with_scope_timeline(&self_clone);
3182 231 : self_clone.flush_loop(layer_flush_start_rx, &background_ctx).await;
3183 5 : let mut flush_loop_state = self_clone.flush_loop_state.lock().unwrap();
3184 5 : assert!(matches!(*flush_loop_state, FlushLoopState::Running{..}));
3185 5 : *flush_loop_state = FlushLoopState::Exited;
3186 5 : Ok(())
3187 5 : }
3188 231 : .instrument(info_span!(parent: None, "layer flush task", tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))
3189 : );
3190 341 : }
3191 :
3192 0 : pub(crate) fn update_gc_compaction_state(
3193 0 : &self,
3194 0 : gc_compaction_state: GcCompactionState,
3195 0 : ) -> anyhow::Result<()> {
3196 0 : self.gc_compaction_state
3197 0 : .store(Arc::new(Some(gc_compaction_state.clone())));
3198 0 : self.remote_client
3199 0 : .schedule_index_upload_for_gc_compaction_state_update(gc_compaction_state)
3200 0 : }
3201 :
3202 0 : pub(crate) fn update_rel_size_v2_status(
3203 0 : &self,
3204 0 : rel_size_v2_status: RelSizeMigration,
3205 0 : ) -> anyhow::Result<()> {
3206 0 : self.rel_size_v2_status
3207 0 : .store(Some(Arc::new(rel_size_v2_status.clone())));
3208 0 : self.remote_client
3209 0 : .schedule_index_upload_for_rel_size_v2_status_update(rel_size_v2_status)
3210 0 : }
3211 :
3212 0 : pub(crate) fn get_gc_compaction_state(&self) -> Option<GcCompactionState> {
3213 0 : self.gc_compaction_state.load_full().as_ref().clone()
3214 0 : }
3215 :
3216 : /// Creates and starts the wal receiver.
3217 : ///
3218 : /// This function is expected to be called at most once per Timeline's lifecycle
3219 : /// when the timeline is activated.
3220 0 : fn launch_wal_receiver(
3221 0 : self: &Arc<Self>,
3222 0 : ctx: &RequestContext,
3223 0 : broker_client: BrokerClientChannel,
3224 0 : ) {
3225 0 : info!(
3226 0 : "launching WAL receiver for timeline {} of tenant {}",
3227 0 : self.timeline_id, self.tenant_shard_id
3228 : );
3229 :
3230 0 : let tenant_conf = self.tenant_conf.load();
3231 0 : let wal_connect_timeout = tenant_conf
3232 0 : .tenant_conf
3233 0 : .walreceiver_connect_timeout
3234 0 : .unwrap_or(self.conf.default_tenant_conf.walreceiver_connect_timeout);
3235 0 : let lagging_wal_timeout = tenant_conf
3236 0 : .tenant_conf
3237 0 : .lagging_wal_timeout
3238 0 : .unwrap_or(self.conf.default_tenant_conf.lagging_wal_timeout);
3239 0 : let max_lsn_wal_lag = tenant_conf
3240 0 : .tenant_conf
3241 0 : .max_lsn_wal_lag
3242 0 : .unwrap_or(self.conf.default_tenant_conf.max_lsn_wal_lag);
3243 :
3244 0 : let mut guard = self.walreceiver.lock().unwrap();
3245 0 : assert!(
3246 0 : guard.is_none(),
3247 0 : "multiple launches / re-launches of WAL receiver are not supported"
3248 : );
3249 :
3250 0 : let protocol = PostgresClientProtocol::Interpreted {
3251 0 : format: utils::postgres_client::InterpretedFormat::Protobuf,
3252 0 : compression: Some(utils::postgres_client::Compression::Zstd { level: 1 }),
3253 0 : };
3254 :
3255 0 : *guard = Some(WalReceiver::start(
3256 0 : Arc::clone(self),
3257 0 : WalReceiverConf {
3258 0 : protocol,
3259 0 : wal_connect_timeout,
3260 0 : lagging_wal_timeout,
3261 0 : max_lsn_wal_lag,
3262 0 : auth_token: crate::config::SAFEKEEPER_AUTH_TOKEN.get().cloned(),
3263 0 : availability_zone: self.conf.availability_zone.clone(),
3264 0 : ingest_batch_size: self.conf.ingest_batch_size,
3265 0 : validate_wal_contiguity: self.conf.validate_wal_contiguity,
3266 0 : },
3267 0 : broker_client,
3268 0 : ctx,
3269 0 : ));
3270 0 : }
3271 :
3272 : /// Initialize with an empty layer map. Used when creating a new timeline.
3273 231 : pub(super) fn init_empty_layer_map(&self, start_lsn: Lsn) {
3274 231 : let mut layers = self.layers.try_write(LayerManagerLockHolder::Init).expect(
3275 231 : "in the context where we call this function, no other task has access to the object",
3276 : );
3277 231 : layers
3278 231 : .open_mut()
3279 231 : .expect("in this context the LayerManager must still be open")
3280 231 : .initialize_empty(Lsn(start_lsn.0));
3281 231 : }
3282 :
3283 : /// Scan the timeline directory, cleanup, populate the layer map, and schedule uploads for local-only
3284 : /// files.
3285 3 : pub(super) async fn load_layer_map(
3286 3 : &self,
3287 3 : disk_consistent_lsn: Lsn,
3288 3 : index_part: IndexPart,
3289 3 : ) -> anyhow::Result<()> {
3290 : use LayerName::*;
3291 : use init::Decision::*;
3292 : use init::{Discovered, DismissedLayer};
3293 :
3294 3 : let mut guard = self
3295 3 : .layers
3296 3 : .write(LayerManagerLockHolder::LoadLayerMap)
3297 3 : .await;
3298 :
3299 3 : let timer = self.metrics.load_layer_map_histo.start_timer();
3300 :
3301 : // Scan timeline directory and create ImageLayerName and DeltaFilename
3302 : // structs representing all files on disk
3303 3 : let timeline_path = self
3304 3 : .conf
3305 3 : .timeline_path(&self.tenant_shard_id, &self.timeline_id);
3306 3 : let conf = self.conf;
3307 3 : let span = tracing::Span::current();
3308 :
3309 : // Copy to move into the task we're about to spawn
3310 3 : let this = self.myself.upgrade().expect("&self method holds the arc");
3311 :
3312 3 : let (loaded_layers, needs_cleanup, total_physical_size) = tokio::task::spawn_blocking({
3313 3 : move || {
3314 3 : let _g = span.entered();
3315 3 : let discovered = init::scan_timeline_dir(&timeline_path)?;
3316 3 : let mut discovered_layers = Vec::with_capacity(discovered.len());
3317 3 : let mut unrecognized_files = Vec::new();
3318 :
3319 3 : let mut path = timeline_path;
3320 :
3321 11 : for discovered in discovered {
3322 8 : let (name, kind) = match discovered {
3323 8 : Discovered::Layer(layer_file_name, local_metadata) => {
3324 8 : discovered_layers.push((layer_file_name, local_metadata));
3325 8 : continue;
3326 : }
3327 0 : Discovered::IgnoredBackup(path) => {
3328 0 : std::fs::remove_file(path)
3329 0 : .or_else(fs_ext::ignore_not_found)
3330 0 : .fatal_err("Removing .old file");
3331 0 : continue;
3332 : }
3333 0 : Discovered::Unknown(file_name) => {
3334 : // we will later error if there are any
3335 0 : unrecognized_files.push(file_name);
3336 0 : continue;
3337 : }
3338 0 : Discovered::Ephemeral(name) => (name, "old ephemeral file"),
3339 0 : Discovered::Temporary(name) => (name, "temporary timeline file"),
3340 0 : Discovered::TemporaryDownload(name) => (name, "temporary download"),
3341 : };
3342 0 : path.push(Utf8Path::new(&name));
3343 0 : init::cleanup(&path, kind)?;
3344 0 : path.pop();
3345 : }
3346 :
3347 3 : if !unrecognized_files.is_empty() {
3348 : // assume that if there are any there are many many.
3349 0 : let n = unrecognized_files.len();
3350 0 : let first = &unrecognized_files[..n.min(10)];
3351 0 : anyhow::bail!(
3352 0 : "unrecognized files in timeline dir (total {n}), first 10: {first:?}"
3353 : );
3354 3 : }
3355 :
3356 3 : let decided = init::reconcile(discovered_layers, &index_part, disk_consistent_lsn);
3357 :
3358 3 : let mut loaded_layers = Vec::new();
3359 3 : let mut needs_cleanup = Vec::new();
3360 3 : let mut total_physical_size = 0;
3361 :
3362 11 : for (name, decision) in decided {
3363 8 : let decision = match decision {
3364 8 : Ok(decision) => decision,
3365 0 : Err(DismissedLayer::Future { local }) => {
3366 0 : if let Some(local) = local {
3367 0 : init::cleanup_future_layer(
3368 0 : &local.local_path,
3369 0 : &name,
3370 0 : disk_consistent_lsn,
3371 0 : )?;
3372 0 : }
3373 0 : needs_cleanup.push(name);
3374 0 : continue;
3375 : }
3376 0 : Err(DismissedLayer::LocalOnly(local)) => {
3377 0 : init::cleanup_local_only_file(&name, &local)?;
3378 : // this file never existed remotely, we will have to do rework
3379 0 : continue;
3380 : }
3381 0 : Err(DismissedLayer::BadMetadata(local)) => {
3382 0 : init::cleanup_local_file_for_remote(&local)?;
3383 : // this file never existed remotely, we will have to do rework
3384 0 : continue;
3385 : }
3386 : };
3387 :
3388 8 : match &name {
3389 6 : Delta(d) => assert!(d.lsn_range.end <= disk_consistent_lsn + 1),
3390 2 : Image(i) => assert!(i.lsn <= disk_consistent_lsn),
3391 : }
3392 :
3393 8 : tracing::debug!(layer=%name, ?decision, "applied");
3394 :
3395 8 : let layer = match decision {
3396 8 : Resident { local, remote } => {
3397 8 : total_physical_size += local.file_size;
3398 8 : Layer::for_resident(conf, &this, local.local_path, name, remote)
3399 8 : .drop_eviction_guard()
3400 : }
3401 0 : Evicted(remote) => Layer::for_evicted(conf, &this, name, remote),
3402 : };
3403 :
3404 8 : loaded_layers.push(layer);
3405 : }
3406 3 : Ok((loaded_layers, needs_cleanup, total_physical_size))
3407 3 : }
3408 : })
3409 3 : .await
3410 3 : .map_err(anyhow::Error::new)
3411 3 : .and_then(|x| x)?;
3412 :
3413 3 : let num_layers = loaded_layers.len();
3414 :
3415 3 : guard
3416 3 : .open_mut()
3417 3 : .expect("layermanager must be open during init")
3418 3 : .initialize_local_layers(loaded_layers, disk_consistent_lsn + 1);
3419 :
3420 3 : self.remote_client
3421 3 : .schedule_layer_file_deletion(&needs_cleanup)?;
3422 3 : self.remote_client
3423 3 : .schedule_index_upload_for_file_changes()?;
3424 : // This barrier orders above DELETEs before any later operations.
3425 : // This is critical because code executing after the barrier might
3426 : // create again objects with the same key that we just scheduled for deletion.
3427 : // For example, if we just scheduled deletion of an image layer "from the future",
3428 : // later compaction might run again and re-create the same image layer.
3429 : // "from the future" here means an image layer whose LSN is > IndexPart::disk_consistent_lsn.
3430 : // "same" here means same key range and LSN.
3431 : //
3432 : // Without a barrier between above DELETEs and the re-creation's PUTs,
3433 : // the upload queue may execute the PUT first, then the DELETE.
3434 : // In our example, we will end up with an IndexPart referencing a non-existent object.
3435 : //
3436 : // 1. a future image layer is created and uploaded
3437 : // 2. ps restart
3438 : // 3. the future layer from (1) is deleted during load layer map
3439 : // 4. image layer is re-created and uploaded
3440 : // 5. deletion queue would like to delete (1) but actually deletes (4)
3441 : // 6. delete by name works as expected, but it now deletes the wrong (later) version
3442 : //
3443 : // See https://github.com/neondatabase/neon/issues/5878
3444 : //
3445 : // NB: generation numbers naturally protect against this because they disambiguate
3446 : // (1) and (4)
3447 : // TODO: this is basically a no-op now, should we remove it?
3448 3 : self.remote_client.schedule_barrier()?;
3449 : // TenantShard::create_timeline will wait for these uploads to happen before returning, or
3450 : // on retry.
3451 :
3452 3 : info!(
3453 0 : "loaded layer map with {} layers at {}, total physical size: {}",
3454 : num_layers, disk_consistent_lsn, total_physical_size
3455 : );
3456 :
3457 3 : timer.stop_and_record();
3458 3 : Ok(())
3459 3 : }
3460 :
3461 : /// Retrieve current logical size of the timeline.
3462 : ///
3463 : /// The size could be lagging behind the actual number, in case
3464 : /// the initial size calculation has not been run (gets triggered on the first size access).
3465 : ///
3466 : /// return size and boolean flag that shows if the size is exact
3467 0 : pub(crate) fn get_current_logical_size(
3468 0 : self: &Arc<Self>,
3469 0 : priority: GetLogicalSizePriority,
3470 0 : ctx: &RequestContext,
3471 0 : ) -> logical_size::CurrentLogicalSize {
3472 0 : if !self.tenant_shard_id.is_shard_zero() {
3473 : // Logical size is only accurately maintained on shard zero: when called elsewhere, for example
3474 : // when HTTP API is serving a GET for timeline zero, return zero
3475 0 : return logical_size::CurrentLogicalSize::Approximate(logical_size::Approximate::zero());
3476 0 : }
3477 :
3478 0 : let current_size = self.current_logical_size.current_size();
3479 0 : debug!("Current size: {current_size:?}");
3480 :
3481 0 : match (current_size.accuracy(), priority) {
3482 0 : (logical_size::Accuracy::Exact, _) => (), // nothing to do
3483 0 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::Background) => {
3484 0 : // background task will eventually deliver an exact value, we're in no rush
3485 0 : }
3486 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::User) => {
3487 : // background task is not ready, but user is asking for it now;
3488 : // => make the background task skip the line
3489 : // (The alternative would be to calculate the size here, but,
3490 : // it can actually take a long time if the user has a lot of rels.
3491 : // And we'll inevitable need it again; So, let the background task do the work.)
3492 0 : match self
3493 0 : .current_logical_size
3494 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
3495 0 : .get()
3496 : {
3497 0 : Some(cancel) => cancel.cancel(),
3498 : None => {
3499 0 : match self.current_state() {
3500 0 : TimelineState::Broken { .. } | TimelineState::Stopping => {
3501 0 : // Can happen when timeline detail endpoint is used when deletion is ongoing (or its broken).
3502 0 : // Don't make noise.
3503 0 : }
3504 : TimelineState::Loading => {
3505 : // Import does not return an activated timeline.
3506 0 : info!(
3507 0 : "discarding priority boost for logical size calculation because timeline is not yet active"
3508 : );
3509 : }
3510 : TimelineState::Active => {
3511 : // activation should be setting the once cell
3512 0 : warn!(
3513 0 : "unexpected: cancel_wait_for_background_loop_concurrency_limit_semaphore not set, priority-boosting of logical size calculation will not work"
3514 : );
3515 0 : debug_assert!(false);
3516 : }
3517 : }
3518 : }
3519 : }
3520 : }
3521 : }
3522 :
3523 0 : if let CurrentLogicalSize::Approximate(_) = ¤t_size {
3524 0 : if ctx.task_kind() == TaskKind::WalReceiverConnectionHandler {
3525 0 : let first = self
3526 0 : .current_logical_size
3527 0 : .did_return_approximate_to_walreceiver
3528 0 : .compare_exchange(
3529 0 : false,
3530 0 : true,
3531 0 : AtomicOrdering::Relaxed,
3532 0 : AtomicOrdering::Relaxed,
3533 0 : )
3534 0 : .is_ok();
3535 0 : if first {
3536 0 : crate::metrics::initial_logical_size::TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE.inc();
3537 0 : }
3538 0 : }
3539 0 : }
3540 :
3541 0 : current_size
3542 0 : }
3543 :
3544 0 : fn spawn_initial_logical_size_computation_task(self: &Arc<Self>, ctx: &RequestContext) {
3545 0 : let Some(initial_part_end) = self.current_logical_size.initial_part_end else {
3546 : // nothing to do for freshly created timelines;
3547 0 : assert_eq!(
3548 0 : self.current_logical_size.current_size().accuracy(),
3549 : logical_size::Accuracy::Exact,
3550 : );
3551 0 : self.current_logical_size.initialized.add_permits(1);
3552 0 : return;
3553 : };
3554 :
3555 0 : let cancel_wait_for_background_loop_concurrency_limit_semaphore = CancellationToken::new();
3556 0 : let token = cancel_wait_for_background_loop_concurrency_limit_semaphore.clone();
3557 0 : self.current_logical_size
3558 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore.set(token)
3559 0 : .expect("initial logical size calculation task must be spawned exactly once per Timeline object");
3560 :
3561 0 : let self_clone = Arc::clone(self);
3562 0 : let background_ctx = ctx.detached_child(
3563 0 : TaskKind::InitialLogicalSizeCalculation,
3564 0 : DownloadBehavior::Download,
3565 : );
3566 0 : task_mgr::spawn(
3567 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
3568 0 : task_mgr::TaskKind::InitialLogicalSizeCalculation,
3569 0 : self.tenant_shard_id,
3570 0 : Some(self.timeline_id),
3571 0 : "initial size calculation",
3572 : // NB: don't log errors here, task_mgr will do that.
3573 0 : async move {
3574 0 : self_clone
3575 0 : .initial_logical_size_calculation_task(
3576 0 : initial_part_end,
3577 0 : cancel_wait_for_background_loop_concurrency_limit_semaphore,
3578 0 : background_ctx,
3579 0 : )
3580 0 : .await;
3581 0 : Ok(())
3582 0 : }
3583 0 : .instrument(info_span!(parent: None, "initial_size_calculation", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%self.timeline_id)),
3584 : );
3585 0 : }
3586 :
3587 : /// # Cancellation
3588 : ///
3589 : /// This method is sensitive to `Timeline::cancel`.
3590 : ///
3591 : /// It is _not_ sensitive to task_mgr::shutdown_token().
3592 : ///
3593 : /// # Cancel-Safety
3594 : ///
3595 : /// It does Timeline IO, hence this should be polled to completion because
3596 : /// we could be leaving in-flight IOs behind, which is safe, but annoying
3597 : /// to reason about.
3598 0 : async fn initial_logical_size_calculation_task(
3599 0 : self: Arc<Self>,
3600 0 : initial_part_end: Lsn,
3601 0 : skip_concurrency_limiter: CancellationToken,
3602 0 : background_ctx: RequestContext,
3603 0 : ) {
3604 0 : scopeguard::defer! {
3605 : // Irrespective of the outcome of this operation, we should unblock anyone waiting for it.
3606 : self.current_logical_size.initialized.add_permits(1);
3607 : }
3608 :
3609 0 : let try_once = |attempt: usize| {
3610 0 : let background_ctx = &background_ctx;
3611 0 : let self_ref = &self;
3612 0 : let skip_concurrency_limiter = &skip_concurrency_limiter;
3613 0 : async move {
3614 0 : let wait_for_permit = super::tasks::acquire_concurrency_permit(
3615 0 : BackgroundLoopKind::InitialLogicalSizeCalculation,
3616 0 : background_ctx,
3617 : );
3618 :
3619 : use crate::metrics::initial_logical_size::StartCircumstances;
3620 0 : let (_maybe_permit, circumstances) = tokio::select! {
3621 0 : permit = wait_for_permit => {
3622 0 : (Some(permit), StartCircumstances::AfterBackgroundTasksRateLimit)
3623 : }
3624 0 : _ = self_ref.cancel.cancelled() => {
3625 0 : return Err(CalculateLogicalSizeError::Cancelled);
3626 : }
3627 0 : () = skip_concurrency_limiter.cancelled() => {
3628 : // Some action that is part of a end user interaction requested logical size
3629 : // => break out of the rate limit
3630 : // TODO: ideally we'd not run on BackgroundRuntime but the requester's runtime;
3631 : // but then again what happens if they cancel; also, we should just be using
3632 : // one runtime across the entire process, so, let's leave this for now.
3633 0 : (None, StartCircumstances::SkippedConcurrencyLimiter)
3634 : }
3635 : };
3636 :
3637 0 : let metrics_guard = if attempt == 1 {
3638 0 : crate::metrics::initial_logical_size::START_CALCULATION.first(circumstances)
3639 : } else {
3640 0 : crate::metrics::initial_logical_size::START_CALCULATION.retry(circumstances)
3641 : };
3642 :
3643 0 : let io_concurrency = IoConcurrency::spawn_from_conf(
3644 0 : self_ref.conf.get_vectored_concurrent_io,
3645 0 : self_ref
3646 0 : .gate
3647 0 : .enter()
3648 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?,
3649 : );
3650 :
3651 0 : let calculated_size = self_ref
3652 0 : .logical_size_calculation_task(
3653 0 : initial_part_end,
3654 0 : LogicalSizeCalculationCause::Initial,
3655 0 : background_ctx,
3656 0 : )
3657 0 : .await?;
3658 :
3659 0 : self_ref
3660 0 : .trigger_aux_file_size_computation(
3661 0 : initial_part_end,
3662 0 : background_ctx,
3663 0 : io_concurrency,
3664 0 : )
3665 0 : .await?;
3666 :
3667 : // TODO: add aux file size to logical size
3668 :
3669 0 : Ok((calculated_size, metrics_guard))
3670 0 : }
3671 0 : };
3672 :
3673 0 : let retrying = async {
3674 0 : let mut attempt = 0;
3675 : loop {
3676 0 : attempt += 1;
3677 :
3678 0 : match try_once(attempt).await {
3679 0 : Ok(res) => return ControlFlow::Continue(res),
3680 0 : Err(CalculateLogicalSizeError::Cancelled) => return ControlFlow::Break(()),
3681 : Err(
3682 0 : e @ (CalculateLogicalSizeError::Decode(_)
3683 : | CalculateLogicalSizeError::PageRead(_)),
3684 : ) => {
3685 0 : warn!(attempt, "initial size calculation failed: {e:?}");
3686 : // exponential back-off doesn't make sense at these long intervals;
3687 : // use fixed retry interval with generous jitter instead
3688 0 : let sleep_duration = Duration::from_secs(
3689 0 : u64::try_from(
3690 : // 1hour base
3691 0 : (60_i64 * 60_i64)
3692 0 : // 10min jitter
3693 0 : + rand::thread_rng().gen_range(-10 * 60..10 * 60),
3694 : )
3695 0 : .expect("10min < 1hour"),
3696 : );
3697 0 : tokio::select! {
3698 0 : _ = tokio::time::sleep(sleep_duration) => {}
3699 0 : _ = self.cancel.cancelled() => return ControlFlow::Break(()),
3700 : }
3701 : }
3702 : }
3703 : }
3704 0 : };
3705 :
3706 0 : let (calculated_size, metrics_guard) = match retrying.await {
3707 0 : ControlFlow::Continue(calculated_size) => calculated_size,
3708 0 : ControlFlow::Break(()) => return,
3709 : };
3710 :
3711 : // we cannot query current_logical_size.current_size() to know the current
3712 : // *negative* value, only truncated to u64.
3713 0 : let added = self
3714 0 : .current_logical_size
3715 0 : .size_added_after_initial
3716 0 : .load(AtomicOrdering::Relaxed);
3717 :
3718 0 : let sum = calculated_size.saturating_add_signed(added);
3719 :
3720 : // set the gauge value before it can be set in `update_current_logical_size`.
3721 0 : self.metrics.current_logical_size_gauge.set(sum);
3722 :
3723 0 : self.current_logical_size
3724 0 : .initial_logical_size
3725 0 : .set((calculated_size, metrics_guard.calculation_result_saved()))
3726 0 : .ok()
3727 0 : .expect("only this task sets it");
3728 0 : }
3729 :
3730 7 : pub(crate) fn spawn_ondemand_logical_size_calculation(
3731 7 : self: &Arc<Self>,
3732 7 : lsn: Lsn,
3733 7 : cause: LogicalSizeCalculationCause,
3734 7 : ctx: RequestContext,
3735 7 : ) -> oneshot::Receiver<Result<u64, CalculateLogicalSizeError>> {
3736 7 : let (sender, receiver) = oneshot::channel();
3737 7 : let self_clone = Arc::clone(self);
3738 : // XXX if our caller loses interest, i.e., ctx is cancelled,
3739 : // we should stop the size calculation work and return an error.
3740 : // That would require restructuring this function's API to
3741 : // return the result directly, instead of a Receiver for the result.
3742 7 : let ctx = ctx.detached_child(
3743 7 : TaskKind::OndemandLogicalSizeCalculation,
3744 7 : DownloadBehavior::Download,
3745 : );
3746 7 : task_mgr::spawn(
3747 7 : task_mgr::BACKGROUND_RUNTIME.handle(),
3748 7 : task_mgr::TaskKind::OndemandLogicalSizeCalculation,
3749 7 : self.tenant_shard_id,
3750 7 : Some(self.timeline_id),
3751 7 : "ondemand logical size calculation",
3752 7 : async move {
3753 7 : let res = self_clone
3754 7 : .logical_size_calculation_task(lsn, cause, &ctx)
3755 7 : .await;
3756 7 : let _ = sender.send(res).ok();
3757 7 : Ok(()) // Receiver is responsible for handling errors
3758 7 : }
3759 7 : .in_current_span(),
3760 : );
3761 7 : receiver
3762 7 : }
3763 :
3764 : #[instrument(skip_all)]
3765 : async fn logical_size_calculation_task(
3766 : self: &Arc<Self>,
3767 : lsn: Lsn,
3768 : cause: LogicalSizeCalculationCause,
3769 : ctx: &RequestContext,
3770 : ) -> Result<u64, CalculateLogicalSizeError> {
3771 : crate::span::debug_assert_current_span_has_tenant_and_timeline_id();
3772 : // We should never be calculating logical sizes on shard !=0, because these shards do not have
3773 : // accurate relation sizes, and they do not emit consumption metrics.
3774 : debug_assert!(self.tenant_shard_id.is_shard_zero());
3775 :
3776 : let guard = self
3777 : .gate
3778 : .enter()
3779 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?;
3780 :
3781 : self.calculate_logical_size(lsn, cause, &guard, ctx).await
3782 : }
3783 :
3784 : /// Calculate the logical size of the database at the latest LSN.
3785 : ///
3786 : /// NOTE: counted incrementally, includes ancestors. This can be a slow operation,
3787 : /// especially if we need to download remote layers.
3788 7 : async fn calculate_logical_size(
3789 7 : &self,
3790 7 : up_to_lsn: Lsn,
3791 7 : cause: LogicalSizeCalculationCause,
3792 7 : _guard: &GateGuard,
3793 7 : ctx: &RequestContext,
3794 7 : ) -> Result<u64, CalculateLogicalSizeError> {
3795 7 : info!(
3796 0 : "Calculating logical size for timeline {} at {}",
3797 : self.timeline_id, up_to_lsn
3798 : );
3799 :
3800 7 : if let Err(()) = pausable_failpoint!("timeline-calculate-logical-size-pause", &self.cancel)
3801 : {
3802 0 : return Err(CalculateLogicalSizeError::Cancelled);
3803 7 : }
3804 :
3805 : // See if we've already done the work for initial size calculation.
3806 : // This is a short-cut for timelines that are mostly unused.
3807 7 : if let Some(size) = self.current_logical_size.initialized_size(up_to_lsn) {
3808 0 : return Ok(size);
3809 7 : }
3810 7 : let storage_time_metrics = match cause {
3811 : LogicalSizeCalculationCause::Initial
3812 : | LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize
3813 0 : | LogicalSizeCalculationCause::TenantSizeHandler => &self.metrics.logical_size_histo,
3814 : LogicalSizeCalculationCause::EvictionTaskImitation => {
3815 7 : &self.metrics.imitate_logical_size_histo
3816 : }
3817 : };
3818 7 : let timer = storage_time_metrics.start_timer();
3819 7 : let logical_size = self
3820 7 : .get_current_logical_size_non_incremental(up_to_lsn, ctx)
3821 7 : .await?;
3822 7 : debug!("calculated logical size: {logical_size}");
3823 7 : timer.stop_and_record();
3824 7 : Ok(logical_size)
3825 7 : }
3826 :
3827 : /// Update current logical size, adding `delta' to the old value.
3828 135285 : fn update_current_logical_size(&self, delta: i64) {
3829 135285 : let logical_size = &self.current_logical_size;
3830 135285 : logical_size.increment_size(delta);
3831 :
3832 : // Also set the value in the prometheus gauge. Note that
3833 : // there is a race condition here: if this is is called by two
3834 : // threads concurrently, the prometheus gauge might be set to
3835 : // one value while current_logical_size is set to the
3836 : // other.
3837 135285 : match logical_size.current_size() {
3838 135285 : CurrentLogicalSize::Exact(ref new_current_size) => self
3839 135285 : .metrics
3840 135285 : .current_logical_size_gauge
3841 135285 : .set(new_current_size.into()),
3842 0 : CurrentLogicalSize::Approximate(_) => {
3843 0 : // don't update the gauge yet, this allows us not to update the gauge back and
3844 0 : // forth between the initial size calculation task.
3845 0 : }
3846 : }
3847 135285 : }
3848 :
3849 1522 : pub(crate) fn update_directory_entries_count(&self, kind: DirectoryKind, count: MetricsUpdate) {
3850 : // TODO: this directory metrics is not correct -- we could have multiple reldirs in the system
3851 : // for each of the database, but we only store one value, and therefore each pgdirmodification
3852 : // would overwrite the previous value if they modify different databases.
3853 :
3854 1522 : match count {
3855 561 : MetricsUpdate::Set(count) => {
3856 561 : self.directory_metrics[kind.offset()].store(count, AtomicOrdering::Relaxed);
3857 561 : self.directory_metrics_inited[kind.offset()].store(true, AtomicOrdering::Relaxed);
3858 561 : }
3859 960 : MetricsUpdate::Add(count) => {
3860 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3861 : // it's fine.
3862 960 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3863 960 : // The metrics has been initialized with `MetricsUpdate::Set` before, so we can add/sub
3864 960 : // the value reliably.
3865 960 : self.directory_metrics[kind.offset()].fetch_add(count, AtomicOrdering::Relaxed);
3866 960 : }
3867 : // Otherwise, ignore this update
3868 : }
3869 1 : MetricsUpdate::Sub(count) => {
3870 : // TODO: these operations are not atomic; but we only have one writer to the metrics, so
3871 : // it's fine.
3872 1 : if self.directory_metrics_inited[kind.offset()].load(AtomicOrdering::Relaxed) {
3873 1 : // The metrics has been initialized with `MetricsUpdate::Set` before.
3874 1 : // The operation could overflow so we need to normalize the value.
3875 1 : let prev_val =
3876 1 : self.directory_metrics[kind.offset()].load(AtomicOrdering::Relaxed);
3877 1 : let res = prev_val.saturating_sub(count);
3878 1 : self.directory_metrics[kind.offset()].store(res, AtomicOrdering::Relaxed);
3879 1 : }
3880 : // Otherwise, ignore this update
3881 : }
3882 : };
3883 :
3884 : // TODO: remove this, there's no place in the code that updates this aux metrics.
3885 1522 : let aux_metric =
3886 1522 : self.directory_metrics[DirectoryKind::AuxFiles.offset()].load(AtomicOrdering::Relaxed);
3887 :
3888 1522 : let sum_of_entries = self
3889 1522 : .directory_metrics
3890 1522 : .iter()
3891 12176 : .map(|v| v.load(AtomicOrdering::Relaxed))
3892 1522 : .sum();
3893 : // Set a high general threshold and a lower threshold for the auxiliary files,
3894 : // as we can have large numbers of relations in the db directory.
3895 : const SUM_THRESHOLD: u64 = 5000;
3896 : const AUX_THRESHOLD: u64 = 1000;
3897 1522 : if sum_of_entries >= SUM_THRESHOLD || aux_metric >= AUX_THRESHOLD {
3898 0 : self.metrics
3899 0 : .directory_entries_count_gauge
3900 0 : .set(sum_of_entries);
3901 1522 : } else if let Some(metric) = Lazy::get(&self.metrics.directory_entries_count_gauge) {
3902 0 : metric.set(sum_of_entries);
3903 1522 : }
3904 1522 : }
3905 :
3906 0 : async fn find_layer(
3907 0 : &self,
3908 0 : layer_name: &LayerName,
3909 0 : ) -> Result<Option<Layer>, layer_manager::Shutdown> {
3910 0 : let guard = self
3911 0 : .layers
3912 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
3913 0 : .await;
3914 0 : let layer = guard
3915 0 : .layer_map()?
3916 0 : .iter_historic_layers()
3917 0 : .find(|l| &l.layer_name() == layer_name)
3918 0 : .map(|found| guard.get_from_desc(&found));
3919 0 : Ok(layer)
3920 0 : }
3921 :
3922 0 : pub(super) fn should_keep_previous_heatmap(&self, new_heatmap_end_lsn: Lsn) -> bool {
3923 0 : let crnt = self.previous_heatmap.load();
3924 0 : match crnt.as_deref() {
3925 0 : Some(PreviousHeatmap::Active { end_lsn, .. }) => match end_lsn {
3926 0 : Some(crnt_end_lsn) => *crnt_end_lsn > new_heatmap_end_lsn,
3927 0 : None => true,
3928 : },
3929 0 : Some(PreviousHeatmap::Obsolete) => false,
3930 0 : None => false,
3931 : }
3932 0 : }
3933 :
3934 : /// The timeline heatmap is a hint to secondary locations from the primary location,
3935 : /// indicating which layers are currently on-disk on the primary.
3936 : ///
3937 : /// None is returned if the Timeline is in a state where uploading a heatmap
3938 : /// doesn't make sense, such as shutting down or initializing. The caller
3939 : /// should treat this as a cue to simply skip doing any heatmap uploading
3940 : /// for this timeline.
3941 8 : pub(crate) async fn generate_heatmap(&self) -> Option<HeatMapTimeline> {
3942 8 : if !self.is_active() {
3943 0 : return None;
3944 8 : }
3945 :
3946 8 : let guard = self
3947 8 : .layers
3948 8 : .read(LayerManagerLockHolder::GenerateHeatmap)
3949 8 : .await;
3950 :
3951 : // Firstly, if there's any heatmap left over from when this location
3952 : // was a secondary, take that into account. Keep layers that are:
3953 : // * present in the layer map
3954 : // * visible
3955 : // * non-resident
3956 : // * not evicted since we read the heatmap
3957 : //
3958 : // Without this, a new cold, attached location would clobber the previous
3959 : // heatamp.
3960 8 : let previous_heatmap = self.previous_heatmap.load();
3961 8 : let visible_non_resident = match previous_heatmap.as_deref() {
3962 : Some(PreviousHeatmap::Active {
3963 6 : heatmap, read_at, ..
3964 23 : }) => Some(heatmap.all_layers().filter_map(|hl| {
3965 23 : let desc: PersistentLayerDesc = hl.name.clone().into();
3966 23 : let layer = guard.try_get_from_key(&desc.key())?;
3967 :
3968 23 : if layer.visibility() == LayerVisibilityHint::Covered {
3969 0 : return None;
3970 23 : }
3971 :
3972 23 : if layer.is_likely_resident() {
3973 10 : return None;
3974 13 : }
3975 :
3976 13 : if layer.last_evicted_at().happened_after(*read_at) {
3977 3 : return None;
3978 10 : }
3979 :
3980 10 : Some((desc, hl.metadata.clone(), hl.access_time, hl.cold))
3981 23 : })),
3982 0 : Some(PreviousHeatmap::Obsolete) => None,
3983 2 : None => None,
3984 : };
3985 :
3986 : // Secondly, all currently visible, resident layers are included.
3987 18 : let resident = guard.likely_resident_layers().filter_map(|layer| {
3988 18 : match layer.visibility() {
3989 : LayerVisibilityHint::Visible => {
3990 : // Layer is visible to one or more read LSNs: elegible for inclusion in layer map
3991 17 : let last_activity_ts = layer.latest_activity();
3992 17 : Some((
3993 17 : layer.layer_desc().clone(),
3994 17 : layer.metadata(),
3995 17 : last_activity_ts,
3996 17 : false, // these layers are not cold
3997 17 : ))
3998 : }
3999 : LayerVisibilityHint::Covered => {
4000 : // Layer is resident but unlikely to be read: not elegible for inclusion in heatmap.
4001 1 : None
4002 : }
4003 : }
4004 18 : });
4005 :
4006 8 : let mut layers = match visible_non_resident {
4007 6 : Some(non_resident) => {
4008 6 : let mut non_resident = non_resident.peekable();
4009 6 : if non_resident.peek().is_none() {
4010 2 : tracing::info!(timeline_id=%self.timeline_id, "Previous heatmap now obsolete");
4011 2 : self.previous_heatmap
4012 2 : .store(Some(PreviousHeatmap::Obsolete.into()));
4013 4 : }
4014 :
4015 6 : non_resident.chain(resident).collect::<Vec<_>>()
4016 : }
4017 2 : None => resident.collect::<Vec<_>>(),
4018 : };
4019 :
4020 : // Sort layers in order of which to download first. For a large set of layers to download, we
4021 : // want to prioritize those layers which are most likely to still be in the resident many minutes
4022 : // or hours later:
4023 : // - Cold layers go last for convenience when a human inspects the heatmap.
4024 : // - Download L0s last, because they churn the fastest: L0s on a fast-writing tenant might
4025 : // only exist for a few minutes before being compacted into L1s.
4026 : // - For L1 & image layers, download most recent LSNs first: the older the LSN, the sooner
4027 : // the layer is likely to be covered by an image layer during compaction.
4028 60 : layers.sort_by_key(|(desc, _meta, _atime, cold)| {
4029 60 : std::cmp::Reverse((
4030 60 : *cold,
4031 60 : !LayerMap::is_l0(&desc.key_range, desc.is_delta),
4032 60 : desc.lsn_range.end,
4033 60 : ))
4034 60 : });
4035 :
4036 8 : let layers = layers
4037 8 : .into_iter()
4038 27 : .map(|(desc, meta, atime, cold)| {
4039 27 : HeatMapLayer::new(desc.layer_name(), meta, atime, cold)
4040 27 : })
4041 8 : .collect();
4042 :
4043 8 : Some(HeatMapTimeline::new(self.timeline_id, layers))
4044 8 : }
4045 :
4046 0 : pub(super) async fn generate_unarchival_heatmap(&self, end_lsn: Lsn) -> PreviousHeatmap {
4047 0 : let guard = self
4048 0 : .layers
4049 0 : .read(LayerManagerLockHolder::GenerateHeatmap)
4050 0 : .await;
4051 :
4052 0 : let now = SystemTime::now();
4053 0 : let mut heatmap_layers = Vec::default();
4054 0 : for vl in guard.visible_layers() {
4055 0 : if vl.layer_desc().get_lsn_range().start >= end_lsn {
4056 0 : continue;
4057 0 : }
4058 :
4059 0 : let hl = HeatMapLayer {
4060 0 : name: vl.layer_desc().layer_name(),
4061 0 : metadata: vl.metadata(),
4062 0 : access_time: now,
4063 0 : cold: true,
4064 0 : };
4065 0 : heatmap_layers.push(hl);
4066 : }
4067 :
4068 0 : tracing::info!(
4069 0 : "Generating unarchival heatmap with {} layers",
4070 0 : heatmap_layers.len()
4071 : );
4072 :
4073 0 : let heatmap = HeatMapTimeline::new(self.timeline_id, heatmap_layers);
4074 0 : PreviousHeatmap::Active {
4075 0 : heatmap,
4076 0 : read_at: Instant::now(),
4077 0 : end_lsn: Some(end_lsn),
4078 0 : }
4079 0 : }
4080 :
4081 : /// Returns true if the given lsn is or was an ancestor branchpoint.
4082 0 : pub(crate) fn is_ancestor_lsn(&self, lsn: Lsn) -> bool {
4083 : // upon timeline detach, we set the ancestor_lsn to Lsn::INVALID and the store the original
4084 : // branchpoint in the value in IndexPart::lineage
4085 0 : self.ancestor_lsn == lsn
4086 0 : || (self.ancestor_lsn == Lsn::INVALID
4087 0 : && self.remote_client.is_previous_ancestor_lsn(lsn))
4088 0 : }
4089 : }
4090 :
4091 : #[derive(Clone)]
4092 : /// Type representing a query in the ([`Lsn`], [`Key`]) space.
4093 : /// In other words, a set of segments in a 2D space.
4094 : ///
4095 : /// This representation has the advatange of avoiding hash map
4096 : /// allocations for uniform queries.
4097 : pub(crate) enum VersionedKeySpaceQuery {
4098 : /// Variant for queries at a single [`Lsn`]
4099 : Uniform { keyspace: KeySpace, lsn: Lsn },
4100 : /// Variant for queries at multiple [`Lsn`]s
4101 : Scattered {
4102 : keyspaces_at_lsn: Vec<(Lsn, KeySpace)>,
4103 : },
4104 : }
4105 :
4106 : impl VersionedKeySpaceQuery {
4107 302152 : pub(crate) fn uniform(keyspace: KeySpace, lsn: Lsn) -> Self {
4108 302152 : Self::Uniform { keyspace, lsn }
4109 302152 : }
4110 :
4111 10192 : pub(crate) fn scattered(keyspaces_at_lsn: Vec<(Lsn, KeySpace)>) -> Self {
4112 10192 : Self::Scattered { keyspaces_at_lsn }
4113 10192 : }
4114 :
4115 : /// Returns the most recent (largest) LSN included in the query.
4116 : /// If any of the LSNs included in the query are invalid, returns
4117 : /// an error instead.
4118 624688 : fn high_watermark_lsn(&self) -> Result<Lsn, GetVectoredError> {
4119 624688 : match self {
4120 604304 : Self::Uniform { lsn, .. } => {
4121 604304 : if !lsn.is_valid() {
4122 0 : return Err(GetVectoredError::InvalidLsn(*lsn));
4123 604304 : }
4124 :
4125 604304 : Ok(*lsn)
4126 : }
4127 20384 : Self::Scattered { keyspaces_at_lsn } => {
4128 20384 : let mut max_lsn = None;
4129 42218 : for (lsn, _keyspace) in keyspaces_at_lsn.iter() {
4130 42218 : if !lsn.is_valid() {
4131 0 : return Err(GetVectoredError::InvalidLsn(*lsn));
4132 42218 : }
4133 42218 : max_lsn = std::cmp::max(max_lsn, Some(lsn));
4134 : }
4135 :
4136 20384 : if let Some(computed) = max_lsn {
4137 20384 : Ok(*computed)
4138 : } else {
4139 0 : Err(GetVectoredError::Other(anyhow!("empty input")))
4140 : }
4141 : }
4142 : }
4143 624688 : }
4144 :
4145 : /// Returns the total keyspace being queried: the result of projecting
4146 : /// everything in the key dimensions onto the key axis.
4147 323364 : fn total_keyspace(&self) -> KeySpace {
4148 323364 : match self {
4149 302980 : Self::Uniform { keyspace, .. } => keyspace.clone(),
4150 20384 : Self::Scattered { keyspaces_at_lsn } => keyspaces_at_lsn
4151 20384 : .iter()
4152 20384 : .map(|(_lsn, keyspace)| keyspace)
4153 42218 : .fold(KeySpace::default(), |mut acc, v| {
4154 42218 : acc.merge(v);
4155 42218 : acc
4156 42218 : }),
4157 : }
4158 323364 : }
4159 :
4160 : /// Returns LSN for a specific key.
4161 : ///
4162 : /// Invariant: requested key must be part of [`Self::total_keyspace`]
4163 395515 : pub(super) fn map_key_to_lsn(&self, key: &Key) -> Lsn {
4164 395515 : match self {
4165 322323 : Self::Uniform { lsn, .. } => *lsn,
4166 73192 : Self::Scattered { keyspaces_at_lsn } => {
4167 73192 : keyspaces_at_lsn
4168 73192 : .iter()
4169 418476 : .find(|(_lsn, keyspace)| keyspace.contains(key))
4170 73192 : .expect("Returned key was requested")
4171 : .0
4172 : }
4173 : }
4174 395515 : }
4175 :
4176 : /// Remove any parts of the query (segments) which overlap with the provided
4177 : /// key space (also segments).
4178 962423 : fn remove_overlapping_with(&mut self, to_remove: &KeySpace) -> KeySpace {
4179 962423 : match self {
4180 942039 : Self::Uniform { keyspace, .. } => keyspace.remove_overlapping_with(to_remove),
4181 20384 : Self::Scattered { keyspaces_at_lsn } => {
4182 20384 : let mut removed_accum = KeySpaceRandomAccum::new();
4183 42218 : keyspaces_at_lsn.iter_mut().for_each(|(_lsn, keyspace)| {
4184 42218 : let removed = keyspace.remove_overlapping_with(to_remove);
4185 42218 : removed_accum.add_keyspace(removed);
4186 42218 : });
4187 :
4188 20384 : removed_accum.to_keyspace()
4189 : }
4190 : }
4191 962423 : }
4192 :
4193 737266 : fn is_empty(&self) -> bool {
4194 737266 : match self {
4195 716882 : Self::Uniform { keyspace, .. } => keyspace.is_empty(),
4196 20384 : Self::Scattered { keyspaces_at_lsn } => keyspaces_at_lsn
4197 20384 : .iter()
4198 31301 : .all(|(_lsn, keyspace)| keyspace.is_empty()),
4199 : }
4200 737266 : }
4201 :
4202 : /// "Lower" the query on the LSN dimension
4203 112579 : fn lower(&mut self, to: Lsn) {
4204 112579 : match self {
4205 112579 : Self::Uniform { lsn, .. } => {
4206 112579 : // If the originally requested LSN is smaller than the starting
4207 112579 : // LSN of the ancestor we are descending into, we need to respect that.
4208 112579 : // Hence the min.
4209 112579 : *lsn = std::cmp::min(*lsn, to);
4210 112579 : }
4211 0 : Self::Scattered { keyspaces_at_lsn } => {
4212 0 : keyspaces_at_lsn.iter_mut().for_each(|(lsn, _keyspace)| {
4213 0 : *lsn = std::cmp::min(*lsn, to);
4214 0 : });
4215 : }
4216 : }
4217 112579 : }
4218 : }
4219 :
4220 : impl std::fmt::Display for VersionedKeySpaceQuery {
4221 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4222 0 : write!(f, "[")?;
4223 :
4224 0 : match self {
4225 0 : VersionedKeySpaceQuery::Uniform { keyspace, lsn } => {
4226 0 : write!(f, "{keyspace} @ {lsn}")?;
4227 : }
4228 0 : VersionedKeySpaceQuery::Scattered { keyspaces_at_lsn } => {
4229 0 : for (lsn, keyspace) in keyspaces_at_lsn.iter() {
4230 0 : write!(f, "{keyspace} @ {lsn},")?;
4231 : }
4232 : }
4233 : }
4234 :
4235 0 : write!(f, "]")
4236 0 : }
4237 : }
4238 :
4239 : impl Timeline {
4240 : #[allow(clippy::doc_lazy_continuation)]
4241 : /// Get the data needed to reconstruct all keys in the provided keyspace
4242 : ///
4243 : /// The algorithm is as follows:
4244 : /// 1. While some keys are still not done and there's a timeline to visit:
4245 : /// 2. Visit the timeline (see [`Timeline::get_vectored_reconstruct_data_timeline`]:
4246 : /// 2.1: Build the fringe for the current keyspace
4247 : /// 2.2 Visit the newest layer from the fringe to collect all values for the range it
4248 : /// intersects
4249 : /// 2.3. Pop the timeline from the fringe
4250 : /// 2.4. If the fringe is empty, go back to 1
4251 312344 : async fn get_vectored_reconstruct_data(
4252 312344 : &self,
4253 312344 : mut query: VersionedKeySpaceQuery,
4254 312344 : reconstruct_state: &mut ValuesReconstructState,
4255 312344 : ctx: &RequestContext,
4256 312344 : ) -> Result<(), GetVectoredError> {
4257 312344 : let original_hwm_lsn = query.high_watermark_lsn().unwrap();
4258 :
4259 : let mut timeline_owned: Arc<Timeline>;
4260 312344 : let mut timeline = self;
4261 :
4262 312343 : let missing_keyspace = loop {
4263 424922 : if self.cancel.is_cancelled() {
4264 0 : return Err(GetVectoredError::Cancelled);
4265 424922 : }
4266 :
4267 : let TimelineVisitOutcome {
4268 424922 : completed_keyspace: completed,
4269 424922 : image_covered_keyspace,
4270 : } = {
4271 424922 : let ctx = RequestContextBuilder::from(ctx)
4272 424922 : .perf_span(|crnt_perf_span| {
4273 0 : info_span!(
4274 : target: PERF_TRACE_TARGET,
4275 0 : parent: crnt_perf_span,
4276 : "PLAN_IO_TIMELINE",
4277 : timeline = %timeline.timeline_id,
4278 0 : high_watermark_lsn = %query.high_watermark_lsn().unwrap(),
4279 : )
4280 0 : })
4281 424922 : .attached_child();
4282 :
4283 424922 : Self::get_vectored_reconstruct_data_timeline(
4284 424922 : timeline,
4285 424922 : &query,
4286 424922 : reconstruct_state,
4287 424922 : &self.cancel,
4288 424922 : &ctx,
4289 : )
4290 424922 : .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
4291 424922 : .await?
4292 : };
4293 :
4294 424922 : query.remove_overlapping_with(&completed);
4295 :
4296 : // Do not descend into the ancestor timeline for aux files.
4297 : // We don't return a blanket [`GetVectoredError::MissingKey`] to avoid
4298 : // stalling compaction.
4299 424922 : query.remove_overlapping_with(&KeySpace {
4300 424922 : ranges: vec![NON_INHERITED_RANGE, Key::sparse_non_inherited_keyspace()],
4301 424922 : });
4302 :
4303 : // Keyspace is fully retrieved
4304 424922 : if query.is_empty() {
4305 312211 : break None;
4306 112711 : }
4307 :
4308 112711 : let Some(ancestor_timeline) = timeline.ancestor_timeline.as_ref() else {
4309 : // Not fully retrieved but no ancestor timeline.
4310 132 : break Some(query.total_keyspace());
4311 : };
4312 :
4313 : // Now we see if there are keys covered by the image layer but does not exist in the
4314 : // image layer, which means that the key does not exist.
4315 :
4316 : // The block below will stop the vectored search if any of the keys encountered an image layer
4317 : // which did not contain a snapshot for said key. Since we have already removed all completed
4318 : // keys from `keyspace`, we expect there to be no overlap between it and the image covered key
4319 : // space. If that's not the case, we had at least one key encounter a gap in the image layer
4320 : // and stop the search as a result of that.
4321 112579 : let mut removed = query.remove_overlapping_with(&image_covered_keyspace);
4322 : // Do not fire missing key error and end early for sparse keys. Note that we hava already removed
4323 : // non-inherited keyspaces before, so we can safely do a full `SPARSE_RANGE` remove instead of
4324 : // figuring out what is the inherited key range and do a fine-grained pruning.
4325 112579 : removed.remove_overlapping_with(&KeySpace {
4326 112579 : ranges: vec![SPARSE_RANGE],
4327 112579 : });
4328 112579 : if !removed.is_empty() {
4329 0 : break Some(removed);
4330 112579 : }
4331 :
4332 : // Each key range in the original query is at some point in the LSN space.
4333 : // When descending into the ancestor, lower all ranges in the LSN space
4334 : // such that new changes on the parent timeline are not visible.
4335 112579 : query.lower(timeline.ancestor_lsn);
4336 :
4337 112579 : let ctx = RequestContextBuilder::from(ctx)
4338 112579 : .perf_span(|crnt_perf_span| {
4339 0 : info_span!(
4340 : target: PERF_TRACE_TARGET,
4341 0 : parent: crnt_perf_span,
4342 : "GET_ANCESTOR",
4343 : timeline = %timeline.timeline_id,
4344 0 : ancestor = %ancestor_timeline.timeline_id,
4345 : ancestor_lsn = %timeline.ancestor_lsn
4346 : )
4347 0 : })
4348 112579 : .attached_child();
4349 :
4350 112579 : timeline_owned = timeline
4351 112579 : .get_ready_ancestor_timeline(ancestor_timeline, &ctx)
4352 112579 : .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
4353 112579 : .await?;
4354 112578 : timeline = &*timeline_owned;
4355 : };
4356 :
4357 : // Remove sparse keys from the keyspace so that it doesn't fire errors.
4358 312343 : let missing_keyspace = if let Some(missing_keyspace) = missing_keyspace {
4359 132 : let mut missing_keyspace = missing_keyspace;
4360 132 : missing_keyspace.remove_overlapping_with(&KeySpace {
4361 132 : ranges: vec![SPARSE_RANGE],
4362 132 : });
4363 132 : if missing_keyspace.is_empty() {
4364 125 : None
4365 : } else {
4366 7 : Some(missing_keyspace)
4367 : }
4368 : } else {
4369 312211 : None
4370 : };
4371 :
4372 312343 : if let Some(missing_keyspace) = missing_keyspace {
4373 7 : return Err(GetVectoredError::MissingKey(Box::new(MissingKeyError {
4374 7 : keyspace: missing_keyspace, /* better if we can store the full keyspace */
4375 7 : shard: self.shard_identity.number,
4376 7 : original_hwm_lsn,
4377 7 : ancestor_lsn: Some(timeline.ancestor_lsn),
4378 7 : backtrace: None,
4379 7 : read_path: std::mem::take(&mut reconstruct_state.read_path),
4380 7 : query: None,
4381 7 : })));
4382 312336 : }
4383 :
4384 312336 : Ok(())
4385 312344 : }
4386 :
4387 424922 : async fn get_vectored_init_fringe(
4388 424922 : &self,
4389 424922 : query: &VersionedKeySpaceQuery,
4390 424922 : ) -> Result<LayerFringe, GetVectoredError> {
4391 424922 : let mut fringe = LayerFringe::new();
4392 424922 : let guard = self.layers.read(LayerManagerLockHolder::GetPage).await;
4393 :
4394 424922 : match query {
4395 414730 : VersionedKeySpaceQuery::Uniform { keyspace, lsn } => {
4396 : // LSNs requested by the compute or determined by the pageserver
4397 : // are inclusive. Queries to the layer map use exclusive LSNs.
4398 : // Hence, bump the value before the query - same in the other
4399 : // match arm.
4400 414730 : let cont_lsn = Lsn(lsn.0 + 1);
4401 414730 : guard.update_search_fringe(keyspace, cont_lsn, &mut fringe)?;
4402 : }
4403 10192 : VersionedKeySpaceQuery::Scattered { keyspaces_at_lsn } => {
4404 21109 : for (lsn, keyspace) in keyspaces_at_lsn.iter() {
4405 21109 : let cont_lsn_for_keyspace = Lsn(lsn.0 + 1);
4406 21109 : guard.update_search_fringe(keyspace, cont_lsn_for_keyspace, &mut fringe)?;
4407 : }
4408 : }
4409 : }
4410 :
4411 424922 : Ok(fringe)
4412 424922 : }
4413 :
4414 : /// Collect the reconstruct data for a keyspace from the specified timeline.
4415 : ///
4416 : /// Maintain a fringe [`LayerFringe`] which tracks all the layers that intersect
4417 : /// the current keyspace. The current keyspace of the search at any given timeline
4418 : /// is the original keyspace minus all the keys that have been completed minus
4419 : /// any keys for which we couldn't find an intersecting layer. It's not tracked explicitly,
4420 : /// but if you merge all the keyspaces in the fringe, you get the "current keyspace".
4421 : ///
4422 : /// This is basically a depth-first search visitor implementation where a vertex
4423 : /// is the (layer, lsn range, key space) tuple. The fringe acts as the stack.
4424 : ///
4425 : /// At each iteration pop the top of the fringe (the layer with the highest Lsn)
4426 : /// and get all the required reconstruct data from the layer in one go.
4427 : ///
4428 : /// Returns the completed keyspace and the keyspaces with image coverage. The caller
4429 : /// decides how to deal with these two keyspaces.
4430 424922 : async fn get_vectored_reconstruct_data_timeline(
4431 424922 : timeline: &Timeline,
4432 424922 : query: &VersionedKeySpaceQuery,
4433 424922 : reconstruct_state: &mut ValuesReconstructState,
4434 424922 : cancel: &CancellationToken,
4435 424922 : ctx: &RequestContext,
4436 424922 : ) -> Result<TimelineVisitOutcome, GetVectoredError> {
4437 : // Prevent GC from progressing while visiting the current timeline.
4438 : // If we are GC-ing because a new image layer was added while traversing
4439 : // the timeline, then it will remove layers that are required for fulfilling
4440 : // the current get request (read-path cannot "look back" and notice the new
4441 : // image layer).
4442 424922 : let _gc_cutoff_holder = timeline.get_applied_gc_cutoff_lsn();
4443 :
4444 : // See `compaction::compact_with_gc` for why we need this.
4445 424922 : let _guard = timeline.gc_compaction_layer_update_lock.read().await;
4446 :
4447 : // Initialize the fringe
4448 424922 : let mut fringe = timeline.get_vectored_init_fringe(query).await?;
4449 :
4450 424922 : let mut completed_keyspace = KeySpace::default();
4451 424922 : let mut image_covered_keyspace = KeySpaceRandomAccum::new();
4452 :
4453 870596 : while let Some((layer_to_read, keyspace_to_read, lsn_range)) = fringe.next_layer() {
4454 445674 : if cancel.is_cancelled() {
4455 0 : return Err(GetVectoredError::Cancelled);
4456 445674 : }
4457 :
4458 445674 : if let Some(ref mut read_path) = reconstruct_state.read_path {
4459 445674 : read_path.record_layer_visit(&layer_to_read, &keyspace_to_read, &lsn_range);
4460 445674 : }
4461 :
4462 : // Visit the layer and plan IOs for it
4463 445674 : let next_cont_lsn = lsn_range.start;
4464 445674 : layer_to_read
4465 445674 : .get_values_reconstruct_data(
4466 445674 : keyspace_to_read.clone(),
4467 445674 : lsn_range,
4468 445674 : reconstruct_state,
4469 445674 : ctx,
4470 445674 : )
4471 445674 : .await?;
4472 :
4473 445674 : let mut unmapped_keyspace = keyspace_to_read;
4474 445674 : let cont_lsn = next_cont_lsn;
4475 :
4476 445674 : reconstruct_state.on_layer_visited(&layer_to_read);
4477 :
4478 445674 : let (keys_done_last_step, keys_with_image_coverage) =
4479 445674 : reconstruct_state.consume_done_keys();
4480 445674 : unmapped_keyspace.remove_overlapping_with(&keys_done_last_step);
4481 445674 : completed_keyspace.merge(&keys_done_last_step);
4482 445674 : if let Some(keys_with_image_coverage) = keys_with_image_coverage {
4483 14122 : unmapped_keyspace
4484 14122 : .remove_overlapping_with(&KeySpace::single(keys_with_image_coverage.clone()));
4485 14122 : image_covered_keyspace.add_range(keys_with_image_coverage);
4486 431552 : }
4487 :
4488 : // Query the layer map for the next layers to read.
4489 : //
4490 : // Do not descent any further if the last layer we visited
4491 : // completed all keys in the keyspace it inspected. This is not
4492 : // required for correctness, but avoids visiting extra layers
4493 : // which turns out to be a perf bottleneck in some cases.
4494 445674 : if !unmapped_keyspace.is_empty() {
4495 129009 : let guard = timeline.layers.read(LayerManagerLockHolder::GetPage).await;
4496 129009 : guard.update_search_fringe(&unmapped_keyspace, cont_lsn, &mut fringe)?;
4497 :
4498 : // It's safe to drop the layer map lock after planning the next round of reads.
4499 : // The fringe keeps readable handles for the layers which are safe to read even
4500 : // if layers were compacted or flushed.
4501 : //
4502 : // The more interesting consideration is: "Why is the read algorithm still correct
4503 : // if the layer map changes while it is operating?". Doing a vectored read on a
4504 : // timeline boils down to pushing an imaginary lsn boundary downwards for each range
4505 : // covered by the read. The layer map tells us how to move the lsn downwards for a
4506 : // range at *a particular point in time*. It is fine for the answer to be different
4507 : // at two different time points.
4508 129009 : drop(guard);
4509 316665 : }
4510 : }
4511 :
4512 424922 : Ok(TimelineVisitOutcome {
4513 424922 : completed_keyspace,
4514 424922 : image_covered_keyspace: image_covered_keyspace.consume_keyspace(),
4515 424922 : })
4516 424922 : }
4517 :
4518 112579 : async fn get_ready_ancestor_timeline(
4519 112579 : &self,
4520 112579 : ancestor: &Arc<Timeline>,
4521 112579 : ctx: &RequestContext,
4522 112579 : ) -> Result<Arc<Timeline>, GetReadyAncestorError> {
4523 : // It's possible that the ancestor timeline isn't active yet, or
4524 : // is active but hasn't yet caught up to the branch point. Wait
4525 : // for it.
4526 : //
4527 : // This cannot happen while the pageserver is running normally,
4528 : // because you cannot create a branch from a point that isn't
4529 : // present in the pageserver yet. However, we don't wait for the
4530 : // branch point to be uploaded to cloud storage before creating
4531 : // a branch. I.e., the branch LSN need not be remote consistent
4532 : // for the branching operation to succeed.
4533 : //
4534 : // Hence, if we try to load a tenant in such a state where
4535 : // 1. the existence of the branch was persisted (in IndexPart and/or locally)
4536 : // 2. but the ancestor state is behind branch_lsn because it was not yet persisted
4537 : // then we will need to wait for the ancestor timeline to
4538 : // re-stream WAL up to branch_lsn before we access it.
4539 : //
4540 : // How can a tenant get in such a state?
4541 : // - ungraceful pageserver process exit
4542 : // - detach+attach => this is a bug, https://github.com/neondatabase/neon/issues/4219
4543 : //
4544 : // NB: this could be avoided by requiring
4545 : // branch_lsn >= remote_consistent_lsn
4546 : // during branch creation.
4547 112579 : match ancestor.wait_to_become_active(ctx).await {
4548 112578 : Ok(()) => {}
4549 : Err(TimelineState::Stopping) => {
4550 : // If an ancestor is stopping, it means the tenant is stopping: handle this the same as if this timeline was stopping.
4551 0 : return Err(GetReadyAncestorError::Cancelled);
4552 : }
4553 1 : Err(state) => {
4554 1 : return Err(GetReadyAncestorError::BadState {
4555 1 : timeline_id: ancestor.timeline_id,
4556 1 : state,
4557 1 : });
4558 : }
4559 : }
4560 112578 : ancestor
4561 112578 : .wait_lsn(
4562 112578 : self.ancestor_lsn,
4563 112578 : WaitLsnWaiter::Timeline(self),
4564 112578 : WaitLsnTimeout::Default,
4565 112578 : ctx,
4566 112578 : )
4567 112578 : .await
4568 112578 : .map_err(|e| match e {
4569 0 : e @ WaitLsnError::Timeout(_) => GetReadyAncestorError::AncestorLsnTimeout(e),
4570 0 : WaitLsnError::Shutdown => GetReadyAncestorError::Cancelled,
4571 0 : WaitLsnError::BadState(state) => GetReadyAncestorError::BadState {
4572 0 : timeline_id: ancestor.timeline_id,
4573 0 : state,
4574 0 : },
4575 0 : })?;
4576 :
4577 112578 : Ok(ancestor.clone())
4578 112579 : }
4579 :
4580 148592 : pub(crate) fn get_shard_identity(&self) -> &ShardIdentity {
4581 148592 : &self.shard_identity
4582 148592 : }
4583 :
4584 : #[inline(always)]
4585 0 : pub(crate) fn shard_timeline_id(&self) -> ShardTimelineId {
4586 0 : ShardTimelineId {
4587 0 : shard_index: ShardIndex {
4588 0 : shard_number: self.shard_identity.number,
4589 0 : shard_count: self.shard_identity.count,
4590 0 : },
4591 0 : timeline_id: self.timeline_id,
4592 0 : }
4593 0 : }
4594 :
4595 : /// Returns a non-frozen open in-memory layer for ingestion.
4596 : ///
4597 : /// Takes a witness of timeline writer state lock being held, because it makes no sense to call
4598 : /// this function without holding the mutex.
4599 659 : async fn get_layer_for_write(
4600 659 : &self,
4601 659 : lsn: Lsn,
4602 659 : _guard: &tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4603 659 : ctx: &RequestContext,
4604 659 : ) -> anyhow::Result<Arc<InMemoryLayer>> {
4605 659 : let mut guard = self
4606 659 : .layers
4607 659 : .write(LayerManagerLockHolder::GetLayerForWrite)
4608 659 : .await;
4609 :
4610 659 : let last_record_lsn = self.get_last_record_lsn();
4611 659 : ensure!(
4612 659 : lsn > last_record_lsn,
4613 0 : "cannot modify relation after advancing last_record_lsn (incoming_lsn={}, last_record_lsn={})",
4614 : lsn,
4615 : last_record_lsn,
4616 : );
4617 :
4618 659 : let layer = guard
4619 659 : .open_mut()?
4620 659 : .get_layer_for_write(
4621 659 : lsn,
4622 659 : self.conf,
4623 659 : self.timeline_id,
4624 659 : self.tenant_shard_id,
4625 659 : &self.gate,
4626 659 : &self.cancel,
4627 659 : ctx,
4628 : )
4629 659 : .await?;
4630 659 : Ok(layer)
4631 659 : }
4632 :
4633 2639558 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
4634 2639558 : assert!(new_lsn.is_aligned());
4635 :
4636 2639558 : self.metrics.last_record_lsn_gauge.set(new_lsn.0 as i64);
4637 2639558 : self.last_record_lsn.advance(new_lsn);
4638 2639558 : }
4639 :
4640 : /// Freeze any existing open in-memory layer and unconditionally notify the flush loop.
4641 : ///
4642 : /// Unconditional flush loop notification is given because in sharded cases we will want to
4643 : /// leave an Lsn gap. Unsharded tenants do not have Lsn gaps.
4644 610 : async fn freeze_inmem_layer_at(
4645 610 : &self,
4646 610 : at: Lsn,
4647 610 : write_lock: &mut tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
4648 610 : ) -> Result<u64, FlushLayerError> {
4649 610 : let frozen = {
4650 610 : let mut guard = self
4651 610 : .layers
4652 610 : .write(LayerManagerLockHolder::TryFreezeLayer)
4653 610 : .await;
4654 610 : guard
4655 610 : .open_mut()?
4656 610 : .try_freeze_in_memory_layer(at, &self.last_freeze_at, write_lock, &self.metrics)
4657 610 : .await
4658 : };
4659 :
4660 610 : if frozen {
4661 596 : let now = Instant::now();
4662 596 : *(self.last_freeze_ts.write().unwrap()) = now;
4663 596 : }
4664 :
4665 : // Increment the flush cycle counter and wake up the flush task.
4666 : // Remember the new value, so that when we listen for the flush
4667 : // to finish, we know when the flush that we initiated has
4668 : // finished, instead of some other flush that was started earlier.
4669 610 : let mut my_flush_request = 0;
4670 :
4671 610 : let flush_loop_state = { *self.flush_loop_state.lock().unwrap() };
4672 610 : if !matches!(flush_loop_state, FlushLoopState::Running { .. }) {
4673 0 : return Err(FlushLayerError::NotRunning(flush_loop_state));
4674 610 : }
4675 :
4676 610 : self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
4677 610 : my_flush_request = *counter + 1;
4678 610 : *counter = my_flush_request;
4679 610 : *lsn = std::cmp::max(at, *lsn);
4680 610 : });
4681 :
4682 610 : assert_ne!(my_flush_request, 0);
4683 :
4684 610 : Ok(my_flush_request)
4685 610 : }
4686 :
4687 : /// Layer flusher task's main loop.
4688 231 : async fn flush_loop(
4689 231 : self: &Arc<Self>,
4690 231 : mut layer_flush_start_rx: tokio::sync::watch::Receiver<(u64, Lsn)>,
4691 231 : ctx: &RequestContext,
4692 231 : ) {
4693 : // Always notify waiters about the flush loop exiting since the loop might stop
4694 : // when the timeline hasn't been cancelled.
4695 231 : let scopeguard_rx = layer_flush_start_rx.clone();
4696 231 : scopeguard::defer! {
4697 : let (flush_counter, _) = *scopeguard_rx.borrow();
4698 : let _ = self
4699 : .layer_flush_done_tx
4700 : .send_replace((flush_counter, Err(FlushLayerError::Cancelled)));
4701 : }
4702 :
4703 : // Subscribe to L0 delta layer updates, for compaction backpressure.
4704 231 : let mut watch_l0 = match self
4705 231 : .layers
4706 231 : .read(LayerManagerLockHolder::FlushLoop)
4707 231 : .await
4708 231 : .layer_map()
4709 : {
4710 231 : Ok(lm) => lm.watch_level0_deltas(),
4711 0 : Err(Shutdown) => return,
4712 : };
4713 :
4714 231 : info!("started flush loop");
4715 : loop {
4716 831 : tokio::select! {
4717 831 : _ = self.cancel.cancelled() => {
4718 5 : info!("shutting down layer flush task due to Timeline::cancel");
4719 5 : break;
4720 : },
4721 831 : _ = layer_flush_start_rx.changed() => {}
4722 : }
4723 600 : trace!("waking up");
4724 600 : let (flush_counter, frozen_to_lsn) = *layer_flush_start_rx.borrow();
4725 :
4726 : // The highest LSN to which we flushed in the loop over frozen layers
4727 600 : let mut flushed_to_lsn = Lsn(0);
4728 :
4729 600 : let result = loop {
4730 1195 : if self.cancel.is_cancelled() {
4731 0 : info!("dropping out of flush loop for timeline shutdown");
4732 0 : return;
4733 1195 : }
4734 :
4735 : // Break to notify potential waiters as soon as we've flushed the requested LSN. If
4736 : // more requests have arrived in the meanwhile, we'll resume flushing afterwards.
4737 1195 : if flushed_to_lsn >= frozen_to_lsn {
4738 585 : break Ok(());
4739 610 : }
4740 :
4741 : // Fetch the next layer to flush, if any.
4742 610 : let (layer, l0_count, frozen_count, frozen_size, open_layer_size) = {
4743 610 : let layers = self.layers.read(LayerManagerLockHolder::FlushLoop).await;
4744 610 : let Ok(lm) = layers.layer_map() else {
4745 0 : info!("dropping out of flush loop for timeline shutdown");
4746 0 : return;
4747 : };
4748 610 : let l0_count = lm.level0_deltas().len();
4749 610 : let frozen_count = lm.frozen_layers.len();
4750 610 : let frozen_size: u64 = lm
4751 610 : .frozen_layers
4752 610 : .iter()
4753 610 : .map(|l| l.estimated_in_mem_size())
4754 610 : .sum();
4755 610 : let open_layer_size: u64 = lm
4756 610 : .open_layer
4757 610 : .as_ref()
4758 610 : .map(|l| l.estimated_in_mem_size())
4759 610 : .unwrap_or(0);
4760 610 : let layer = lm.frozen_layers.front().cloned();
4761 610 : (layer, l0_count, frozen_count, frozen_size, open_layer_size)
4762 : // drop 'layers' lock
4763 : };
4764 610 : let Some(layer) = layer else {
4765 14 : break Ok(());
4766 : };
4767 :
4768 : // Stall flushes to backpressure if compaction can't keep up. This is propagated up
4769 : // to WAL ingestion by having ephemeral layer rolls wait for flushes.
4770 596 : if let Some(stall_threshold) = self.get_l0_flush_stall_threshold() {
4771 0 : if l0_count >= stall_threshold {
4772 0 : warn!(
4773 0 : "stalling layer flushes for compaction backpressure at {l0_count} \
4774 0 : L0 layers ({frozen_count} frozen layers with {frozen_size} bytes, {open_layer_size} bytes in open layer)"
4775 : );
4776 0 : let stall_timer = self
4777 0 : .metrics
4778 0 : .flush_delay_histo
4779 0 : .start_timer()
4780 0 : .record_on_drop();
4781 0 : tokio::select! {
4782 0 : result = watch_l0.wait_for(|l0| *l0 < stall_threshold) => {
4783 0 : if let Ok(l0) = result.as_deref() {
4784 0 : let delay = stall_timer.elapsed().as_secs_f64();
4785 0 : info!("resuming layer flushes at {l0} L0 layers after {delay:.3}s");
4786 0 : }
4787 : },
4788 0 : _ = self.cancel.cancelled() => {},
4789 : }
4790 0 : continue; // check again
4791 0 : }
4792 596 : }
4793 :
4794 : // Flush the layer.
4795 596 : let flush_timer = self.metrics.flush_time_histo.start_timer();
4796 596 : match self.flush_frozen_layer(layer, ctx).await {
4797 595 : Ok(layer_lsn) => flushed_to_lsn = max(flushed_to_lsn, layer_lsn),
4798 : Err(FlushLayerError::Cancelled) => {
4799 0 : info!("dropping out of flush loop for timeline shutdown");
4800 0 : return;
4801 : }
4802 1 : err @ Err(
4803 : FlushLayerError::NotRunning(_)
4804 : | FlushLayerError::Other(_)
4805 : | FlushLayerError::CreateImageLayersError(_),
4806 : ) => {
4807 1 : error!("could not flush frozen layer: {err:?}");
4808 1 : break err.map(|_| ());
4809 : }
4810 : }
4811 595 : let flush_duration = flush_timer.stop_and_record();
4812 :
4813 : // Notify the tenant compaction loop if L0 compaction is needed.
4814 595 : let l0_count = *watch_l0.borrow();
4815 595 : if l0_count >= self.get_compaction_threshold() {
4816 238 : self.l0_compaction_trigger.notify_one();
4817 357 : }
4818 :
4819 : // Delay the next flush to backpressure if compaction can't keep up. We delay by the
4820 : // flush duration such that the flush takes 2x as long. This is propagated up to WAL
4821 : // ingestion by having ephemeral layer rolls wait for flushes.
4822 595 : if let Some(delay_threshold) = self.get_l0_flush_delay_threshold() {
4823 3 : if l0_count >= delay_threshold {
4824 0 : let delay = flush_duration.as_secs_f64();
4825 0 : info!(
4826 0 : "delaying layer flush by {delay:.3}s for compaction backpressure at \
4827 0 : {l0_count} L0 layers ({frozen_count} frozen layers with {frozen_size} bytes, {open_layer_size} bytes in open layer)"
4828 : );
4829 0 : let _delay_timer = self
4830 0 : .metrics
4831 0 : .flush_delay_histo
4832 0 : .start_timer()
4833 0 : .record_on_drop();
4834 0 : tokio::select! {
4835 0 : _ = tokio::time::sleep(flush_duration) => {},
4836 0 : _ = watch_l0.wait_for(|l0| *l0 < delay_threshold) => {},
4837 0 : _ = self.cancel.cancelled() => {},
4838 : }
4839 3 : }
4840 592 : }
4841 : };
4842 :
4843 : // Unsharded tenants should never advance their LSN beyond the end of the
4844 : // highest layer they write: such gaps between layer data and the frozen LSN
4845 : // are only legal on sharded tenants.
4846 600 : debug_assert!(
4847 600 : self.shard_identity.count.count() > 1
4848 593 : || flushed_to_lsn >= frozen_to_lsn
4849 14 : || !flushed_to_lsn.is_valid()
4850 : );
4851 :
4852 600 : if flushed_to_lsn < frozen_to_lsn
4853 15 : && self.shard_identity.count.count() > 1
4854 1 : && result.is_ok()
4855 : {
4856 : // If our layer flushes didn't carry disk_consistent_lsn up to the `to_lsn` advertised
4857 : // to us via layer_flush_start_rx, then advance it here.
4858 : //
4859 : // This path is only taken for tenants with multiple shards: single sharded tenants should
4860 : // never encounter a gap in the wal.
4861 0 : let old_disk_consistent_lsn = self.disk_consistent_lsn.load();
4862 0 : tracing::debug!(
4863 0 : "Advancing disk_consistent_lsn across layer gap {old_disk_consistent_lsn}->{frozen_to_lsn}"
4864 : );
4865 0 : if self.set_disk_consistent_lsn(frozen_to_lsn) {
4866 0 : if let Err(e) = self.schedule_uploads(frozen_to_lsn, vec![]) {
4867 0 : tracing::warn!(
4868 0 : "Failed to schedule metadata upload after updating disk_consistent_lsn: {e}"
4869 : );
4870 0 : }
4871 0 : }
4872 600 : }
4873 :
4874 : // Notify any listeners that we're done
4875 600 : let _ = self
4876 600 : .layer_flush_done_tx
4877 600 : .send_replace((flush_counter, result));
4878 : }
4879 5 : }
4880 :
4881 : /// Waits any flush request created by [`Self::freeze_inmem_layer_at`] to complete.
4882 570 : async fn wait_flush_completion(&self, request: u64) -> Result<(), FlushLayerError> {
4883 570 : let mut rx = self.layer_flush_done_tx.subscribe();
4884 : loop {
4885 : {
4886 1157 : let (last_result_counter, last_result) = &*rx.borrow();
4887 1157 : if *last_result_counter >= request {
4888 570 : if let Err(err) = last_result {
4889 : // We already logged the original error in
4890 : // flush_loop. We cannot propagate it to the caller
4891 : // here, because it might not be Cloneable
4892 1 : return Err(err.clone());
4893 : } else {
4894 569 : return Ok(());
4895 : }
4896 587 : }
4897 : }
4898 587 : trace!("waiting for flush to complete");
4899 587 : tokio::select! {
4900 587 : rx_e = rx.changed() => {
4901 587 : rx_e.map_err(|_| FlushLayerError::NotRunning(*self.flush_loop_state.lock().unwrap()))?;
4902 : },
4903 : // Cancellation safety: we are not leaving an I/O in-flight for the flush, we're just ignoring
4904 : // the notification from [`flush_loop`] that it completed.
4905 587 : _ = self.cancel.cancelled() => {
4906 0 : tracing::info!("Cancelled layer flush due on timeline shutdown");
4907 0 : return Ok(())
4908 : }
4909 : };
4910 587 : trace!("done")
4911 : }
4912 570 : }
4913 :
4914 : /// Flush one frozen in-memory layer to disk, as a new delta layer.
4915 : ///
4916 : /// Return value is the last lsn (inclusive) of the layer that was frozen.
4917 : #[instrument(skip_all, fields(layer=%frozen_layer))]
4918 : async fn flush_frozen_layer(
4919 : self: &Arc<Self>,
4920 : frozen_layer: Arc<InMemoryLayer>,
4921 : ctx: &RequestContext,
4922 : ) -> Result<Lsn, FlushLayerError> {
4923 : debug_assert_current_span_has_tenant_and_timeline_id();
4924 :
4925 : // As a special case, when we have just imported an image into the repository,
4926 : // instead of writing out a L0 delta layer, we directly write out image layer
4927 : // files instead. This is possible as long as *all* the data imported into the
4928 : // repository have the same LSN.
4929 : let lsn_range = frozen_layer.get_lsn_range();
4930 :
4931 : // Whether to directly create image layers for this flush, or flush them as delta layers
4932 : let create_image_layer =
4933 : lsn_range.start == self.initdb_lsn && lsn_range.end == Lsn(self.initdb_lsn.0 + 1);
4934 :
4935 : #[cfg(test)]
4936 : {
4937 : match &mut *self.flush_loop_state.lock().unwrap() {
4938 : FlushLoopState::NotStarted | FlushLoopState::Exited => {
4939 : panic!("flush loop not running")
4940 : }
4941 : FlushLoopState::Running {
4942 : expect_initdb_optimization,
4943 : initdb_optimization_count,
4944 : ..
4945 : } => {
4946 : if create_image_layer {
4947 : *initdb_optimization_count += 1;
4948 : } else {
4949 : assert!(!*expect_initdb_optimization, "expected initdb optimization");
4950 : }
4951 : }
4952 : }
4953 : }
4954 :
4955 : let (layers_to_upload, delta_layer_to_add) = if create_image_layer {
4956 : // Note: The 'ctx' in use here has DownloadBehavior::Error. We should not
4957 : // require downloading anything during initial import.
4958 : let ((rel_partition, metadata_partition), _lsn) = self
4959 : .repartition(
4960 : self.initdb_lsn,
4961 : self.get_compaction_target_size(),
4962 : EnumSet::empty(),
4963 : ctx,
4964 : )
4965 : .await
4966 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e.into()))?;
4967 :
4968 : if self.cancel.is_cancelled() {
4969 : return Err(FlushLayerError::Cancelled);
4970 : }
4971 :
4972 : // Ensure that we have a single call to `create_image_layers` with a combined dense keyspace.
4973 : // So that the key ranges don't overlap.
4974 : let mut partitions = KeyPartitioning::default();
4975 : partitions.parts.extend(rel_partition.parts);
4976 : if !metadata_partition.parts.is_empty() {
4977 : assert_eq!(
4978 : metadata_partition.parts.len(),
4979 : 1,
4980 : "currently sparse keyspace should only contain a single metadata keyspace"
4981 : );
4982 : // Safety: create_image_layers treat sparse keyspaces differently that it does not scan
4983 : // every single key within the keyspace, and therefore, it's safe to force converting it
4984 : // into a dense keyspace before calling this function.
4985 : partitions
4986 : .parts
4987 : .extend(metadata_partition.into_dense().parts);
4988 : }
4989 :
4990 : let mut layers_to_upload = Vec::new();
4991 : let (generated_image_layers, is_complete) = self
4992 : .create_image_layers(
4993 : &partitions,
4994 : self.initdb_lsn,
4995 : ImageLayerCreationMode::Initial,
4996 : ctx,
4997 : LastImageLayerCreationStatus::Initial,
4998 : false, // don't yield for L0, we're flushing L0
4999 : )
5000 : .instrument(info_span!("create_image_layers", mode = %ImageLayerCreationMode::Initial, partition_mode = "initial", lsn = %self.initdb_lsn))
5001 : .await?;
5002 : debug_assert!(
5003 : matches!(is_complete, LastImageLayerCreationStatus::Complete),
5004 : "init image generation mode must fully cover the keyspace"
5005 : );
5006 : layers_to_upload.extend(generated_image_layers);
5007 :
5008 : (layers_to_upload, None)
5009 : } else {
5010 : // Normal case, write out a L0 delta layer file.
5011 : // `create_delta_layer` will not modify the layer map.
5012 : // We will remove frozen layer and add delta layer in one atomic operation later.
5013 : let Some(layer) = self
5014 : .create_delta_layer(&frozen_layer, None, ctx)
5015 : .await
5016 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?
5017 : else {
5018 : panic!("delta layer cannot be empty if no filter is applied");
5019 : };
5020 : (
5021 : // FIXME: even though we have a single image and single delta layer assumption
5022 : // we push them to vec
5023 : vec![layer.clone()],
5024 : Some(layer),
5025 : )
5026 : };
5027 :
5028 : pausable_failpoint!("flush-layer-cancel-after-writing-layer-out-pausable");
5029 :
5030 : if self.cancel.is_cancelled() {
5031 : return Err(FlushLayerError::Cancelled);
5032 : }
5033 :
5034 1 : fail_point!("flush-layer-before-update-remote-consistent-lsn", |_| {
5035 1 : Err(FlushLayerError::Other(anyhow!("failpoint").into()))
5036 1 : });
5037 :
5038 : let disk_consistent_lsn = Lsn(lsn_range.end.0 - 1);
5039 :
5040 : // The new on-disk layers are now in the layer map. We can remove the
5041 : // in-memory layer from the map now. The flushed layer is stored in
5042 : // the mapping in `create_delta_layer`.
5043 : {
5044 : let mut guard = self
5045 : .layers
5046 : .write(LayerManagerLockHolder::FlushFrozenLayer)
5047 : .await;
5048 :
5049 : guard.open_mut()?.finish_flush_l0_layer(
5050 : delta_layer_to_add.as_ref(),
5051 : &frozen_layer,
5052 : &self.metrics,
5053 : );
5054 :
5055 : if self.set_disk_consistent_lsn(disk_consistent_lsn) {
5056 : // Schedule remote uploads that will reflect our new disk_consistent_lsn
5057 : self.schedule_uploads(disk_consistent_lsn, layers_to_upload)
5058 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?;
5059 : }
5060 : // release lock on 'layers'
5061 : };
5062 :
5063 : // FIXME: between create_delta_layer and the scheduling of the upload in `update_metadata_file`,
5064 : // a compaction can delete the file and then it won't be available for uploads any more.
5065 : // We still schedule the upload, resulting in an error, but ideally we'd somehow avoid this
5066 : // race situation.
5067 : // See https://github.com/neondatabase/neon/issues/4526
5068 : pausable_failpoint!("flush-frozen-pausable");
5069 :
5070 : // This failpoint is used by another test case `test_pageserver_recovery`.
5071 : fail_point!("flush-frozen-exit");
5072 :
5073 : Ok(Lsn(lsn_range.end.0 - 1))
5074 : }
5075 :
5076 : /// Return true if the value changed
5077 : ///
5078 : /// This function must only be used from the layer flush task.
5079 595 : fn set_disk_consistent_lsn(&self, new_value: Lsn) -> bool {
5080 595 : let old_value = self.disk_consistent_lsn.fetch_max(new_value);
5081 595 : assert!(
5082 595 : new_value >= old_value,
5083 0 : "disk_consistent_lsn must be growing monotonously at runtime; current {old_value}, offered {new_value}"
5084 : );
5085 :
5086 595 : self.metrics
5087 595 : .disk_consistent_lsn_gauge
5088 595 : .set(new_value.0 as i64);
5089 595 : new_value != old_value
5090 595 : }
5091 :
5092 : /// Update metadata file
5093 622 : fn schedule_uploads(
5094 622 : &self,
5095 622 : disk_consistent_lsn: Lsn,
5096 622 : layers_to_upload: impl IntoIterator<Item = ResidentLayer>,
5097 622 : ) -> anyhow::Result<()> {
5098 : // We can only save a valid 'prev_record_lsn' value on disk if we
5099 : // flushed *all* in-memory changes to disk. We only track
5100 : // 'prev_record_lsn' in memory for the latest processed record, so we
5101 : // don't remember what the correct value that corresponds to some old
5102 : // LSN is. But if we flush everything, then the value corresponding
5103 : // current 'last_record_lsn' is correct and we can store it on disk.
5104 : let RecordLsn {
5105 622 : last: last_record_lsn,
5106 622 : prev: prev_record_lsn,
5107 622 : } = self.last_record_lsn.load();
5108 622 : let ondisk_prev_record_lsn = if disk_consistent_lsn == last_record_lsn {
5109 560 : Some(prev_record_lsn)
5110 : } else {
5111 62 : None
5112 : };
5113 :
5114 622 : let update = crate::tenant::metadata::MetadataUpdate::new(
5115 622 : disk_consistent_lsn,
5116 622 : ondisk_prev_record_lsn,
5117 622 : *self.applied_gc_cutoff_lsn.read(),
5118 : );
5119 :
5120 622 : fail_point!("checkpoint-before-saving-metadata", |x| bail!(
5121 0 : "{}",
5122 0 : x.unwrap()
5123 : ));
5124 :
5125 1223 : for layer in layers_to_upload {
5126 601 : self.remote_client.schedule_layer_file_upload(layer)?;
5127 : }
5128 622 : self.remote_client
5129 622 : .schedule_index_upload_for_metadata_update(&update)?;
5130 :
5131 622 : Ok(())
5132 622 : }
5133 :
5134 0 : pub(crate) async fn preserve_initdb_archive(&self) -> anyhow::Result<()> {
5135 0 : self.remote_client
5136 0 : .preserve_initdb_archive(
5137 0 : &self.tenant_shard_id.tenant_id,
5138 0 : &self.timeline_id,
5139 0 : &self.cancel,
5140 0 : )
5141 0 : .await
5142 0 : }
5143 :
5144 : // Write out the given frozen in-memory layer as a new L0 delta file. This L0 file will not be tracked
5145 : // in layer map immediately. The caller is responsible to put it into the layer map.
5146 486 : async fn create_delta_layer(
5147 486 : self: &Arc<Self>,
5148 486 : frozen_layer: &Arc<InMemoryLayer>,
5149 486 : key_range: Option<Range<Key>>,
5150 486 : ctx: &RequestContext,
5151 486 : ) -> anyhow::Result<Option<ResidentLayer>> {
5152 486 : let self_clone = Arc::clone(self);
5153 486 : let frozen_layer = Arc::clone(frozen_layer);
5154 486 : let ctx = ctx.attached_child();
5155 486 : let work = async move {
5156 486 : let Some((desc, path)) = frozen_layer
5157 486 : .write_to_disk(
5158 486 : &ctx,
5159 486 : key_range,
5160 486 : self_clone.l0_flush_global_state.inner(),
5161 486 : &self_clone.gate,
5162 486 : self_clone.cancel.clone(),
5163 486 : )
5164 486 : .await?
5165 : else {
5166 0 : return Ok(None);
5167 : };
5168 486 : let new_delta = Layer::finish_creating(self_clone.conf, &self_clone, desc, &path)?;
5169 :
5170 : // The write_to_disk() above calls writer.finish() which already did the fsync of the inodes.
5171 : // We just need to fsync the directory in which these inodes are linked,
5172 : // which we know to be the timeline directory.
5173 : //
5174 : // We use fatal_err() below because the after write_to_disk returns with success,
5175 : // the in-memory state of the filesystem already has the layer file in its final place,
5176 : // and subsequent pageserver code could think it's durable while it really isn't.
5177 486 : let timeline_dir = VirtualFile::open(
5178 486 : &self_clone
5179 486 : .conf
5180 486 : .timeline_path(&self_clone.tenant_shard_id, &self_clone.timeline_id),
5181 486 : &ctx,
5182 486 : )
5183 486 : .await
5184 486 : .fatal_err("VirtualFile::open for timeline dir fsync");
5185 486 : timeline_dir
5186 486 : .sync_all()
5187 486 : .await
5188 486 : .fatal_err("VirtualFile::sync_all timeline dir");
5189 486 : anyhow::Ok(Some(new_delta))
5190 486 : };
5191 : // Before tokio-epoll-uring, we ran write_to_disk & the sync_all inside spawn_blocking.
5192 : // Preserve that behavior to maintain the same behavior for `virtual_file_io_engine=std-fs`.
5193 : use crate::virtual_file::io_engine::IoEngine;
5194 486 : match crate::virtual_file::io_engine::get() {
5195 0 : IoEngine::NotSet => panic!("io engine not set"),
5196 : IoEngine::StdFs => {
5197 0 : let span = tracing::info_span!("blocking");
5198 0 : tokio::task::spawn_blocking({
5199 0 : move || Handle::current().block_on(work.instrument(span))
5200 : })
5201 0 : .await
5202 0 : .context("spawn_blocking")
5203 0 : .and_then(|x| x)
5204 : }
5205 : #[cfg(target_os = "linux")]
5206 486 : IoEngine::TokioEpollUring => work.await,
5207 : }
5208 486 : }
5209 :
5210 302 : async fn repartition(
5211 302 : &self,
5212 302 : lsn: Lsn,
5213 302 : partition_size: u64,
5214 302 : flags: EnumSet<CompactFlags>,
5215 302 : ctx: &RequestContext,
5216 302 : ) -> Result<((KeyPartitioning, SparseKeyPartitioning), Lsn), CompactionError> {
5217 302 : let Ok(mut guard) = self.partitioning.try_write_guard() else {
5218 : // NB: there are two callers, one is the compaction task, of which there is only one per struct Tenant and hence Timeline.
5219 : // The other is the initdb optimization in flush_frozen_layer, used by `boostrap_timeline`, which runs before `.activate()`
5220 : // and hence before the compaction task starts.
5221 0 : return Err(CompactionError::Other(anyhow!(
5222 0 : "repartition() called concurrently"
5223 0 : )));
5224 : };
5225 302 : let ((dense_partition, sparse_partition), partition_lsn) = &*guard.read();
5226 302 : if lsn < *partition_lsn {
5227 0 : return Err(CompactionError::Other(anyhow!(
5228 0 : "repartition() called with LSN going backwards, this should not happen"
5229 0 : )));
5230 302 : }
5231 :
5232 302 : let distance = lsn.0 - partition_lsn.0;
5233 302 : if *partition_lsn != Lsn(0)
5234 141 : && distance <= self.repartition_threshold
5235 141 : && !flags.contains(CompactFlags::ForceRepartition)
5236 : {
5237 134 : debug!(
5238 : distance,
5239 : threshold = self.repartition_threshold,
5240 0 : "no repartitioning needed"
5241 : );
5242 134 : return Ok((
5243 134 : (dense_partition.clone(), sparse_partition.clone()),
5244 134 : *partition_lsn,
5245 134 : ));
5246 168 : }
5247 :
5248 168 : let (dense_ks, sparse_ks) = self.collect_keyspace(lsn, ctx).await?;
5249 168 : let dense_partitioning = dense_ks.partition(
5250 168 : &self.shard_identity,
5251 168 : partition_size,
5252 168 : postgres_ffi::BLCKSZ as u64,
5253 : );
5254 168 : let sparse_partitioning = SparseKeyPartitioning {
5255 168 : parts: vec![sparse_ks],
5256 168 : }; // no partitioning for metadata keys for now
5257 168 : let result = ((dense_partitioning, sparse_partitioning), lsn);
5258 168 : guard.write(result.clone());
5259 168 : Ok(result)
5260 302 : }
5261 :
5262 : // Is it time to create a new image layer for the given partition? True if we want to generate.
5263 7 : async fn time_for_new_image_layer(&self, partition: &KeySpace, lsn: Lsn) -> bool {
5264 7 : let threshold = self.get_image_creation_threshold();
5265 :
5266 7 : let guard = self.layers.read(LayerManagerLockHolder::Compaction).await;
5267 7 : let Ok(layers) = guard.layer_map() else {
5268 0 : return false;
5269 : };
5270 :
5271 7 : let mut max_deltas = 0;
5272 14 : for part_range in &partition.ranges {
5273 7 : let image_coverage = layers.image_coverage(part_range, lsn);
5274 14 : for (img_range, last_img) in image_coverage {
5275 7 : let img_lsn = if let Some(last_img) = last_img {
5276 0 : last_img.get_lsn_range().end
5277 : } else {
5278 7 : Lsn(0)
5279 : };
5280 : // Let's consider an example:
5281 : //
5282 : // delta layer with LSN range 71-81
5283 : // delta layer with LSN range 81-91
5284 : // delta layer with LSN range 91-101
5285 : // image layer at LSN 100
5286 : //
5287 : // If 'lsn' is still 100, i.e. no new WAL has been processed since the last image layer,
5288 : // there's no need to create a new one. We check this case explicitly, to avoid passing
5289 : // a bogus range to count_deltas below, with start > end. It's even possible that there
5290 : // are some delta layers *later* than current 'lsn', if more WAL was processed and flushed
5291 : // after we read last_record_lsn, which is passed here in the 'lsn' argument.
5292 7 : if img_lsn < lsn {
5293 7 : let num_deltas =
5294 7 : layers.count_deltas(&img_range, &(img_lsn..lsn), Some(threshold));
5295 :
5296 7 : max_deltas = max_deltas.max(num_deltas);
5297 7 : if num_deltas >= threshold {
5298 0 : debug!(
5299 0 : "key range {}-{}, has {} deltas on this timeline in LSN range {}..{}",
5300 : img_range.start, img_range.end, num_deltas, img_lsn, lsn
5301 : );
5302 0 : return true;
5303 7 : }
5304 0 : }
5305 : }
5306 : }
5307 :
5308 7 : debug!(
5309 : max_deltas,
5310 0 : "none of the partitioned ranges had >= {threshold} deltas"
5311 : );
5312 7 : false
5313 7 : }
5314 :
5315 : /// Create image layers for Postgres data. Assumes the caller passes a partition that is not too large,
5316 : /// so that at most one image layer will be produced from this function.
5317 : #[allow(clippy::too_many_arguments)]
5318 123 : async fn create_image_layer_for_rel_blocks(
5319 123 : self: &Arc<Self>,
5320 123 : partition: &KeySpace,
5321 123 : mut image_layer_writer: ImageLayerWriter,
5322 123 : lsn: Lsn,
5323 123 : ctx: &RequestContext,
5324 123 : img_range: Range<Key>,
5325 123 : io_concurrency: IoConcurrency,
5326 123 : progress: Option<(usize, usize)>,
5327 123 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
5328 123 : let mut wrote_keys = false;
5329 :
5330 123 : let mut key_request_accum = KeySpaceAccum::new();
5331 817 : for range in &partition.ranges {
5332 694 : let mut key = range.start;
5333 1504 : while key < range.end {
5334 : // Decide whether to retain this key: usually we do, but sharded tenants may
5335 : // need to drop keys that don't belong to them. If we retain the key, add it
5336 : // to `key_request_accum` for later issuing a vectored get
5337 810 : if self.shard_identity.is_key_disposable(&key) {
5338 0 : debug!(
5339 0 : "Dropping key {} during compaction (it belongs on shard {:?})",
5340 : key,
5341 0 : self.shard_identity.get_shard_number(&key)
5342 : );
5343 810 : } else {
5344 810 : key_request_accum.add_key(key);
5345 810 : }
5346 :
5347 810 : let last_key_in_range = key.next() == range.end;
5348 810 : key = key.next();
5349 :
5350 : // Maybe flush `key_rest_accum`
5351 810 : if key_request_accum.raw_size() >= self.conf.max_get_vectored_keys.get() as u64
5352 810 : || (last_key_in_range && key_request_accum.raw_size() > 0)
5353 : {
5354 694 : let query =
5355 694 : VersionedKeySpaceQuery::uniform(key_request_accum.consume_keyspace(), lsn);
5356 :
5357 694 : let results = self
5358 694 : .get_vectored(query, io_concurrency.clone(), ctx)
5359 694 : .await?;
5360 :
5361 694 : if self.cancel.is_cancelled() {
5362 0 : return Err(CreateImageLayersError::Cancelled);
5363 694 : }
5364 :
5365 1504 : for (img_key, img) in results {
5366 810 : let img = match img {
5367 810 : Ok(img) => img,
5368 0 : Err(err) => {
5369 : // If we fail to reconstruct a VM or FSM page, we can zero the
5370 : // page without losing any actual user data. That seems better
5371 : // than failing repeatedly and getting stuck.
5372 : //
5373 : // We had a bug at one point, where we truncated the FSM and VM
5374 : // in the pageserver, but the Postgres didn't know about that
5375 : // and continued to generate incremental WAL records for pages
5376 : // that didn't exist in the pageserver. Trying to replay those
5377 : // WAL records failed to find the previous image of the page.
5378 : // This special case allows us to recover from that situation.
5379 : // See https://github.com/neondatabase/neon/issues/2601.
5380 : //
5381 : // Unfortunately we cannot do this for the main fork, or for
5382 : // any metadata keys, keys, as that would lead to actual data
5383 : // loss.
5384 0 : if img_key.is_rel_fsm_block_key() || img_key.is_rel_vm_block_key() {
5385 0 : warn!(
5386 0 : "could not reconstruct FSM or VM key {img_key}, filling with zeros: {err:?}"
5387 : );
5388 0 : ZERO_PAGE.clone()
5389 : } else {
5390 0 : return Err(CreateImageLayersError::from(err));
5391 : }
5392 : }
5393 : };
5394 :
5395 : // Write all the keys we just read into our new image layer.
5396 810 : image_layer_writer.put_image(img_key, img, ctx).await?;
5397 810 : wrote_keys = true;
5398 : }
5399 116 : }
5400 : }
5401 : }
5402 :
5403 123 : let progress_report = progress
5404 123 : .map(|(idx, total)| format!("({idx}/{total}) "))
5405 123 : .unwrap_or_default();
5406 123 : if wrote_keys {
5407 : // Normal path: we have written some data into the new image layer for this
5408 : // partition, so flush it to disk.
5409 123 : info!(
5410 0 : "{} produced image layer for rel {}",
5411 : progress_report,
5412 0 : ImageLayerName {
5413 0 : key_range: img_range.clone(),
5414 0 : lsn
5415 0 : },
5416 : );
5417 123 : Ok(ImageLayerCreationOutcome::Generated {
5418 123 : unfinished_image_layer: image_layer_writer,
5419 123 : })
5420 : } else {
5421 0 : tracing::debug!(
5422 0 : "{} no data in range {}-{}",
5423 : progress_report,
5424 : img_range.start,
5425 : img_range.end
5426 : );
5427 0 : Ok(ImageLayerCreationOutcome::Empty)
5428 : }
5429 123 : }
5430 :
5431 : /// Create an image layer for metadata keys. This function produces one image layer for all metadata
5432 : /// keys for now. Because metadata keys cannot exceed basebackup size limit, the image layer for it
5433 : /// would not be too large to fit in a single image layer.
5434 : ///
5435 : /// Creating image layers for metadata keys are different from relational keys. Firstly, instead of
5436 : /// iterating each key and get an image for each of them, we do a `vectored_get` scan over the sparse
5437 : /// keyspace to get all images in one run. Secondly, we use a different image layer generation metrics
5438 : /// for metadata keys than relational keys, which is the number of delta files visited during the scan.
5439 : #[allow(clippy::too_many_arguments)]
5440 118 : async fn create_image_layer_for_metadata_keys(
5441 118 : self: &Arc<Self>,
5442 118 : partition: &KeySpace,
5443 118 : mut image_layer_writer: ImageLayerWriter,
5444 118 : lsn: Lsn,
5445 118 : ctx: &RequestContext,
5446 118 : img_range: Range<Key>,
5447 118 : mode: ImageLayerCreationMode,
5448 118 : io_concurrency: IoConcurrency,
5449 118 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
5450 : // Metadata keys image layer creation.
5451 118 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
5452 118 : let begin = Instant::now();
5453 : // Directly use `get_vectored_impl` to skip the max_vectored_read_key limit check. Note that the keyspace should
5454 : // not contain too many keys, otherwise this takes a lot of memory.
5455 118 : let data = self
5456 118 : .get_vectored_impl(
5457 118 : VersionedKeySpaceQuery::uniform(partition.clone(), lsn),
5458 118 : &mut reconstruct_state,
5459 118 : ctx,
5460 118 : )
5461 118 : .await?;
5462 118 : let (data, total_kb_retrieved, total_keys_retrieved) = {
5463 118 : let mut new_data = BTreeMap::new();
5464 118 : let mut total_kb_retrieved = 0;
5465 118 : let mut total_keys_retrieved = 0;
5466 5124 : for (k, v) in data {
5467 5006 : let v = v?;
5468 5006 : total_kb_retrieved += KEY_SIZE + v.len();
5469 5006 : total_keys_retrieved += 1;
5470 5006 : new_data.insert(k, v);
5471 : }
5472 118 : (new_data, total_kb_retrieved / 1024, total_keys_retrieved)
5473 : };
5474 118 : let delta_files_accessed = reconstruct_state.get_delta_layers_visited();
5475 118 : let elapsed = begin.elapsed();
5476 :
5477 118 : let trigger_generation = delta_files_accessed as usize >= MAX_AUX_FILE_V2_DELTAS;
5478 118 : info!(
5479 0 : "metadata key compaction: trigger_generation={trigger_generation}, delta_files_accessed={delta_files_accessed}, total_kb_retrieved={total_kb_retrieved}, total_keys_retrieved={total_keys_retrieved}, read_time={}s",
5480 0 : elapsed.as_secs_f64()
5481 : );
5482 :
5483 118 : if !trigger_generation && mode == ImageLayerCreationMode::Try {
5484 1 : return Ok(ImageLayerCreationOutcome::Skip);
5485 117 : }
5486 117 : if self.cancel.is_cancelled() {
5487 0 : return Err(CreateImageLayersError::Cancelled);
5488 117 : }
5489 117 : let mut wrote_any_image = false;
5490 5123 : for (k, v) in data {
5491 5006 : if v.is_empty() {
5492 : // the key has been deleted, it does not need an image
5493 : // in metadata keyspace, an empty image == tombstone
5494 4 : continue;
5495 5002 : }
5496 5002 : wrote_any_image = true;
5497 :
5498 : // No need to handle sharding b/c metadata keys are always on the 0-th shard.
5499 :
5500 : // TODO: split image layers to avoid too large layer files. Too large image files are not handled
5501 : // on the normal data path either.
5502 5002 : image_layer_writer.put_image(k, v, ctx).await?;
5503 : }
5504 :
5505 117 : if wrote_any_image {
5506 : // Normal path: we have written some data into the new image layer for this
5507 : // partition, so flush it to disk.
5508 6 : info!(
5509 0 : "created image layer for metadata {}",
5510 0 : ImageLayerName {
5511 0 : key_range: img_range.clone(),
5512 0 : lsn
5513 0 : }
5514 : );
5515 6 : Ok(ImageLayerCreationOutcome::Generated {
5516 6 : unfinished_image_layer: image_layer_writer,
5517 6 : })
5518 : } else {
5519 111 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
5520 111 : Ok(ImageLayerCreationOutcome::Empty)
5521 : }
5522 118 : }
5523 :
5524 : /// Predicate function which indicates whether we should check if new image layers
5525 : /// are required. Since checking if new image layers are required is expensive in
5526 : /// terms of CPU, we only do it in the following cases:
5527 : /// 1. If the timeline has ingested sufficient WAL to justify the cost
5528 : /// 2. If enough time has passed since the last check:
5529 : /// 1. For large tenants, we wish to perform the check more often since they
5530 : /// suffer from the lack of image layers
5531 : /// 2. For small tenants (that can mostly fit in RAM), we use a much longer interval
5532 190 : fn should_check_if_image_layers_required(self: &Arc<Timeline>, lsn: Lsn) -> bool {
5533 : const LARGE_TENANT_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
5534 :
5535 190 : let last_checks_at = self.last_image_layer_creation_check_at.load();
5536 190 : let distance = lsn
5537 190 : .checked_sub(last_checks_at)
5538 190 : .expect("Attempt to compact with LSN going backwards");
5539 190 : let min_distance =
5540 190 : self.get_image_layer_creation_check_threshold() as u64 * self.get_checkpoint_distance();
5541 :
5542 190 : let distance_based_decision = distance.0 >= min_distance;
5543 :
5544 190 : let mut time_based_decision = false;
5545 190 : let mut last_check_instant = self.last_image_layer_creation_check_instant.lock().unwrap();
5546 190 : if let CurrentLogicalSize::Exact(logical_size) = self.current_logical_size.current_size() {
5547 139 : let check_required_after = if Into::<u64>::into(&logical_size) >= LARGE_TENANT_THRESHOLD
5548 : {
5549 0 : self.get_checkpoint_timeout()
5550 : } else {
5551 139 : Duration::from_secs(3600 * 48)
5552 : };
5553 :
5554 139 : time_based_decision = match *last_check_instant {
5555 29 : Some(last_check) => {
5556 29 : let elapsed = last_check.elapsed();
5557 29 : elapsed >= check_required_after
5558 : }
5559 110 : None => true,
5560 : };
5561 51 : }
5562 :
5563 : // Do the expensive delta layer counting only if this timeline has ingested sufficient
5564 : // WAL since the last check or a checkpoint timeout interval has elapsed since the last
5565 : // check.
5566 190 : let decision = distance_based_decision || time_based_decision;
5567 :
5568 190 : if decision {
5569 111 : self.last_image_layer_creation_check_at.store(lsn);
5570 111 : *last_check_instant = Some(Instant::now());
5571 111 : }
5572 :
5573 190 : decision
5574 190 : }
5575 :
5576 : /// Returns the image layers generated and an enum indicating whether the process is fully completed.
5577 : /// true = we have generate all image layers, false = we preempt the process for L0 compaction.
5578 : ///
5579 : /// `partition_mode` is only for logging purpose and is not used anywhere in this function.
5580 190 : async fn create_image_layers(
5581 190 : self: &Arc<Timeline>,
5582 190 : partitioning: &KeyPartitioning,
5583 190 : lsn: Lsn,
5584 190 : mode: ImageLayerCreationMode,
5585 190 : ctx: &RequestContext,
5586 190 : last_status: LastImageLayerCreationStatus,
5587 190 : yield_for_l0: bool,
5588 190 : ) -> Result<(Vec<ResidentLayer>, LastImageLayerCreationStatus), CreateImageLayersError> {
5589 190 : let timer = self.metrics.create_images_time_histo.start_timer();
5590 :
5591 190 : if partitioning.parts.is_empty() {
5592 0 : warn!("no partitions to create image layers for");
5593 0 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5594 190 : }
5595 :
5596 : // We need to avoid holes between generated image layers.
5597 : // Otherwise LayerMap::image_layer_exists will return false if key range of some layer is covered by more than one
5598 : // image layer with hole between them. In this case such layer can not be utilized by GC.
5599 : //
5600 : // How such hole between partitions can appear?
5601 : // if we have relation with relid=1 and size 100 and relation with relid=2 with size 200 then result of
5602 : // KeySpace::partition may contain partitions <100000000..100000099> and <200000000..200000199>.
5603 : // If there is delta layer <100000000..300000000> then it never be garbage collected because
5604 : // image layers <100000000..100000099> and <200000000..200000199> are not completely covering it.
5605 190 : let mut start = Key::MIN;
5606 :
5607 190 : let check_for_image_layers =
5608 190 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5609 0 : info!(
5610 0 : "resuming image layer creation: last_status=incomplete, continue from {}",
5611 : last_key
5612 : );
5613 0 : true
5614 : } else {
5615 190 : self.should_check_if_image_layers_required(lsn)
5616 : };
5617 :
5618 190 : let mut batch_image_writer = BatchLayerWriter::new(self.conf);
5619 :
5620 190 : let mut all_generated = true;
5621 :
5622 190 : let mut partition_processed = 0;
5623 190 : let mut total_partitions = partitioning.parts.len();
5624 190 : let mut last_partition_processed = None;
5625 190 : let mut partition_parts = partitioning.parts.clone();
5626 :
5627 190 : if let LastImageLayerCreationStatus::Incomplete { last_key } = last_status {
5628 : // We need to skip the partitions that have already been processed.
5629 0 : let mut found = false;
5630 0 : for (i, partition) in partition_parts.iter().enumerate() {
5631 0 : if last_key <= partition.end().unwrap() {
5632 : // ```plain
5633 : // |------|--------|----------|------|
5634 : // ^last_key
5635 : // ^start from this partition
5636 : // ```
5637 : // Why `i+1` instead of `i`?
5638 : // It is possible that the user did some writes after the previous image layer creation attempt so that
5639 : // a relation grows in size, and the last_key is now in the middle of the partition. In this case, we
5640 : // still want to skip this partition, so that we can make progress and avoid generating image layers over
5641 : // the same partition. Doing a mod to ensure we don't end up with an empty vec.
5642 0 : if i + 1 >= total_partitions {
5643 : // In general, this case should not happen -- if last_key is on the last partition, the previous
5644 : // iteration of image layer creation should return a complete status.
5645 0 : break; // with found=false
5646 0 : }
5647 0 : partition_parts = partition_parts.split_off(i + 1); // Remove the first i + 1 elements
5648 0 : total_partitions = partition_parts.len();
5649 : // Update the start key to the partition start.
5650 0 : start = partition_parts[0].start().unwrap();
5651 0 : found = true;
5652 0 : break;
5653 0 : }
5654 : }
5655 0 : if !found {
5656 : // Last key is within the last partition, or larger than all partitions.
5657 0 : return Ok((vec![], LastImageLayerCreationStatus::Complete));
5658 0 : }
5659 190 : }
5660 :
5661 190 : let total = partition_parts.len();
5662 392 : for (idx, partition) in partition_parts.iter().enumerate() {
5663 392 : if self.cancel.is_cancelled() {
5664 0 : return Err(CreateImageLayersError::Cancelled);
5665 392 : }
5666 392 : partition_processed += 1;
5667 392 : let img_range = start..partition.ranges.last().unwrap().end;
5668 392 : let compact_metadata = partition.overlaps(&Key::metadata_key_range());
5669 392 : if compact_metadata {
5670 760 : for range in &partition.ranges {
5671 570 : assert!(
5672 570 : range.start.field1 >= METADATA_KEY_BEGIN_PREFIX
5673 570 : && range.end.field1 <= METADATA_KEY_END_PREFIX,
5674 0 : "metadata keys must be partitioned separately"
5675 : );
5676 : }
5677 190 : if mode == ImageLayerCreationMode::Try && !check_for_image_layers {
5678 : // Skip compaction if there are not enough updates. Metadata compaction will do a scan and
5679 : // might mess up with evictions.
5680 72 : start = img_range.end;
5681 72 : continue;
5682 118 : }
5683 : // For initial and force modes, we always generate image layers for metadata keys.
5684 202 : } else if let ImageLayerCreationMode::Try = mode {
5685 : // check_for_image_layers = false -> skip
5686 : // check_for_image_layers = true -> check time_for_new_image_layer -> skip/generate
5687 79 : if !check_for_image_layers || !self.time_for_new_image_layer(partition, lsn).await {
5688 79 : start = img_range.end;
5689 79 : continue;
5690 0 : }
5691 123 : }
5692 241 : if let ImageLayerCreationMode::Force = mode {
5693 : // When forced to create image layers, we might try and create them where they already
5694 : // exist. This mode is only used in tests/debug.
5695 14 : let layers = self.layers.read(LayerManagerLockHolder::Compaction).await;
5696 14 : if layers.contains_key(&PersistentLayerKey {
5697 14 : key_range: img_range.clone(),
5698 14 : lsn_range: PersistentLayerDesc::image_layer_lsn_range(lsn),
5699 14 : is_delta: false,
5700 14 : }) {
5701 : // TODO: this can be processed with the BatchLayerWriter::finish_with_discard
5702 : // in the future.
5703 0 : tracing::info!(
5704 0 : "Skipping image layer at {lsn} {}..{}, already exists",
5705 : img_range.start,
5706 : img_range.end
5707 : );
5708 0 : start = img_range.end;
5709 0 : continue;
5710 14 : }
5711 227 : }
5712 :
5713 241 : let image_layer_writer = ImageLayerWriter::new(
5714 241 : self.conf,
5715 241 : self.timeline_id,
5716 241 : self.tenant_shard_id,
5717 241 : &img_range,
5718 241 : lsn,
5719 241 : &self.gate,
5720 241 : self.cancel.clone(),
5721 241 : ctx,
5722 241 : )
5723 241 : .await
5724 241 : .map_err(CreateImageLayersError::Other)?;
5725 :
5726 241 : fail_point!("image-layer-writer-fail-before-finish", |_| {
5727 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
5728 0 : "failpoint image-layer-writer-fail-before-finish"
5729 0 : )))
5730 0 : });
5731 :
5732 241 : let io_concurrency = IoConcurrency::spawn_from_conf(
5733 241 : self.conf.get_vectored_concurrent_io,
5734 241 : self.gate
5735 241 : .enter()
5736 241 : .map_err(|_| CreateImageLayersError::Cancelled)?,
5737 : );
5738 :
5739 241 : let outcome = if !compact_metadata {
5740 123 : self.create_image_layer_for_rel_blocks(
5741 123 : partition,
5742 123 : image_layer_writer,
5743 123 : lsn,
5744 123 : ctx,
5745 123 : img_range.clone(),
5746 123 : io_concurrency,
5747 123 : Some((idx, total)),
5748 123 : )
5749 123 : .await?
5750 : } else {
5751 118 : self.create_image_layer_for_metadata_keys(
5752 118 : partition,
5753 118 : image_layer_writer,
5754 118 : lsn,
5755 118 : ctx,
5756 118 : img_range.clone(),
5757 118 : mode,
5758 118 : io_concurrency,
5759 118 : )
5760 118 : .await?
5761 : };
5762 241 : match outcome {
5763 111 : ImageLayerCreationOutcome::Empty => {
5764 111 : // No data in this partition, so we don't need to create an image layer (for now).
5765 111 : // The next image layer should cover this key range, so we don't advance the `start`
5766 111 : // key.
5767 111 : }
5768 : ImageLayerCreationOutcome::Generated {
5769 129 : unfinished_image_layer,
5770 129 : } => {
5771 129 : batch_image_writer.add_unfinished_image_writer(
5772 129 : unfinished_image_layer,
5773 129 : img_range.clone(),
5774 129 : lsn,
5775 129 : );
5776 129 : // The next image layer should be generated right after this one.
5777 129 : start = img_range.end;
5778 129 : }
5779 1 : ImageLayerCreationOutcome::Skip => {
5780 1 : // We don't need to create an image layer for this partition.
5781 1 : // The next image layer should NOT cover this range, otherwise
5782 1 : // the keyspace becomes empty (reads don't go past image layers).
5783 1 : start = img_range.end;
5784 1 : }
5785 : }
5786 :
5787 241 : if let ImageLayerCreationMode::Try = mode {
5788 : // We have at least made some progress
5789 1 : if yield_for_l0 && batch_image_writer.pending_layer_num() >= 1 {
5790 : // The `Try` mode is currently only used on the compaction path. We want to avoid
5791 : // image layer generation taking too long time and blocking L0 compaction. So in this
5792 : // mode, we also inspect the current number of L0 layers and skip image layer generation
5793 : // if there are too many of them.
5794 0 : let image_preempt_threshold = self.get_image_creation_preempt_threshold()
5795 0 : * self.get_compaction_threshold();
5796 : // TODO: currently we do not respect `get_image_creation_preempt_threshold` and always yield
5797 : // when there is a single timeline with more than L0 threshold L0 layers. As long as the
5798 : // `get_image_creation_preempt_threshold` is set to a value greater than 0, we will yield for L0 compaction.
5799 0 : if image_preempt_threshold != 0 {
5800 0 : let should_yield = self
5801 0 : .l0_compaction_trigger
5802 0 : .notified()
5803 0 : .now_or_never()
5804 0 : .is_some();
5805 0 : if should_yield {
5806 0 : tracing::info!(
5807 0 : "preempt image layer generation at {lsn} when processing partition {}..{}: too many L0 layers",
5808 0 : partition.start().unwrap(),
5809 0 : partition.end().unwrap()
5810 : );
5811 0 : last_partition_processed = Some(partition.clone());
5812 0 : all_generated = false;
5813 0 : break;
5814 0 : }
5815 0 : }
5816 1 : }
5817 240 : }
5818 : }
5819 :
5820 190 : let image_layers = batch_image_writer
5821 190 : .finish(self, ctx)
5822 190 : .await
5823 190 : .map_err(CreateImageLayersError::Other)?;
5824 :
5825 190 : let mut guard = self.layers.write(LayerManagerLockHolder::Compaction).await;
5826 :
5827 : // FIXME: we could add the images to be uploaded *before* returning from here, but right
5828 : // now they are being scheduled outside of write lock; current way is inconsistent with
5829 : // compaction lock order.
5830 190 : guard
5831 190 : .open_mut()?
5832 190 : .track_new_image_layers(&image_layers, &self.metrics);
5833 190 : drop_layer_manager_wlock(guard);
5834 190 : let duration = timer.stop_and_record();
5835 :
5836 : // Creating image layers may have caused some previously visible layers to be covered
5837 190 : if !image_layers.is_empty() {
5838 117 : self.update_layer_visibility().await?;
5839 73 : }
5840 :
5841 190 : let total_layer_size = image_layers
5842 190 : .iter()
5843 190 : .map(|l| l.metadata().file_size)
5844 190 : .sum::<u64>();
5845 :
5846 190 : if !image_layers.is_empty() {
5847 117 : info!(
5848 0 : "created {} image layers ({} bytes) in {}s, processed {} out of {} partitions",
5849 0 : image_layers.len(),
5850 : total_layer_size,
5851 0 : duration.as_secs_f64(),
5852 : partition_processed,
5853 : total_partitions
5854 : );
5855 73 : }
5856 :
5857 : Ok((
5858 190 : image_layers,
5859 190 : if all_generated {
5860 190 : LastImageLayerCreationStatus::Complete
5861 : } else {
5862 : LastImageLayerCreationStatus::Incomplete {
5863 0 : last_key: if let Some(last_partition_processed) = last_partition_processed {
5864 0 : last_partition_processed.end().unwrap_or(Key::MIN)
5865 : } else {
5866 : // This branch should be unreachable, but in case it happens, we can just return the start key.
5867 0 : Key::MIN
5868 : },
5869 : }
5870 : },
5871 : ))
5872 190 : }
5873 :
5874 : /// Wait until the background initial logical size calculation is complete, or
5875 : /// this Timeline is shut down. Calling this function will cause the initial
5876 : /// logical size calculation to skip waiting for the background jobs barrier.
5877 0 : pub(crate) async fn await_initial_logical_size(self: Arc<Self>) {
5878 0 : if !self.shard_identity.is_shard_zero() {
5879 : // We don't populate logical size on shard >0: skip waiting for it.
5880 0 : return;
5881 0 : }
5882 :
5883 0 : if self.remote_client.is_deleting() {
5884 : // The timeline was created in a deletion-resume state, we don't expect logical size to be populated
5885 0 : return;
5886 0 : }
5887 :
5888 0 : if self.current_logical_size.current_size().is_exact() {
5889 : // root timelines are initialized with exact count, but never start the background
5890 : // calculation
5891 0 : return;
5892 0 : }
5893 :
5894 0 : if self.cancel.is_cancelled() {
5895 : // We already requested stopping the tenant, so we cannot wait for the logical size
5896 : // calculation to complete given the task might have been already cancelled.
5897 0 : return;
5898 0 : }
5899 :
5900 0 : if let Some(await_bg_cancel) = self
5901 0 : .current_logical_size
5902 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
5903 0 : .get()
5904 0 : {
5905 0 : await_bg_cancel.cancel();
5906 0 : } else {
5907 : // We should not wait if we were not able to explicitly instruct
5908 : // the logical size cancellation to skip the concurrency limit semaphore.
5909 : // TODO: this is an unexpected case. We should restructure so that it
5910 : // can't happen.
5911 0 : tracing::warn!(
5912 0 : "await_initial_logical_size: can't get semaphore cancel token, skipping"
5913 : );
5914 0 : debug_assert!(false);
5915 : }
5916 :
5917 0 : tokio::select!(
5918 0 : _ = self.current_logical_size.initialized.acquire() => {},
5919 0 : _ = self.cancel.cancelled() => {}
5920 : )
5921 0 : }
5922 :
5923 : /// Detach this timeline from its ancestor by copying all of ancestors layers as this
5924 : /// Timelines layers up to the ancestor_lsn.
5925 : ///
5926 : /// Requires a timeline that:
5927 : /// - has an ancestor to detach from
5928 : /// - the ancestor does not have an ancestor -- follows from the original RFC limitations, not
5929 : /// a technical requirement
5930 : ///
5931 : /// After the operation has been started, it cannot be canceled. Upon restart it needs to be
5932 : /// polled again until completion.
5933 : ///
5934 : /// During the operation all timelines sharing the data with this timeline will be reparented
5935 : /// from our ancestor to be branches of this timeline.
5936 0 : pub(crate) async fn prepare_to_detach_from_ancestor(
5937 0 : self: &Arc<Timeline>,
5938 0 : tenant: &crate::tenant::TenantShard,
5939 0 : options: detach_ancestor::Options,
5940 0 : behavior: DetachBehavior,
5941 0 : ctx: &RequestContext,
5942 0 : ) -> Result<detach_ancestor::Progress, detach_ancestor::Error> {
5943 0 : detach_ancestor::prepare(self, tenant, behavior, options, ctx).await
5944 0 : }
5945 :
5946 : /// Second step of detach from ancestor; detaches the `self` from it's current ancestor and
5947 : /// reparents any reparentable children of previous ancestor.
5948 : ///
5949 : /// This method is to be called while holding the TenantManager's tenant slot, so during this
5950 : /// method we cannot be deleted nor can any timeline be deleted. After this method returns
5951 : /// successfully, tenant must be reloaded.
5952 : ///
5953 : /// Final step will be to [`Self::complete_detaching_timeline_ancestor`] after optionally
5954 : /// resetting the tenant.
5955 0 : pub(crate) async fn detach_from_ancestor_and_reparent(
5956 0 : self: &Arc<Timeline>,
5957 0 : tenant: &crate::tenant::TenantShard,
5958 0 : prepared: detach_ancestor::PreparedTimelineDetach,
5959 0 : ancestor_timeline_id: TimelineId,
5960 0 : ancestor_lsn: Lsn,
5961 0 : behavior: DetachBehavior,
5962 0 : ctx: &RequestContext,
5963 0 : ) -> Result<detach_ancestor::DetachingAndReparenting, detach_ancestor::Error> {
5964 0 : detach_ancestor::detach_and_reparent(
5965 0 : self,
5966 0 : tenant,
5967 0 : prepared,
5968 0 : ancestor_timeline_id,
5969 0 : ancestor_lsn,
5970 0 : behavior,
5971 0 : ctx,
5972 0 : )
5973 0 : .await
5974 0 : }
5975 :
5976 : /// Final step which unblocks the GC.
5977 : ///
5978 : /// The tenant must've been reset if ancestry was modified previously (in tenant manager).
5979 0 : pub(crate) async fn complete_detaching_timeline_ancestor(
5980 0 : self: &Arc<Timeline>,
5981 0 : tenant: &crate::tenant::TenantShard,
5982 0 : attempt: detach_ancestor::Attempt,
5983 0 : ctx: &RequestContext,
5984 0 : ) -> Result<(), detach_ancestor::Error> {
5985 0 : detach_ancestor::complete(self, tenant, attempt, ctx).await
5986 0 : }
5987 : }
5988 :
5989 : impl Drop for Timeline {
5990 5 : fn drop(&mut self) {
5991 5 : if let Some(ancestor) = &self.ancestor_timeline {
5992 : // This lock should never be poisoned, but in case it is we do a .map() instead of
5993 : // an unwrap(), to avoid panicking in a destructor and thereby aborting the process.
5994 2 : if let Ok(mut gc_info) = ancestor.gc_info.write() {
5995 2 : if !gc_info.remove_child_not_offloaded(self.timeline_id) {
5996 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
5997 0 : "Couldn't remove retain_lsn entry from timeline's parent on drop: already removed");
5998 2 : }
5999 0 : }
6000 3 : }
6001 5 : info!(
6002 0 : "Timeline {} for tenant {} is being dropped",
6003 : self.timeline_id, self.tenant_shard_id.tenant_id
6004 : );
6005 5 : }
6006 : }
6007 :
6008 : /// Top-level failure to compact.
6009 : #[derive(Debug, thiserror::Error)]
6010 : pub(crate) enum CompactionError {
6011 : #[error("The timeline or pageserver is shutting down")]
6012 : ShuttingDown,
6013 : /// Compaction cannot be done right now; page reconstruction and so on.
6014 : #[error("Failed to collect keyspace: {0}")]
6015 : CollectKeySpaceError(#[from] CollectKeySpaceError),
6016 : #[error(transparent)]
6017 : Other(anyhow::Error),
6018 : }
6019 :
6020 : impl CompactionError {
6021 : /// Errors that can be ignored, i.e., cancel and shutdown.
6022 0 : pub fn is_cancel(&self) -> bool {
6023 0 : matches!(
6024 0 : self,
6025 : Self::ShuttingDown
6026 : | Self::CollectKeySpaceError(CollectKeySpaceError::Cancelled)
6027 : | Self::CollectKeySpaceError(CollectKeySpaceError::PageRead(
6028 : PageReconstructError::Cancelled
6029 : ))
6030 : )
6031 0 : }
6032 :
6033 : /// Critical errors that indicate data corruption.
6034 0 : pub fn is_critical(&self) -> bool {
6035 0 : matches!(
6036 0 : self,
6037 : Self::CollectKeySpaceError(
6038 : CollectKeySpaceError::Decode(_)
6039 : | CollectKeySpaceError::PageRead(
6040 : PageReconstructError::MissingKey(_) | PageReconstructError::WalRedo(_),
6041 : )
6042 : )
6043 : )
6044 0 : }
6045 : }
6046 :
6047 : impl From<super::upload_queue::NotInitialized> for CompactionError {
6048 0 : fn from(value: super::upload_queue::NotInitialized) -> Self {
6049 0 : match value {
6050 : super::upload_queue::NotInitialized::Uninitialized => {
6051 0 : CompactionError::Other(anyhow::anyhow!(value))
6052 : }
6053 : super::upload_queue::NotInitialized::ShuttingDown
6054 0 : | super::upload_queue::NotInitialized::Stopped => CompactionError::ShuttingDown,
6055 : }
6056 0 : }
6057 : }
6058 :
6059 : impl From<super::storage_layer::layer::DownloadError> for CompactionError {
6060 0 : fn from(e: super::storage_layer::layer::DownloadError) -> Self {
6061 0 : match e {
6062 : super::storage_layer::layer::DownloadError::TimelineShutdown
6063 : | super::storage_layer::layer::DownloadError::DownloadCancelled => {
6064 0 : CompactionError::ShuttingDown
6065 : }
6066 : super::storage_layer::layer::DownloadError::ContextAndConfigReallyDeniesDownloads
6067 : | super::storage_layer::layer::DownloadError::DownloadRequired
6068 : | super::storage_layer::layer::DownloadError::NotFile(_)
6069 : | super::storage_layer::layer::DownloadError::DownloadFailed
6070 : | super::storage_layer::layer::DownloadError::PreStatFailed(_) => {
6071 0 : CompactionError::Other(anyhow::anyhow!(e))
6072 : }
6073 : #[cfg(test)]
6074 : super::storage_layer::layer::DownloadError::Failpoint(_) => {
6075 0 : CompactionError::Other(anyhow::anyhow!(e))
6076 : }
6077 : }
6078 0 : }
6079 : }
6080 :
6081 : impl From<layer_manager::Shutdown> for CompactionError {
6082 0 : fn from(_: layer_manager::Shutdown) -> Self {
6083 0 : CompactionError::ShuttingDown
6084 0 : }
6085 : }
6086 :
6087 : impl From<super::storage_layer::errors::PutError> for CompactionError {
6088 0 : fn from(e: super::storage_layer::errors::PutError) -> Self {
6089 0 : if e.is_cancel() {
6090 0 : CompactionError::ShuttingDown
6091 : } else {
6092 0 : CompactionError::Other(e.into_anyhow())
6093 : }
6094 0 : }
6095 : }
6096 :
6097 : #[serde_as]
6098 : #[derive(serde::Serialize)]
6099 : struct RecordedDuration(#[serde_as(as = "serde_with::DurationMicroSeconds")] Duration);
6100 :
6101 : #[derive(Default)]
6102 : enum DurationRecorder {
6103 : #[default]
6104 : NotStarted,
6105 : Recorded(RecordedDuration, tokio::time::Instant),
6106 : }
6107 :
6108 : impl DurationRecorder {
6109 115 : fn till_now(&self) -> DurationRecorder {
6110 115 : match self {
6111 : DurationRecorder::NotStarted => {
6112 0 : panic!("must only call on recorded measurements")
6113 : }
6114 115 : DurationRecorder::Recorded(_, ended) => {
6115 115 : let now = tokio::time::Instant::now();
6116 115 : DurationRecorder::Recorded(RecordedDuration(now - *ended), now)
6117 : }
6118 : }
6119 115 : }
6120 138 : fn into_recorded(self) -> Option<RecordedDuration> {
6121 138 : match self {
6122 0 : DurationRecorder::NotStarted => None,
6123 138 : DurationRecorder::Recorded(recorded, _) => Some(recorded),
6124 : }
6125 138 : }
6126 : }
6127 :
6128 : /// Descriptor for a delta layer used in testing infra. The start/end key/lsn range of the
6129 : /// delta layer might be different from the min/max key/lsn in the delta layer. Therefore,
6130 : /// the layer descriptor requires the user to provide the ranges, which should cover all
6131 : /// keys specified in the `data` field.
6132 : #[cfg(test)]
6133 : #[derive(Clone)]
6134 : pub struct DeltaLayerTestDesc {
6135 : pub lsn_range: Range<Lsn>,
6136 : pub key_range: Range<Key>,
6137 : pub data: Vec<(Key, Lsn, Value)>,
6138 : }
6139 :
6140 : #[cfg(test)]
6141 : #[derive(Clone)]
6142 : pub struct InMemoryLayerTestDesc {
6143 : pub lsn_range: Range<Lsn>,
6144 : pub data: Vec<(Key, Lsn, Value)>,
6145 : pub is_open: bool,
6146 : }
6147 :
6148 : #[cfg(test)]
6149 : impl DeltaLayerTestDesc {
6150 2 : pub fn new(lsn_range: Range<Lsn>, key_range: Range<Key>, data: Vec<(Key, Lsn, Value)>) -> Self {
6151 2 : Self {
6152 2 : lsn_range,
6153 2 : key_range,
6154 2 : data,
6155 2 : }
6156 2 : }
6157 :
6158 45 : pub fn new_with_inferred_key_range(
6159 45 : lsn_range: Range<Lsn>,
6160 45 : data: Vec<(Key, Lsn, Value)>,
6161 45 : ) -> Self {
6162 45 : let key_min = data.iter().map(|(key, _, _)| key).min().unwrap();
6163 45 : let key_max = data.iter().map(|(key, _, _)| key).max().unwrap();
6164 45 : Self {
6165 45 : key_range: (*key_min)..(key_max.next()),
6166 45 : lsn_range,
6167 45 : data,
6168 45 : }
6169 45 : }
6170 :
6171 5 : pub(crate) fn layer_name(&self) -> LayerName {
6172 5 : LayerName::Delta(super::storage_layer::DeltaLayerName {
6173 5 : key_range: self.key_range.clone(),
6174 5 : lsn_range: self.lsn_range.clone(),
6175 5 : })
6176 5 : }
6177 : }
6178 :
6179 : impl Timeline {
6180 23 : async fn finish_compact_batch(
6181 23 : self: &Arc<Self>,
6182 23 : new_deltas: &[ResidentLayer],
6183 23 : new_images: &[ResidentLayer],
6184 23 : layers_to_remove: &[Layer],
6185 23 : ) -> Result<(), CompactionError> {
6186 23 : let mut guard = tokio::select! {
6187 23 : guard = self.layers.write(LayerManagerLockHolder::Compaction) => guard,
6188 23 : _ = self.cancel.cancelled() => {
6189 0 : return Err(CompactionError::ShuttingDown);
6190 : }
6191 : };
6192 :
6193 23 : let mut duplicated_layers = HashSet::new();
6194 :
6195 23 : let mut insert_layers = Vec::with_capacity(new_deltas.len());
6196 :
6197 186 : for l in new_deltas {
6198 163 : if guard.contains(l.as_ref()) {
6199 : // expected in tests
6200 0 : tracing::error!(layer=%l, "duplicated L1 layer");
6201 :
6202 : // good ways to cause a duplicate: we repeatedly error after taking the writelock
6203 : // `guard` on self.layers. as of writing this, there are no error returns except
6204 : // for compact_level0_phase1 creating an L0, which does not happen in practice
6205 : // because we have not implemented L0 => L0 compaction.
6206 0 : duplicated_layers.insert(l.layer_desc().key());
6207 163 : } else if LayerMap::is_l0(&l.layer_desc().key_range, l.layer_desc().is_delta) {
6208 0 : return Err(CompactionError::Other(anyhow::anyhow!(
6209 0 : "compaction generates a L0 layer file as output, which will cause infinite compaction."
6210 0 : )));
6211 163 : } else {
6212 163 : insert_layers.push(l.clone());
6213 163 : }
6214 : }
6215 :
6216 : // only remove those inputs which were not outputs
6217 23 : let remove_layers: Vec<Layer> = layers_to_remove
6218 23 : .iter()
6219 201 : .filter(|l| !duplicated_layers.contains(&l.layer_desc().key()))
6220 23 : .cloned()
6221 23 : .collect();
6222 :
6223 23 : if !new_images.is_empty() {
6224 0 : guard
6225 0 : .open_mut()?
6226 0 : .track_new_image_layers(new_images, &self.metrics);
6227 23 : }
6228 :
6229 23 : guard
6230 23 : .open_mut()?
6231 23 : .finish_compact_l0(&remove_layers, &insert_layers, &self.metrics);
6232 :
6233 23 : self.remote_client
6234 23 : .schedule_compaction_update(&remove_layers, new_deltas)?;
6235 :
6236 23 : drop_layer_manager_wlock(guard);
6237 :
6238 23 : Ok(())
6239 23 : }
6240 :
6241 0 : async fn rewrite_layers(
6242 0 : self: &Arc<Self>,
6243 0 : mut replace_layers: Vec<(Layer, ResidentLayer)>,
6244 0 : mut drop_layers: Vec<Layer>,
6245 0 : ) -> Result<(), CompactionError> {
6246 0 : let mut guard = self.layers.write(LayerManagerLockHolder::Compaction).await;
6247 :
6248 : // Trim our lists in case our caller (compaction) raced with someone else (GC) removing layers: we want
6249 : // to avoid double-removing, and avoid rewriting something that was removed.
6250 0 : replace_layers.retain(|(l, _)| guard.contains(l));
6251 0 : drop_layers.retain(|l| guard.contains(l));
6252 :
6253 0 : guard
6254 0 : .open_mut()?
6255 0 : .rewrite_layers(&replace_layers, &drop_layers, &self.metrics);
6256 :
6257 0 : let upload_layers: Vec<_> = replace_layers.into_iter().map(|r| r.1).collect();
6258 :
6259 0 : self.remote_client
6260 0 : .schedule_compaction_update(&drop_layers, &upload_layers)?;
6261 :
6262 0 : Ok(())
6263 0 : }
6264 :
6265 : /// Schedules the uploads of the given image layers
6266 80 : fn upload_new_image_layers(
6267 80 : self: &Arc<Self>,
6268 80 : new_images: impl IntoIterator<Item = ResidentLayer>,
6269 80 : ) -> Result<(), super::upload_queue::NotInitialized> {
6270 93 : for layer in new_images {
6271 13 : self.remote_client.schedule_layer_file_upload(layer)?;
6272 : }
6273 : // should any new image layer been created, not uploading index_part will
6274 : // result in a mismatch between remote_physical_size and layermap calculated
6275 : // size, which will fail some tests, but should not be an issue otherwise.
6276 80 : self.remote_client
6277 80 : .schedule_index_upload_for_file_changes()?;
6278 80 : Ok(())
6279 80 : }
6280 :
6281 0 : async fn find_gc_time_cutoff(
6282 0 : &self,
6283 0 : now: SystemTime,
6284 0 : pitr: Duration,
6285 0 : cancel: &CancellationToken,
6286 0 : ctx: &RequestContext,
6287 0 : ) -> Result<Option<Lsn>, PageReconstructError> {
6288 0 : debug_assert_current_span_has_tenant_and_timeline_id();
6289 0 : if self.shard_identity.is_shard_zero() {
6290 : // Shard Zero has SLRU data and can calculate the PITR time -> LSN mapping itself
6291 0 : let time_range = if pitr == Duration::ZERO {
6292 0 : humantime::parse_duration(DEFAULT_PITR_INTERVAL).expect("constant is invalid")
6293 : } else {
6294 0 : pitr
6295 : };
6296 :
6297 : // If PITR is so large or `now` is so small that this underflows, we will retain no history (highly unexpected case)
6298 0 : let time_cutoff = now.checked_sub(time_range).unwrap_or(now);
6299 0 : let timestamp = to_pg_timestamp(time_cutoff);
6300 :
6301 0 : let time_cutoff = match self.find_lsn_for_timestamp(timestamp, cancel, ctx).await? {
6302 0 : LsnForTimestamp::Present(lsn) => Some(lsn),
6303 0 : LsnForTimestamp::Future(lsn) => {
6304 : // The timestamp is in the future. That sounds impossible,
6305 : // but what it really means is that there hasn't been
6306 : // any commits since the cutoff timestamp.
6307 : //
6308 : // In this case we should use the LSN of the most recent commit,
6309 : // which is implicitly the last LSN in the log.
6310 0 : debug!("future({})", lsn);
6311 0 : Some(self.get_last_record_lsn())
6312 : }
6313 0 : LsnForTimestamp::Past(lsn) => {
6314 0 : debug!("past({})", lsn);
6315 0 : None
6316 : }
6317 0 : LsnForTimestamp::NoData(lsn) => {
6318 0 : debug!("nodata({})", lsn);
6319 0 : None
6320 : }
6321 : };
6322 0 : Ok(time_cutoff)
6323 : } else {
6324 : // Shards other than shard zero cannot do timestamp->lsn lookups, and must instead learn their GC cutoff
6325 : // from shard zero's index. The index doesn't explicitly tell us the time cutoff, but we may assume that
6326 : // the point up to which shard zero's last_gc_cutoff has advanced will either be the time cutoff, or a
6327 : // space cutoff that we would also have respected ourselves.
6328 0 : match self
6329 0 : .remote_client
6330 0 : .download_foreign_index(ShardNumber(0), cancel)
6331 0 : .await
6332 : {
6333 0 : Ok((index_part, index_generation, _index_mtime)) => {
6334 0 : tracing::info!(
6335 0 : "GC loaded shard zero metadata (gen {index_generation:?}): latest_gc_cutoff_lsn: {}",
6336 0 : index_part.metadata.latest_gc_cutoff_lsn()
6337 : );
6338 0 : Ok(Some(index_part.metadata.latest_gc_cutoff_lsn()))
6339 : }
6340 : Err(DownloadError::NotFound) => {
6341 : // This is unexpected, because during timeline creations shard zero persists to remote
6342 : // storage before other shards are called, and during timeline deletion non-zeroth shards are
6343 : // deleted before the zeroth one. However, it should be harmless: if we somehow end up in this
6344 : // state, then shard zero should _eventually_ write an index when it GCs.
6345 0 : tracing::warn!("GC couldn't find shard zero's index for timeline");
6346 0 : Ok(None)
6347 : }
6348 0 : Err(e) => {
6349 : // TODO: this function should return a different error type than page reconstruct error
6350 0 : Err(PageReconstructError::Other(anyhow::anyhow!(e)))
6351 : }
6352 : }
6353 :
6354 : // TODO: after reading shard zero's GC cutoff, we should validate its generation with the storage
6355 : // controller. Otherwise, it is possible that we see the GC cutoff go backwards while shard zero
6356 : // is going through a migration if we read the old location's index and it has GC'd ahead of the
6357 : // new location. This is legal in principle, but problematic in practice because it might result
6358 : // in a timeline creation succeeding on shard zero ('s new location) but then failing on other shards
6359 : // because they have GC'd past the branch point.
6360 : }
6361 0 : }
6362 :
6363 : /// Find the Lsns above which layer files need to be retained on
6364 : /// garbage collection.
6365 : ///
6366 : /// We calculate two cutoffs, one based on time and one based on WAL size. `pitr`
6367 : /// controls the time cutoff (or ZERO to disable time-based retention), and `space_cutoff` controls
6368 : /// the space-based retention.
6369 : ///
6370 : /// This function doesn't simply to calculate time & space based retention: it treats time-based
6371 : /// retention as authoritative if enabled, and falls back to space-based retention if calculating
6372 : /// the LSN for a time point isn't possible. Therefore the GcCutoffs::horizon in the response might
6373 : /// be different to the `space_cutoff` input. Callers should treat the min() of the two cutoffs
6374 : /// in the response as the GC cutoff point for the timeline.
6375 : #[instrument(skip_all, fields(timeline_id=%self.timeline_id))]
6376 : pub(super) async fn find_gc_cutoffs(
6377 : &self,
6378 : now: SystemTime,
6379 : space_cutoff: Lsn,
6380 : pitr: Duration,
6381 : cancel: &CancellationToken,
6382 : ctx: &RequestContext,
6383 : ) -> Result<GcCutoffs, PageReconstructError> {
6384 : let _timer = self
6385 : .metrics
6386 : .find_gc_cutoffs_histo
6387 : .start_timer()
6388 : .record_on_drop();
6389 :
6390 : pausable_failpoint!("Timeline::find_gc_cutoffs-pausable");
6391 :
6392 : if cfg!(test) && pitr == Duration::ZERO {
6393 : // Unit tests which specify zero PITR interval expect to avoid doing any I/O for timestamp lookup
6394 : return Ok(GcCutoffs {
6395 : time: Some(self.get_last_record_lsn()),
6396 : space: space_cutoff,
6397 : });
6398 : }
6399 :
6400 : // Calculate a time-based limit on how much to retain:
6401 : // - if PITR interval is set, then this is our cutoff.
6402 : // - if PITR interval is not set, then we do a lookup
6403 : // based on DEFAULT_PITR_INTERVAL, so that size-based retention does not result in keeping history around permanently on idle databases.
6404 : let time_cutoff = self.find_gc_time_cutoff(now, pitr, cancel, ctx).await?;
6405 :
6406 : Ok(match (pitr, time_cutoff) {
6407 : (Duration::ZERO, Some(time_cutoff)) => {
6408 : // PITR is not set. Retain the size-based limit, or the default time retention,
6409 : // whichever requires less data.
6410 : GcCutoffs {
6411 : time: Some(self.get_last_record_lsn()),
6412 : space: std::cmp::max(time_cutoff, space_cutoff),
6413 : }
6414 : }
6415 : (Duration::ZERO, None) => {
6416 : // PITR is not set, and time lookup failed
6417 : GcCutoffs {
6418 : time: Some(self.get_last_record_lsn()),
6419 : space: space_cutoff,
6420 : }
6421 : }
6422 : (_, None) => {
6423 : // PITR interval is set & we didn't look up a timestamp successfully. Conservatively assume PITR
6424 : // cannot advance beyond what was already GC'd, and respect space-based retention
6425 : GcCutoffs {
6426 : time: Some(*self.get_applied_gc_cutoff_lsn()),
6427 : space: space_cutoff,
6428 : }
6429 : }
6430 : (_, Some(time_cutoff)) => {
6431 : // PITR interval is set and we looked up timestamp successfully. Ignore
6432 : // size based retention and make time cutoff authoritative
6433 : GcCutoffs {
6434 : time: Some(time_cutoff),
6435 : space: time_cutoff,
6436 : }
6437 : }
6438 : })
6439 : }
6440 :
6441 : /// Garbage collect layer files on a timeline that are no longer needed.
6442 : ///
6443 : /// Currently, we don't make any attempt at removing unneeded page versions
6444 : /// within a layer file. We can only remove the whole file if it's fully
6445 : /// obsolete.
6446 377 : pub(super) async fn gc(&self) -> Result<GcResult, GcError> {
6447 : // this is most likely the background tasks, but it might be the spawned task from
6448 : // immediate_gc
6449 377 : let _g = tokio::select! {
6450 377 : guard = self.gc_lock.lock() => guard,
6451 377 : _ = self.cancel.cancelled() => return Ok(GcResult::default()),
6452 : };
6453 377 : let timer = self.metrics.garbage_collect_histo.start_timer();
6454 :
6455 377 : fail_point!("before-timeline-gc");
6456 :
6457 : // Is the timeline being deleted?
6458 377 : if self.is_stopping() {
6459 0 : return Err(GcError::TimelineCancelled);
6460 377 : }
6461 :
6462 377 : let (space_cutoff, time_cutoff, retain_lsns, max_lsn_with_valid_lease) = {
6463 377 : let gc_info = self.gc_info.read().unwrap();
6464 :
6465 377 : let space_cutoff = min(gc_info.cutoffs.space, self.get_disk_consistent_lsn());
6466 377 : let time_cutoff = gc_info.cutoffs.time;
6467 377 : let retain_lsns = gc_info
6468 377 : .retain_lsns
6469 377 : .iter()
6470 377 : .map(|(lsn, _child_id, _is_offloaded)| *lsn)
6471 377 : .collect();
6472 :
6473 : // Gets the maximum LSN that holds the valid lease.
6474 : //
6475 : // Caveat: `refresh_gc_info` is in charged of updating the lease map.
6476 : // Here, we do not check for stale leases again.
6477 377 : let max_lsn_with_valid_lease = gc_info.leases.last_key_value().map(|(lsn, _)| *lsn);
6478 :
6479 377 : (
6480 377 : space_cutoff,
6481 377 : time_cutoff,
6482 377 : retain_lsns,
6483 377 : max_lsn_with_valid_lease,
6484 377 : )
6485 : };
6486 :
6487 377 : let mut new_gc_cutoff = space_cutoff.min(time_cutoff.unwrap_or_default());
6488 377 : let standby_horizon = self.standby_horizon.load();
6489 : // Hold GC for the standby, but as a safety guard do it only within some
6490 : // reasonable lag.
6491 377 : if standby_horizon != Lsn::INVALID {
6492 0 : if let Some(standby_lag) = new_gc_cutoff.checked_sub(standby_horizon) {
6493 : const MAX_ALLOWED_STANDBY_LAG: u64 = 10u64 << 30; // 10 GB
6494 0 : if standby_lag.0 < MAX_ALLOWED_STANDBY_LAG {
6495 0 : new_gc_cutoff = Lsn::min(standby_horizon, new_gc_cutoff);
6496 0 : trace!("holding off GC for standby apply LSN {}", standby_horizon);
6497 : } else {
6498 0 : warn!(
6499 0 : "standby is lagging for more than {}MB, not holding gc for it",
6500 0 : MAX_ALLOWED_STANDBY_LAG / 1024 / 1024
6501 : )
6502 : }
6503 0 : }
6504 377 : }
6505 :
6506 : // Reset standby horizon to ignore it if it is not updated till next GC.
6507 : // It is an easy way to unset it when standby disappears without adding
6508 : // more conf options.
6509 377 : self.standby_horizon.store(Lsn::INVALID);
6510 377 : self.metrics
6511 377 : .standby_horizon_gauge
6512 377 : .set(Lsn::INVALID.0 as i64);
6513 :
6514 377 : let res = self
6515 377 : .gc_timeline(
6516 377 : space_cutoff,
6517 377 : time_cutoff,
6518 377 : retain_lsns,
6519 377 : max_lsn_with_valid_lease,
6520 377 : new_gc_cutoff,
6521 : )
6522 377 : .instrument(
6523 377 : info_span!("gc_timeline", timeline_id = %self.timeline_id, cutoff = %new_gc_cutoff),
6524 : )
6525 377 : .await?;
6526 :
6527 : // only record successes
6528 377 : timer.stop_and_record();
6529 :
6530 377 : Ok(res)
6531 377 : }
6532 :
6533 377 : async fn gc_timeline(
6534 377 : &self,
6535 377 : space_cutoff: Lsn,
6536 377 : time_cutoff: Option<Lsn>, // None if uninitialized
6537 377 : retain_lsns: Vec<Lsn>,
6538 377 : max_lsn_with_valid_lease: Option<Lsn>,
6539 377 : new_gc_cutoff: Lsn,
6540 377 : ) -> Result<GcResult, GcError> {
6541 : // FIXME: if there is an ongoing detach_from_ancestor, we should just skip gc
6542 :
6543 377 : let now = SystemTime::now();
6544 377 : let mut result: GcResult = GcResult::default();
6545 :
6546 : // Nothing to GC. Return early.
6547 377 : let latest_gc_cutoff = *self.get_applied_gc_cutoff_lsn();
6548 377 : if latest_gc_cutoff >= new_gc_cutoff {
6549 11 : info!(
6550 0 : "Nothing to GC: new_gc_cutoff_lsn {new_gc_cutoff}, latest_gc_cutoff_lsn {latest_gc_cutoff}",
6551 : );
6552 11 : return Ok(result);
6553 366 : }
6554 :
6555 366 : let Some(time_cutoff) = time_cutoff else {
6556 : // The GC cutoff should have been computed by now, but let's be defensive.
6557 0 : info!("Nothing to GC: time_cutoff not yet computed");
6558 0 : return Ok(result);
6559 : };
6560 :
6561 : // We need to ensure that no one tries to read page versions or create
6562 : // branches at a point before latest_gc_cutoff_lsn. See branch_timeline()
6563 : // for details. This will block until the old value is no longer in use.
6564 : //
6565 : // The GC cutoff should only ever move forwards.
6566 366 : let waitlist = {
6567 366 : let write_guard = self.applied_gc_cutoff_lsn.lock_for_write();
6568 366 : if *write_guard > new_gc_cutoff {
6569 0 : return Err(GcError::BadLsn {
6570 0 : why: format!(
6571 0 : "Cannot move GC cutoff LSN backwards (was {}, new {})",
6572 0 : *write_guard, new_gc_cutoff
6573 0 : ),
6574 0 : });
6575 366 : }
6576 :
6577 366 : write_guard.store_and_unlock(new_gc_cutoff)
6578 : };
6579 366 : waitlist.wait().await;
6580 :
6581 366 : info!("GC starting");
6582 :
6583 366 : debug!("retain_lsns: {:?}", retain_lsns);
6584 :
6585 366 : let max_retain_lsn = retain_lsns.iter().max();
6586 :
6587 : // Scan all layers in the timeline (remote or on-disk).
6588 : //
6589 : // Garbage collect the layer if all conditions are satisfied:
6590 : // 1. it is older than cutoff LSN;
6591 : // 2. it is older than PITR interval;
6592 : // 3. it doesn't need to be retained for 'retain_lsns';
6593 : // 4. it does not need to be kept for LSNs holding valid leases.
6594 : // 5. newer on-disk image layers cover the layer's whole key range
6595 366 : let layers_to_remove = {
6596 366 : let mut layers_to_remove = Vec::new();
6597 :
6598 366 : let guard = self
6599 366 : .layers
6600 366 : .read(LayerManagerLockHolder::GarbageCollection)
6601 366 : .await;
6602 366 : let layers = guard.layer_map()?;
6603 6209 : 'outer: for l in layers.iter_historic_layers() {
6604 6209 : result.layers_total += 1;
6605 :
6606 : // 1. Is it newer than GC horizon cutoff point?
6607 6209 : if l.get_lsn_range().end > space_cutoff {
6608 371 : debug!(
6609 0 : "keeping {} because it's newer than space_cutoff {}",
6610 0 : l.layer_name(),
6611 : space_cutoff,
6612 : );
6613 371 : result.layers_needed_by_cutoff += 1;
6614 371 : continue 'outer;
6615 5838 : }
6616 :
6617 : // 2. It is newer than PiTR cutoff point?
6618 5838 : if l.get_lsn_range().end > time_cutoff {
6619 0 : debug!(
6620 0 : "keeping {} because it's newer than time_cutoff {}",
6621 0 : l.layer_name(),
6622 : time_cutoff,
6623 : );
6624 0 : result.layers_needed_by_pitr += 1;
6625 0 : continue 'outer;
6626 5838 : }
6627 :
6628 : // 3. Is it needed by a child branch?
6629 : // NOTE With that we would keep data that
6630 : // might be referenced by child branches forever.
6631 : // We can track this in child timeline GC and delete parent layers when
6632 : // they are no longer needed. This might be complicated with long inheritance chains.
6633 5838 : if let Some(retain_lsn) = max_retain_lsn {
6634 : // start_lsn is inclusive
6635 6 : if &l.get_lsn_range().start <= retain_lsn {
6636 6 : debug!(
6637 0 : "keeping {} because it's still might be referenced by child branch forked at {} is_dropped: xx is_incremental: {}",
6638 0 : l.layer_name(),
6639 : retain_lsn,
6640 0 : l.is_incremental(),
6641 : );
6642 6 : result.layers_needed_by_branches += 1;
6643 6 : continue 'outer;
6644 0 : }
6645 5832 : }
6646 :
6647 : // 4. Is there a valid lease that requires us to keep this layer?
6648 5832 : if let Some(lsn) = &max_lsn_with_valid_lease {
6649 : // keep if layer start <= any of the lease
6650 9 : if &l.get_lsn_range().start <= lsn {
6651 7 : debug!(
6652 0 : "keeping {} because there is a valid lease preventing GC at {}",
6653 0 : l.layer_name(),
6654 : lsn,
6655 : );
6656 7 : result.layers_needed_by_leases += 1;
6657 7 : continue 'outer;
6658 2 : }
6659 5823 : }
6660 :
6661 : // 5. Is there a later on-disk layer for this relation?
6662 : //
6663 : // The end-LSN is exclusive, while disk_consistent_lsn is
6664 : // inclusive. For example, if disk_consistent_lsn is 100, it is
6665 : // OK for a delta layer to have end LSN 101, but if the end LSN
6666 : // is 102, then it might not have been fully flushed to disk
6667 : // before crash.
6668 : //
6669 : // For example, imagine that the following layers exist:
6670 : //
6671 : // 1000 - image (A)
6672 : // 1000-2000 - delta (B)
6673 : // 2000 - image (C)
6674 : // 2000-3000 - delta (D)
6675 : // 3000 - image (E)
6676 : //
6677 : // If GC horizon is at 2500, we can remove layers A and B, but
6678 : // we cannot remove C, even though it's older than 2500, because
6679 : // the delta layer 2000-3000 depends on it.
6680 5825 : if !layers
6681 5825 : .image_layer_exists(&l.get_key_range(), &(l.get_lsn_range().end..new_gc_cutoff))
6682 : {
6683 5821 : debug!("keeping {} because it is the latest layer", l.layer_name());
6684 5821 : result.layers_not_updated += 1;
6685 5821 : continue 'outer;
6686 4 : }
6687 :
6688 : // We didn't find any reason to keep this file, so remove it.
6689 4 : info!(
6690 0 : "garbage collecting {} is_dropped: xx is_incremental: {}",
6691 0 : l.layer_name(),
6692 0 : l.is_incremental(),
6693 : );
6694 4 : layers_to_remove.push(l);
6695 : }
6696 :
6697 366 : layers_to_remove
6698 : };
6699 :
6700 366 : if !layers_to_remove.is_empty() {
6701 : // Persist the new GC cutoff value before we actually remove anything.
6702 : // This unconditionally schedules also an index_part.json update, even though, we will
6703 : // be doing one a bit later with the unlinked gc'd layers.
6704 3 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
6705 3 : self.schedule_uploads(disk_consistent_lsn, None)
6706 3 : .map_err(|e| {
6707 0 : if self.cancel.is_cancelled() {
6708 0 : GcError::TimelineCancelled
6709 : } else {
6710 0 : GcError::Remote(e)
6711 : }
6712 0 : })?;
6713 :
6714 3 : let mut guard = self
6715 3 : .layers
6716 3 : .write(LayerManagerLockHolder::GarbageCollection)
6717 3 : .await;
6718 :
6719 3 : let gc_layers = layers_to_remove
6720 3 : .iter()
6721 4 : .flat_map(|desc| guard.try_get_from_key(&desc.key()).cloned())
6722 3 : .collect::<Vec<Layer>>();
6723 :
6724 3 : result.layers_removed = gc_layers.len() as u64;
6725 :
6726 3 : self.remote_client.schedule_gc_update(&gc_layers)?;
6727 3 : guard.open_mut()?.finish_gc_timeline(&gc_layers);
6728 :
6729 : #[cfg(feature = "testing")]
6730 3 : {
6731 3 : result.doomed_layers = gc_layers;
6732 3 : }
6733 363 : }
6734 :
6735 366 : info!(
6736 0 : "GC completed removing {} layers, cutoff {}",
6737 : result.layers_removed, new_gc_cutoff
6738 : );
6739 :
6740 366 : result.elapsed = now.elapsed().unwrap_or(Duration::ZERO);
6741 366 : Ok(result)
6742 377 : }
6743 :
6744 : /// Reconstruct a value, using the given base image and WAL records in 'data'.
6745 364848 : async fn reconstruct_value(
6746 364848 : &self,
6747 364848 : key: Key,
6748 364848 : request_lsn: Lsn,
6749 364848 : mut data: ValueReconstructState,
6750 364848 : redo_attempt_type: RedoAttemptType,
6751 364848 : ) -> Result<Bytes, PageReconstructError> {
6752 : // Perform WAL redo if needed
6753 364848 : data.records.reverse();
6754 :
6755 364848 : let fire_critical_error = match redo_attempt_type {
6756 363515 : RedoAttemptType::ReadPage => true,
6757 0 : RedoAttemptType::LegacyCompaction => true,
6758 1333 : RedoAttemptType::GcCompaction => false,
6759 : };
6760 :
6761 : // If we have a page image, and no WAL, we're all set
6762 364848 : if data.records.is_empty() {
6763 338074 : if let Some((img_lsn, img)) = &data.img {
6764 338074 : trace!(
6765 0 : "found page image for key {} at {}, no WAL redo required, req LSN {}",
6766 : key, img_lsn, request_lsn,
6767 : );
6768 338074 : Ok(img.clone())
6769 : } else {
6770 0 : Err(PageReconstructError::from(anyhow!(
6771 0 : "base image for {key} at {request_lsn} not found"
6772 0 : )))
6773 : }
6774 : } else {
6775 : // We need to do WAL redo.
6776 : //
6777 : // If we don't have a base image, then the oldest WAL record better initialize
6778 : // the page
6779 26774 : if data.img.is_none() && !data.records.first().unwrap().1.will_init() {
6780 0 : Err(PageReconstructError::from(anyhow!(
6781 0 : "Base image for {} at {} not found, but got {} WAL records",
6782 0 : key,
6783 0 : request_lsn,
6784 0 : data.records.len()
6785 0 : )))
6786 : } else {
6787 26774 : if data.img.is_some() {
6788 13029 : trace!(
6789 0 : "found {} WAL records and a base image for {} at {}, performing WAL redo",
6790 0 : data.records.len(),
6791 : key,
6792 : request_lsn
6793 : );
6794 : } else {
6795 13745 : trace!(
6796 0 : "found {} WAL records that will init the page for {} at {}, performing WAL redo",
6797 0 : data.records.len(),
6798 : key,
6799 : request_lsn
6800 : );
6801 : };
6802 26774 : let res = self
6803 26774 : .walredo_mgr
6804 26774 : .as_ref()
6805 26774 : .context("timeline has no walredo manager")
6806 26774 : .map_err(PageReconstructError::WalRedo)?
6807 26774 : .request_redo(
6808 26774 : key,
6809 26774 : request_lsn,
6810 26774 : data.img,
6811 26774 : data.records,
6812 26774 : self.pg_version,
6813 26774 : redo_attempt_type,
6814 : )
6815 26774 : .await;
6816 26773 : let img = match res {
6817 26773 : Ok(img) => img,
6818 0 : Err(walredo::Error::Cancelled) => return Err(PageReconstructError::Cancelled),
6819 1 : Err(walredo::Error::Other(err)) => {
6820 1 : if fire_critical_error {
6821 0 : critical_timeline!(
6822 0 : self.tenant_shard_id,
6823 0 : self.timeline_id,
6824 0 : "walredo failure during page reconstruction: {err:?}"
6825 : );
6826 1 : }
6827 1 : return Err(PageReconstructError::WalRedo(
6828 1 : err.context("reconstruct a page image"),
6829 1 : ));
6830 : }
6831 : };
6832 26773 : Ok(img)
6833 : }
6834 : }
6835 364848 : }
6836 :
6837 0 : pub(crate) async fn spawn_download_all_remote_layers(
6838 0 : self: Arc<Self>,
6839 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6840 0 : ctx: &RequestContext,
6841 0 : ) -> Result<DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskInfo> {
6842 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6843 :
6844 : // this is not really needed anymore; it has tests which really check the return value from
6845 : // http api. it would be better not to maintain this anymore.
6846 :
6847 0 : let mut status_guard = self.download_all_remote_layers_task_info.write().unwrap();
6848 0 : if let Some(st) = &*status_guard {
6849 0 : match &st.state {
6850 : DownloadRemoteLayersTaskState::Running => {
6851 0 : return Err(st.clone());
6852 : }
6853 : DownloadRemoteLayersTaskState::ShutDown
6854 0 : | DownloadRemoteLayersTaskState::Completed => {
6855 0 : *status_guard = None;
6856 0 : }
6857 : }
6858 0 : }
6859 :
6860 0 : let self_clone = Arc::clone(&self);
6861 0 : let task_ctx = ctx.detached_child(
6862 0 : TaskKind::DownloadAllRemoteLayers,
6863 0 : DownloadBehavior::Download,
6864 : );
6865 0 : let task_id = task_mgr::spawn(
6866 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
6867 0 : task_mgr::TaskKind::DownloadAllRemoteLayers,
6868 0 : self.tenant_shard_id,
6869 0 : Some(self.timeline_id),
6870 0 : "download all remote layers task",
6871 0 : async move {
6872 0 : self_clone.download_all_remote_layers(request, &task_ctx).await;
6873 0 : let mut status_guard = self_clone.download_all_remote_layers_task_info.write().unwrap();
6874 0 : match &mut *status_guard {
6875 : None => {
6876 0 : warn!("tasks status is supposed to be Some(), since we are running");
6877 : }
6878 0 : Some(st) => {
6879 0 : let exp_task_id = format!("{}", task_mgr::current_task_id().unwrap());
6880 0 : if st.task_id != exp_task_id {
6881 0 : warn!("task id changed while we were still running, expecting {} but have {}", exp_task_id, st.task_id);
6882 0 : } else {
6883 0 : st.state = DownloadRemoteLayersTaskState::Completed;
6884 0 : }
6885 : }
6886 : };
6887 0 : Ok(())
6888 0 : }
6889 0 : .instrument(info_span!(parent: None, "download_all_remote_layers", tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))
6890 : );
6891 :
6892 0 : let initial_info = DownloadRemoteLayersTaskInfo {
6893 0 : task_id: format!("{task_id}"),
6894 0 : state: DownloadRemoteLayersTaskState::Running,
6895 0 : total_layer_count: 0,
6896 0 : successful_download_count: 0,
6897 0 : failed_download_count: 0,
6898 0 : };
6899 0 : *status_guard = Some(initial_info.clone());
6900 :
6901 0 : Ok(initial_info)
6902 0 : }
6903 :
6904 0 : async fn download_all_remote_layers(
6905 0 : self: &Arc<Self>,
6906 0 : request: DownloadRemoteLayersTaskSpawnRequest,
6907 0 : ctx: &RequestContext,
6908 0 : ) {
6909 : use pageserver_api::models::DownloadRemoteLayersTaskState;
6910 :
6911 0 : let remaining = {
6912 0 : let guard = self
6913 0 : .layers
6914 0 : .read(LayerManagerLockHolder::GetLayerMapInfo)
6915 0 : .await;
6916 0 : let Ok(lm) = guard.layer_map() else {
6917 : // technically here we could look into iterating accessible layers, but downloading
6918 : // all layers of a shutdown timeline makes no sense regardless.
6919 0 : tracing::info!("attempted to download all layers of shutdown timeline");
6920 0 : return;
6921 : };
6922 0 : lm.iter_historic_layers()
6923 0 : .map(|desc| guard.get_from_desc(&desc))
6924 0 : .collect::<Vec<_>>()
6925 : };
6926 0 : let total_layer_count = remaining.len();
6927 :
6928 : macro_rules! lock_status {
6929 : ($st:ident) => {
6930 : let mut st = self.download_all_remote_layers_task_info.write().unwrap();
6931 : let st = st
6932 : .as_mut()
6933 : .expect("this function is only called after the task has been spawned");
6934 : assert_eq!(
6935 : st.task_id,
6936 : format!(
6937 : "{}",
6938 : task_mgr::current_task_id().expect("we run inside a task_mgr task")
6939 : )
6940 : );
6941 : let $st = st;
6942 : };
6943 : }
6944 :
6945 : {
6946 0 : lock_status!(st);
6947 0 : st.total_layer_count = total_layer_count as u64;
6948 : }
6949 :
6950 0 : let mut remaining = remaining.into_iter();
6951 0 : let mut have_remaining = true;
6952 0 : let mut js = tokio::task::JoinSet::new();
6953 :
6954 0 : let cancel = task_mgr::shutdown_token();
6955 :
6956 0 : let limit = request.max_concurrent_downloads;
6957 :
6958 : loop {
6959 0 : while js.len() < limit.get() && have_remaining && !cancel.is_cancelled() {
6960 0 : let Some(next) = remaining.next() else {
6961 0 : have_remaining = false;
6962 0 : break;
6963 : };
6964 :
6965 0 : let span = tracing::info_span!("download", layer = %next);
6966 :
6967 0 : let ctx = ctx.attached_child();
6968 0 : js.spawn(
6969 0 : async move {
6970 0 : let res = next.download(&ctx).await;
6971 0 : (next, res)
6972 0 : }
6973 0 : .instrument(span),
6974 : );
6975 : }
6976 :
6977 0 : while let Some(res) = js.join_next().await {
6978 0 : match res {
6979 : Ok((_, Ok(_))) => {
6980 0 : lock_status!(st);
6981 0 : st.successful_download_count += 1;
6982 : }
6983 0 : Ok((layer, Err(e))) => {
6984 0 : tracing::error!(%layer, "download failed: {e:#}");
6985 0 : lock_status!(st);
6986 0 : st.failed_download_count += 1;
6987 : }
6988 0 : Err(je) if je.is_cancelled() => unreachable!("not used here"),
6989 0 : Err(je) if je.is_panic() => {
6990 0 : lock_status!(st);
6991 0 : st.failed_download_count += 1;
6992 : }
6993 0 : Err(je) => tracing::warn!("unknown joinerror: {je:?}"),
6994 : }
6995 : }
6996 :
6997 0 : if js.is_empty() && (!have_remaining || cancel.is_cancelled()) {
6998 0 : break;
6999 0 : }
7000 : }
7001 :
7002 : {
7003 0 : lock_status!(st);
7004 0 : st.state = DownloadRemoteLayersTaskState::Completed;
7005 : }
7006 0 : }
7007 :
7008 0 : pub(crate) fn get_download_all_remote_layers_task_info(
7009 0 : &self,
7010 0 : ) -> Option<DownloadRemoteLayersTaskInfo> {
7011 0 : self.download_all_remote_layers_task_info
7012 0 : .read()
7013 0 : .unwrap()
7014 0 : .clone()
7015 0 : }
7016 : }
7017 :
7018 : impl Timeline {
7019 : /// Returns non-remote layers for eviction.
7020 0 : pub(crate) async fn get_local_layers_for_disk_usage_eviction(&self) -> DiskUsageEvictionInfo {
7021 0 : let guard = self.layers.read(LayerManagerLockHolder::Eviction).await;
7022 0 : let mut max_layer_size: Option<u64> = None;
7023 :
7024 0 : let resident_layers = guard
7025 0 : .likely_resident_layers()
7026 0 : .map(|layer| {
7027 0 : let file_size = layer.layer_desc().file_size;
7028 0 : max_layer_size = max_layer_size.map_or(Some(file_size), |m| Some(m.max(file_size)));
7029 :
7030 0 : let last_activity_ts = layer.latest_activity();
7031 :
7032 0 : EvictionCandidate {
7033 0 : layer: layer.to_owned().into(),
7034 0 : last_activity_ts,
7035 0 : relative_last_activity: finite_f32::FiniteF32::ZERO,
7036 0 : visibility: layer.visibility(),
7037 0 : }
7038 0 : })
7039 0 : .collect();
7040 :
7041 0 : DiskUsageEvictionInfo {
7042 0 : max_layer_size,
7043 0 : resident_layers,
7044 0 : }
7045 0 : }
7046 :
7047 961 : pub(crate) fn get_shard_index(&self) -> ShardIndex {
7048 961 : ShardIndex {
7049 961 : shard_number: self.tenant_shard_id.shard_number,
7050 961 : shard_count: self.tenant_shard_id.shard_count,
7051 961 : }
7052 961 : }
7053 :
7054 : /// Persistently blocks gc for `Manual` reason.
7055 : ///
7056 : /// Returns true if no such block existed before, false otherwise.
7057 0 : pub(crate) async fn block_gc(&self, tenant: &super::TenantShard) -> anyhow::Result<bool> {
7058 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
7059 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
7060 0 : tenant.gc_block.insert(self, GcBlockingReason::Manual).await
7061 0 : }
7062 :
7063 : /// Persistently unblocks gc for `Manual` reason.
7064 0 : pub(crate) async fn unblock_gc(&self, tenant: &super::TenantShard) -> anyhow::Result<()> {
7065 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
7066 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
7067 0 : tenant.gc_block.remove(self, GcBlockingReason::Manual).await
7068 0 : }
7069 :
7070 : #[cfg(test)]
7071 31 : pub(super) fn force_advance_lsn(self: &Arc<Timeline>, new_lsn: Lsn) {
7072 31 : self.last_record_lsn.advance(new_lsn);
7073 31 : }
7074 :
7075 : #[cfg(test)]
7076 2 : pub(super) fn force_set_disk_consistent_lsn(&self, new_value: Lsn) {
7077 2 : self.disk_consistent_lsn.store(new_value);
7078 2 : }
7079 :
7080 : /// Force create an image layer and place it into the layer map.
7081 : ///
7082 : /// DO NOT use this function directly. Use [`TenantShard::branch_timeline_test_with_layers`]
7083 : /// or [`TenantShard::create_test_timeline_with_layers`] to ensure all these layers are
7084 : /// placed into the layer map in one run AND be validated.
7085 : #[cfg(test)]
7086 36 : pub(super) async fn force_create_image_layer(
7087 36 : self: &Arc<Timeline>,
7088 36 : lsn: Lsn,
7089 36 : mut images: Vec<(Key, Bytes)>,
7090 36 : check_start_lsn: Option<Lsn>,
7091 36 : ctx: &RequestContext,
7092 36 : ) -> anyhow::Result<()> {
7093 36 : let last_record_lsn = self.get_last_record_lsn();
7094 36 : assert!(
7095 36 : lsn <= last_record_lsn,
7096 0 : "advance last record lsn before inserting a layer, lsn={lsn}, last_record_lsn={last_record_lsn}"
7097 : );
7098 36 : if let Some(check_start_lsn) = check_start_lsn {
7099 36 : assert!(lsn >= check_start_lsn);
7100 0 : }
7101 240 : images.sort_unstable_by(|(ka, _), (kb, _)| ka.cmp(kb));
7102 36 : let min_key = *images.first().map(|(k, _)| k).unwrap();
7103 36 : let end_key = images.last().map(|(k, _)| k).unwrap().next();
7104 36 : let mut image_layer_writer = ImageLayerWriter::new(
7105 36 : self.conf,
7106 36 : self.timeline_id,
7107 36 : self.tenant_shard_id,
7108 36 : &(min_key..end_key),
7109 36 : lsn,
7110 36 : &self.gate,
7111 36 : self.cancel.clone(),
7112 36 : ctx,
7113 36 : )
7114 36 : .await?;
7115 312 : for (key, img) in images {
7116 276 : image_layer_writer.put_image(key, img, ctx).await?;
7117 : }
7118 36 : let (desc, path) = image_layer_writer.finish(ctx).await?;
7119 36 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
7120 36 : info!("force created image layer {}", image_layer.local_path());
7121 : {
7122 36 : let mut guard = self.layers.write(LayerManagerLockHolder::Testing).await;
7123 36 : guard
7124 36 : .open_mut()
7125 36 : .unwrap()
7126 36 : .force_insert_layer(image_layer.clone());
7127 : }
7128 :
7129 : // Update remote_timeline_client state to reflect existence of this layer
7130 36 : self.remote_client
7131 36 : .schedule_layer_file_upload(image_layer)
7132 36 : .unwrap();
7133 :
7134 36 : Ok(())
7135 36 : }
7136 :
7137 : /// Force create a delta layer and place it into the layer map.
7138 : ///
7139 : /// DO NOT use this function directly. Use [`TenantShard::branch_timeline_test_with_layers`]
7140 : /// or [`TenantShard::create_test_timeline_with_layers`] to ensure all these layers are
7141 : /// placed into the layer map in one run AND be validated.
7142 : #[cfg(test)]
7143 50 : pub(super) async fn force_create_delta_layer(
7144 50 : self: &Arc<Timeline>,
7145 50 : mut deltas: DeltaLayerTestDesc,
7146 50 : check_start_lsn: Option<Lsn>,
7147 50 : ctx: &RequestContext,
7148 50 : ) -> anyhow::Result<()> {
7149 50 : let last_record_lsn = self.get_last_record_lsn();
7150 50 : deltas
7151 50 : .data
7152 124364 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
7153 50 : assert!(deltas.data.first().unwrap().0 >= deltas.key_range.start);
7154 50 : assert!(deltas.data.last().unwrap().0 < deltas.key_range.end);
7155 10464 : for (_, lsn, _) in &deltas.data {
7156 10414 : assert!(deltas.lsn_range.start <= *lsn && *lsn < deltas.lsn_range.end);
7157 : }
7158 50 : assert!(
7159 50 : deltas.lsn_range.end <= last_record_lsn,
7160 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
7161 : deltas.lsn_range.end,
7162 : last_record_lsn
7163 : );
7164 50 : if let Some(check_start_lsn) = check_start_lsn {
7165 50 : assert!(deltas.lsn_range.start >= check_start_lsn);
7166 0 : }
7167 50 : let mut delta_layer_writer = DeltaLayerWriter::new(
7168 50 : self.conf,
7169 50 : self.timeline_id,
7170 50 : self.tenant_shard_id,
7171 50 : deltas.key_range.start,
7172 50 : deltas.lsn_range,
7173 50 : &self.gate,
7174 50 : self.cancel.clone(),
7175 50 : ctx,
7176 50 : )
7177 50 : .await?;
7178 10464 : for (key, lsn, val) in deltas.data {
7179 10414 : delta_layer_writer.put_value(key, lsn, val, ctx).await?;
7180 : }
7181 50 : let (desc, path) = delta_layer_writer.finish(deltas.key_range.end, ctx).await?;
7182 50 : let delta_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
7183 50 : info!("force created delta layer {}", delta_layer.local_path());
7184 : {
7185 50 : let mut guard = self.layers.write(LayerManagerLockHolder::Testing).await;
7186 50 : guard
7187 50 : .open_mut()
7188 50 : .unwrap()
7189 50 : .force_insert_layer(delta_layer.clone());
7190 : }
7191 :
7192 : // Update remote_timeline_client state to reflect existence of this layer
7193 50 : self.remote_client
7194 50 : .schedule_layer_file_upload(delta_layer)
7195 50 : .unwrap();
7196 :
7197 50 : Ok(())
7198 50 : }
7199 :
7200 : /// Force create an in-memory layer and place them into the layer map.
7201 : #[cfg(test)]
7202 4 : pub(super) async fn force_create_in_memory_layer(
7203 4 : self: &Arc<Timeline>,
7204 4 : mut in_memory: InMemoryLayerTestDesc,
7205 4 : check_start_lsn: Option<Lsn>,
7206 4 : ctx: &RequestContext,
7207 4 : ) -> anyhow::Result<()> {
7208 : use utils::bin_ser::BeSer;
7209 :
7210 : // Validate LSNs
7211 4 : if let Some(check_start_lsn) = check_start_lsn {
7212 4 : assert!(in_memory.lsn_range.start >= check_start_lsn);
7213 0 : }
7214 :
7215 4 : let last_record_lsn = self.get_last_record_lsn();
7216 4 : let layer_end_lsn = if in_memory.is_open {
7217 1 : in_memory
7218 1 : .data
7219 1 : .iter()
7220 1 : .map(|(_key, lsn, _value)| lsn)
7221 1 : .max()
7222 1 : .cloned()
7223 : } else {
7224 3 : Some(in_memory.lsn_range.end)
7225 : };
7226 :
7227 4 : if let Some(end) = layer_end_lsn {
7228 4 : assert!(
7229 4 : end <= last_record_lsn,
7230 0 : "advance last record lsn before inserting a layer, end_lsn={end}, last_record_lsn={last_record_lsn}",
7231 : );
7232 0 : }
7233 :
7234 19820 : in_memory.data.iter().for_each(|(_key, lsn, _value)| {
7235 19820 : assert!(*lsn >= in_memory.lsn_range.start);
7236 19820 : assert!(*lsn < in_memory.lsn_range.end);
7237 19820 : });
7238 :
7239 : // Build the batch
7240 4 : in_memory
7241 4 : .data
7242 273384 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
7243 :
7244 4 : let data = in_memory
7245 4 : .data
7246 4 : .into_iter()
7247 19820 : .map(|(key, lsn, value)| {
7248 19820 : let value_size = value.serialized_size().unwrap() as usize;
7249 19820 : (key.to_compact(), lsn, value_size, value)
7250 19820 : })
7251 4 : .collect::<Vec<_>>();
7252 :
7253 4 : let batch = SerializedValueBatch::from_values(data);
7254 :
7255 : // Create the in-memory layer and write the batch into it
7256 4 : let layer = InMemoryLayer::create(
7257 4 : self.conf,
7258 4 : self.timeline_id,
7259 4 : self.tenant_shard_id,
7260 4 : in_memory.lsn_range.start,
7261 4 : &self.gate,
7262 4 : // TODO: if we ever use this function in production code, we need to pass the real cancellation token
7263 4 : &CancellationToken::new(),
7264 4 : ctx,
7265 4 : )
7266 4 : .await
7267 4 : .unwrap();
7268 :
7269 4 : layer.put_batch(batch, ctx).await.unwrap();
7270 4 : if !in_memory.is_open {
7271 3 : layer.freeze(in_memory.lsn_range.end).await;
7272 1 : }
7273 :
7274 4 : info!("force created in-memory layer {:?}", in_memory.lsn_range);
7275 :
7276 : // Link the layer to the layer map
7277 : {
7278 4 : let mut guard = self.layers.write(LayerManagerLockHolder::Testing).await;
7279 4 : let layer_map = guard.open_mut().unwrap();
7280 4 : layer_map.force_insert_in_memory_layer(Arc::new(layer));
7281 : }
7282 :
7283 4 : Ok(())
7284 4 : }
7285 :
7286 : /// Return all keys at the LSN in the image layers
7287 : #[cfg(test)]
7288 3 : pub(crate) async fn inspect_image_layers(
7289 3 : self: &Arc<Timeline>,
7290 3 : lsn: Lsn,
7291 3 : ctx: &RequestContext,
7292 3 : io_concurrency: IoConcurrency,
7293 3 : ) -> anyhow::Result<Vec<(Key, Bytes)>> {
7294 3 : let mut all_data = Vec::new();
7295 3 : let guard = self.layers.read(LayerManagerLockHolder::Testing).await;
7296 17 : for layer in guard.layer_map()?.iter_historic_layers() {
7297 17 : if !layer.is_delta() && layer.image_layer_lsn() == lsn {
7298 4 : let layer = guard.get_from_desc(&layer);
7299 4 : let mut reconstruct_data = ValuesReconstructState::new(io_concurrency.clone());
7300 4 : layer
7301 4 : .get_values_reconstruct_data(
7302 4 : KeySpace::single(Key::MIN..Key::MAX),
7303 4 : lsn..Lsn(lsn.0 + 1),
7304 4 : &mut reconstruct_data,
7305 4 : ctx,
7306 4 : )
7307 4 : .await?;
7308 33 : for (k, v) in std::mem::take(&mut reconstruct_data.keys) {
7309 33 : let v = v.collect_pending_ios().await?;
7310 33 : all_data.push((k, v.img.unwrap().1));
7311 : }
7312 13 : }
7313 : }
7314 3 : all_data.sort();
7315 3 : Ok(all_data)
7316 3 : }
7317 :
7318 : /// Get all historic layer descriptors in the layer map
7319 : #[cfg(test)]
7320 12 : pub(crate) async fn inspect_historic_layers(
7321 12 : self: &Arc<Timeline>,
7322 12 : ) -> anyhow::Result<Vec<super::storage_layer::PersistentLayerKey>> {
7323 12 : let mut layers = Vec::new();
7324 12 : let guard = self.layers.read(LayerManagerLockHolder::Testing).await;
7325 57 : for layer in guard.layer_map()?.iter_historic_layers() {
7326 57 : layers.push(layer.key());
7327 57 : }
7328 12 : Ok(layers)
7329 12 : }
7330 :
7331 : #[cfg(test)]
7332 5 : pub(crate) fn add_extra_test_dense_keyspace(&self, ks: KeySpace) {
7333 5 : let mut keyspace = self.extra_test_dense_keyspace.load().as_ref().clone();
7334 5 : keyspace.merge(&ks);
7335 5 : self.extra_test_dense_keyspace.store(Arc::new(keyspace));
7336 5 : }
7337 : }
7338 :
7339 : /// Tracking writes ingestion does to a particular in-memory layer.
7340 : ///
7341 : /// Cleared upon freezing a layer.
7342 : pub(crate) struct TimelineWriterState {
7343 : open_layer: Arc<InMemoryLayer>,
7344 : current_size: u64,
7345 : // Previous Lsn which passed through
7346 : prev_lsn: Option<Lsn>,
7347 : // Largest Lsn which passed through the current writer
7348 : max_lsn: Option<Lsn>,
7349 : // Cached details of the last freeze. Avoids going trough the atomic/lock on every put.
7350 : cached_last_freeze_at: Lsn,
7351 : }
7352 :
7353 : impl TimelineWriterState {
7354 659 : fn new(open_layer: Arc<InMemoryLayer>, current_size: u64, last_freeze_at: Lsn) -> Self {
7355 659 : Self {
7356 659 : open_layer,
7357 659 : current_size,
7358 659 : prev_lsn: None,
7359 659 : max_lsn: None,
7360 659 : cached_last_freeze_at: last_freeze_at,
7361 659 : }
7362 659 : }
7363 : }
7364 :
7365 : /// Various functions to mutate the timeline.
7366 : // TODO Currently, Deref is used to allow easy access to read methods from this trait.
7367 : // This is probably considered a bad practice in Rust and should be fixed eventually,
7368 : // but will cause large code changes.
7369 : pub(crate) struct TimelineWriter<'a> {
7370 : tl: &'a Timeline,
7371 : write_guard: tokio::sync::MutexGuard<'a, Option<TimelineWriterState>>,
7372 : }
7373 :
7374 : impl Deref for TimelineWriter<'_> {
7375 : type Target = Timeline;
7376 :
7377 4949213 : fn deref(&self) -> &Self::Target {
7378 4949213 : self.tl
7379 4949213 : }
7380 : }
7381 :
7382 : #[derive(PartialEq)]
7383 : enum OpenLayerAction {
7384 : Roll,
7385 : Open,
7386 : None,
7387 : }
7388 :
7389 : impl TimelineWriter<'_> {
7390 2402128 : async fn handle_open_layer_action(
7391 2402128 : &mut self,
7392 2402128 : at: Lsn,
7393 2402128 : action: OpenLayerAction,
7394 2402128 : ctx: &RequestContext,
7395 2402128 : ) -> anyhow::Result<&Arc<InMemoryLayer>> {
7396 2402128 : match action {
7397 : OpenLayerAction::Roll => {
7398 40 : let freeze_at = self.write_guard.as_ref().unwrap().max_lsn.unwrap();
7399 40 : self.roll_layer(freeze_at).await?;
7400 40 : self.open_layer(at, ctx).await?;
7401 : }
7402 619 : OpenLayerAction::Open => self.open_layer(at, ctx).await?,
7403 : OpenLayerAction::None => {
7404 2401469 : assert!(self.write_guard.is_some());
7405 : }
7406 : }
7407 :
7408 2402128 : Ok(&self.write_guard.as_ref().unwrap().open_layer)
7409 2402128 : }
7410 :
7411 659 : async fn open_layer(&mut self, at: Lsn, ctx: &RequestContext) -> anyhow::Result<()> {
7412 659 : let layer = self
7413 659 : .tl
7414 659 : .get_layer_for_write(at, &self.write_guard, ctx)
7415 659 : .await?;
7416 659 : let initial_size = layer.len();
7417 :
7418 659 : let last_freeze_at = self.last_freeze_at.load();
7419 659 : self.write_guard.replace(TimelineWriterState::new(
7420 659 : layer,
7421 659 : initial_size,
7422 659 : last_freeze_at,
7423 659 : ));
7424 :
7425 659 : Ok(())
7426 659 : }
7427 :
7428 40 : async fn roll_layer(&mut self, freeze_at: Lsn) -> Result<(), FlushLayerError> {
7429 40 : let current_size = self.write_guard.as_ref().unwrap().current_size;
7430 :
7431 : // If layer flushes are backpressured due to compaction not keeping up, wait for the flush
7432 : // to propagate the backpressure up into WAL ingestion.
7433 40 : let l0_count = self
7434 40 : .tl
7435 40 : .layers
7436 40 : .read(LayerManagerLockHolder::GetLayerMapInfo)
7437 40 : .await
7438 40 : .layer_map()?
7439 40 : .level0_deltas()
7440 40 : .len();
7441 40 : let wait_thresholds = [
7442 40 : self.get_l0_flush_delay_threshold(),
7443 40 : self.get_l0_flush_stall_threshold(),
7444 40 : ];
7445 40 : let wait_threshold = wait_thresholds.into_iter().flatten().min();
7446 :
7447 : // self.write_guard will be taken by the freezing
7448 40 : let flush_id = self
7449 40 : .tl
7450 40 : .freeze_inmem_layer_at(freeze_at, &mut self.write_guard)
7451 40 : .await?;
7452 :
7453 40 : assert!(self.write_guard.is_none());
7454 :
7455 40 : if let Some(wait_threshold) = wait_threshold {
7456 0 : if l0_count >= wait_threshold {
7457 0 : debug!(
7458 0 : "layer roll waiting for flush due to compaction backpressure at {l0_count} L0 layers"
7459 : );
7460 0 : self.tl.wait_flush_completion(flush_id).await?;
7461 0 : }
7462 40 : }
7463 :
7464 40 : if current_size >= self.get_checkpoint_distance() * 2 {
7465 0 : warn!("Flushed oversized open layer with size {}", current_size)
7466 40 : }
7467 :
7468 40 : Ok(())
7469 40 : }
7470 :
7471 2402128 : fn get_open_layer_action(&self, lsn: Lsn, new_value_size: u64) -> OpenLayerAction {
7472 2402128 : let state = &*self.write_guard;
7473 2402128 : let Some(state) = &state else {
7474 619 : return OpenLayerAction::Open;
7475 : };
7476 :
7477 : #[cfg(feature = "testing")]
7478 2401509 : if state.cached_last_freeze_at < self.tl.last_freeze_at.load() {
7479 : // this check and assertion are not really needed because
7480 : // LayerManager::try_freeze_in_memory_layer will always clear out the
7481 : // TimelineWriterState if something is frozen. however, we can advance last_freeze_at when there
7482 : // is no TimelineWriterState.
7483 0 : assert!(
7484 0 : state.open_layer.end_lsn.get().is_some(),
7485 0 : "our open_layer must be outdated"
7486 : );
7487 :
7488 : // this would be a memory leak waiting to happen because the in-memory layer always has
7489 : // an index
7490 0 : panic!("BUG: TimelineWriterState held on to frozen in-memory layer.");
7491 2401509 : }
7492 :
7493 2401509 : if state.prev_lsn == Some(lsn) {
7494 : // Rolling mid LSN is not supported by [downstream code].
7495 : // Hence, only roll at LSN boundaries.
7496 : //
7497 : // [downstream code]: https://github.com/neondatabase/neon/pull/7993#discussion_r1633345422
7498 3 : return OpenLayerAction::None;
7499 2401506 : }
7500 :
7501 2401506 : if state.current_size == 0 {
7502 : // Don't roll empty layers
7503 0 : return OpenLayerAction::None;
7504 2401506 : }
7505 :
7506 2401506 : if self.tl.should_roll(
7507 2401506 : state.current_size,
7508 2401506 : state.current_size + new_value_size,
7509 2401506 : self.get_checkpoint_distance(),
7510 2401506 : lsn,
7511 2401506 : state.cached_last_freeze_at,
7512 2401506 : state.open_layer.get_opened_at(),
7513 : ) {
7514 40 : OpenLayerAction::Roll
7515 : } else {
7516 2401466 : OpenLayerAction::None
7517 : }
7518 2402128 : }
7519 :
7520 : /// Put a batch of keys at the specified Lsns.
7521 2402127 : pub(crate) async fn put_batch(
7522 2402127 : &mut self,
7523 2402127 : batch: SerializedValueBatch,
7524 2402127 : ctx: &RequestContext,
7525 2402127 : ) -> anyhow::Result<()> {
7526 2402127 : if !batch.has_data() {
7527 0 : return Ok(());
7528 2402127 : }
7529 :
7530 : // In debug builds, assert that we don't write any keys that don't belong to this shard.
7531 : // We don't assert this in release builds, since key ownership policies may change over
7532 : // time. Stray keys will be removed during compaction.
7533 2402127 : if cfg!(debug_assertions) {
7534 4947521 : for metadata in &batch.metadata {
7535 2545394 : if let ValueMeta::Serialized(metadata) = metadata {
7536 2545394 : let key = Key::from_compact(metadata.key);
7537 2545394 : assert!(
7538 2545394 : self.shard_identity.is_key_local(&key)
7539 12 : || self.shard_identity.is_key_global(&key),
7540 0 : "key {key} does not belong on shard {}",
7541 0 : self.shard_identity.shard_index()
7542 : );
7543 0 : }
7544 : }
7545 0 : }
7546 :
7547 2402127 : let batch_max_lsn = batch.max_lsn;
7548 2402127 : let buf_size: u64 = batch.buffer_size() as u64;
7549 :
7550 2402127 : let action = self.get_open_layer_action(batch_max_lsn, buf_size);
7551 2402127 : let layer = self
7552 2402127 : .handle_open_layer_action(batch_max_lsn, action, ctx)
7553 2402127 : .await?;
7554 :
7555 2402127 : let res = layer.put_batch(batch, ctx).await;
7556 :
7557 2402127 : if res.is_ok() {
7558 2402127 : // Update the current size only when the entire write was ok.
7559 2402127 : // In case of failures, we may have had partial writes which
7560 2402127 : // render the size tracking out of sync. That's ok because
7561 2402127 : // the checkpoint distance should be significantly smaller
7562 2402127 : // than the S3 single shot upload limit of 5GiB.
7563 2402127 : let state = self.write_guard.as_mut().unwrap();
7564 2402127 :
7565 2402127 : state.current_size += buf_size;
7566 2402127 : state.prev_lsn = Some(batch_max_lsn);
7567 2402127 : state.max_lsn = std::cmp::max(state.max_lsn, Some(batch_max_lsn));
7568 2402127 : }
7569 :
7570 2402127 : res
7571 2402127 : }
7572 :
7573 : #[cfg(test)]
7574 : /// Test helper, for tests that would like to poke individual values without composing a batch
7575 2195079 : pub(crate) async fn put(
7576 2195079 : &mut self,
7577 2195079 : key: Key,
7578 2195079 : lsn: Lsn,
7579 2195079 : value: &Value,
7580 2195079 : ctx: &RequestContext,
7581 2195079 : ) -> anyhow::Result<()> {
7582 : use utils::bin_ser::BeSer;
7583 2195079 : if !key.is_valid_key_on_write_path() {
7584 0 : bail!(
7585 0 : "the request contains data not supported by pageserver at TimelineWriter::put: {}",
7586 : key
7587 : );
7588 2195079 : }
7589 2195079 : let val_ser_size = value.serialized_size().unwrap() as usize;
7590 2195079 : let batch = SerializedValueBatch::from_values(vec![(
7591 2195079 : key.to_compact(),
7592 2195079 : lsn,
7593 2195079 : val_ser_size,
7594 2195079 : value.clone(),
7595 2195079 : )]);
7596 :
7597 2195079 : self.put_batch(batch, ctx).await
7598 2195079 : }
7599 :
7600 1 : pub(crate) async fn delete_batch(
7601 1 : &mut self,
7602 1 : batch: &[(Range<Key>, Lsn)],
7603 1 : ctx: &RequestContext,
7604 1 : ) -> anyhow::Result<()> {
7605 1 : if let Some((_, lsn)) = batch.first() {
7606 1 : let action = self.get_open_layer_action(*lsn, 0);
7607 1 : let layer = self.handle_open_layer_action(*lsn, action, ctx).await?;
7608 1 : layer.put_tombstones(batch).await?;
7609 0 : }
7610 :
7611 1 : Ok(())
7612 1 : }
7613 :
7614 : /// Track the end of the latest digested WAL record.
7615 : /// Remember the (end of) last valid WAL record remembered in the timeline.
7616 : ///
7617 : /// Call this after you have finished writing all the WAL up to 'lsn'.
7618 : ///
7619 : /// 'lsn' must be aligned. This wakes up any wait_lsn() callers waiting for
7620 : /// the 'lsn' or anything older. The previous last record LSN is stored alongside
7621 : /// the latest and can be read.
7622 2639558 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
7623 2639558 : self.tl.finish_write(new_lsn);
7624 2639558 : }
7625 :
7626 135285 : pub(crate) fn update_current_logical_size(&self, delta: i64) {
7627 135285 : self.tl.update_current_logical_size(delta)
7628 135285 : }
7629 : }
7630 :
7631 : // We need TimelineWriter to be send in upcoming conversion of
7632 : // Timeline::layers to tokio::sync::RwLock.
7633 : #[test]
7634 1 : fn is_send() {
7635 1 : fn _assert_send<T: Send>() {}
7636 1 : _assert_send::<TimelineWriter<'_>>();
7637 1 : }
7638 :
7639 : #[cfg(test)]
7640 : mod tests {
7641 : use std::sync::Arc;
7642 :
7643 : use pageserver_api::key::Key;
7644 : use postgres_ffi::PgMajorVersion;
7645 : use std::iter::Iterator;
7646 : use tracing::Instrument;
7647 : use utils::id::TimelineId;
7648 : use utils::lsn::Lsn;
7649 : use wal_decoder::models::value::Value;
7650 :
7651 : use super::HeatMapTimeline;
7652 : use crate::context::RequestContextBuilder;
7653 : use crate::tenant::harness::{TenantHarness, test_img};
7654 : use crate::tenant::layer_map::LayerMap;
7655 : use crate::tenant::storage_layer::{Layer, LayerName, LayerVisibilityHint};
7656 : use crate::tenant::timeline::layer_manager::LayerManagerLockHolder;
7657 : use crate::tenant::timeline::{DeltaLayerTestDesc, EvictionError};
7658 : use crate::tenant::{PreviousHeatmap, Timeline};
7659 :
7660 5 : fn assert_heatmaps_have_same_layers(lhs: &HeatMapTimeline, rhs: &HeatMapTimeline) {
7661 5 : assert_eq!(lhs.all_layers().count(), rhs.all_layers().count());
7662 5 : let lhs_rhs = lhs.all_layers().zip(rhs.all_layers());
7663 25 : for (l, r) in lhs_rhs {
7664 20 : assert_eq!(l.name, r.name);
7665 20 : assert_eq!(l.metadata, r.metadata);
7666 : }
7667 5 : }
7668 :
7669 : #[tokio::test]
7670 1 : async fn test_heatmap_generation() {
7671 1 : let harness = TenantHarness::create("heatmap_generation").await.unwrap();
7672 :
7673 1 : let covered_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7674 1 : Lsn(0x10)..Lsn(0x20),
7675 1 : vec![(
7676 1 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7677 1 : Lsn(0x11),
7678 1 : Value::Image(test_img("foo")),
7679 1 : )],
7680 : );
7681 1 : let visible_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
7682 1 : Lsn(0x10)..Lsn(0x20),
7683 1 : vec![(
7684 1 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7685 1 : Lsn(0x11),
7686 1 : Value::Image(test_img("foo")),
7687 1 : )],
7688 : );
7689 1 : let l0_delta = DeltaLayerTestDesc::new(
7690 1 : Lsn(0x20)..Lsn(0x30),
7691 1 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7692 1 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7693 1 : vec![(
7694 1 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7695 1 : Lsn(0x25),
7696 1 : Value::Image(test_img("foo")),
7697 1 : )],
7698 : );
7699 1 : let delta_layers = vec![
7700 1 : covered_delta.clone(),
7701 1 : visible_delta.clone(),
7702 1 : l0_delta.clone(),
7703 : ];
7704 :
7705 1 : let image_layer = (
7706 1 : Lsn(0x40),
7707 1 : vec![(
7708 1 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7709 1 : test_img("bar"),
7710 1 : )],
7711 1 : );
7712 1 : let image_layers = vec![image_layer];
7713 :
7714 1 : let (tenant, ctx) = harness.load().await;
7715 1 : let timeline = tenant
7716 1 : .create_test_timeline_with_layers(
7717 1 : TimelineId::generate(),
7718 1 : Lsn(0x10),
7719 1 : PgMajorVersion::PG14,
7720 1 : &ctx,
7721 1 : Vec::new(), // in-memory layers
7722 1 : delta_layers,
7723 1 : image_layers,
7724 1 : Lsn(0x100),
7725 1 : )
7726 1 : .await
7727 1 : .unwrap();
7728 1 : let ctx = &ctx.with_scope_timeline(&timeline);
7729 :
7730 : // Layer visibility is an input to heatmap generation, so refresh it first
7731 1 : timeline.update_layer_visibility().await.unwrap();
7732 :
7733 1 : let heatmap = timeline
7734 1 : .generate_heatmap()
7735 1 : .await
7736 1 : .expect("Infallible while timeline is not shut down");
7737 :
7738 1 : assert_eq!(heatmap.timeline_id, timeline.timeline_id);
7739 :
7740 : // L0 should come last
7741 1 : let heatmap_layers = heatmap.all_layers().collect::<Vec<_>>();
7742 1 : assert_eq!(heatmap_layers.last().unwrap().name, l0_delta.layer_name());
7743 :
7744 1 : let mut last_lsn = Lsn::MAX;
7745 5 : for layer in heatmap_layers {
7746 : // Covered layer should be omitted
7747 4 : assert!(layer.name != covered_delta.layer_name());
7748 :
7749 4 : let layer_lsn = match &layer.name {
7750 2 : LayerName::Delta(d) => d.lsn_range.end,
7751 2 : LayerName::Image(i) => i.lsn,
7752 : };
7753 :
7754 : // Apart from L0s, newest Layers should come first
7755 4 : if !LayerMap::is_l0(layer.name.key_range(), layer.name.is_delta()) {
7756 3 : assert!(layer_lsn <= last_lsn);
7757 3 : last_lsn = layer_lsn;
7758 1 : }
7759 : }
7760 :
7761 : // Evict all the layers and stash the old heatmap in the timeline.
7762 : // This simulates a migration to a cold secondary location.
7763 :
7764 1 : let guard = timeline.layers.read(LayerManagerLockHolder::Testing).await;
7765 1 : let mut all_layers = Vec::new();
7766 1 : let forever = std::time::Duration::from_secs(120);
7767 5 : for layer in guard.likely_resident_layers() {
7768 5 : all_layers.push(layer.clone());
7769 5 : layer.evict_and_wait(forever).await.unwrap();
7770 : }
7771 1 : drop(guard);
7772 :
7773 1 : timeline
7774 1 : .previous_heatmap
7775 1 : .store(Some(Arc::new(PreviousHeatmap::Active {
7776 1 : heatmap: heatmap.clone(),
7777 1 : read_at: std::time::Instant::now(),
7778 1 : end_lsn: None,
7779 1 : })));
7780 :
7781 : // Generate a new heatmap and assert that it contains the same layers as the old one.
7782 1 : let post_migration_heatmap = timeline.generate_heatmap().await.unwrap();
7783 1 : assert_heatmaps_have_same_layers(&heatmap, &post_migration_heatmap);
7784 :
7785 : // Download each layer one by one. Generate the heatmap at each step and check
7786 : // that it's stable.
7787 6 : for layer in all_layers {
7788 5 : if layer.visibility() == LayerVisibilityHint::Covered {
7789 1 : continue;
7790 4 : }
7791 1 :
7792 4 : eprintln!("Downloading {layer} and re-generating heatmap");
7793 1 :
7794 4 : let ctx = &RequestContextBuilder::from(ctx)
7795 4 : .download_behavior(crate::context::DownloadBehavior::Download)
7796 4 : .attached_child();
7797 1 :
7798 4 : let _resident = layer
7799 4 : .download_and_keep_resident(ctx)
7800 4 : .instrument(tracing::info_span!(
7801 4 : parent: None,
7802 1 : "download_layer",
7803 1 : tenant_id = %timeline.tenant_shard_id.tenant_id,
7804 1 : shard_id = %timeline.tenant_shard_id.shard_slug(),
7805 1 : timeline_id = %timeline.timeline_id
7806 1 : ))
7807 4 : .await
7808 4 : .unwrap();
7809 1 :
7810 4 : let post_download_heatmap = timeline.generate_heatmap().await.unwrap();
7811 4 : assert_heatmaps_have_same_layers(&heatmap, &post_download_heatmap);
7812 1 : }
7813 1 :
7814 1 : // Everything from the post-migration heatmap is now resident.
7815 1 : // Check that we drop it from memory.
7816 1 : assert!(matches!(
7817 1 : timeline.previous_heatmap.load().as_deref(),
7818 1 : Some(PreviousHeatmap::Obsolete)
7819 1 : ));
7820 1 : }
7821 :
7822 : #[tokio::test]
7823 1 : async fn test_previous_heatmap_obsoletion() {
7824 1 : let harness = TenantHarness::create("heatmap_previous_heatmap_obsoletion")
7825 1 : .await
7826 1 : .unwrap();
7827 :
7828 1 : let l0_delta = DeltaLayerTestDesc::new(
7829 1 : Lsn(0x20)..Lsn(0x30),
7830 1 : Key::from_hex("000000000000000000000000000000000000").unwrap()
7831 1 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
7832 1 : vec![(
7833 1 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
7834 1 : Lsn(0x25),
7835 1 : Value::Image(test_img("foo")),
7836 1 : )],
7837 : );
7838 :
7839 1 : let image_layer = (
7840 1 : Lsn(0x40),
7841 1 : vec![(
7842 1 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
7843 1 : test_img("bar"),
7844 1 : )],
7845 1 : );
7846 :
7847 1 : let delta_layers = vec![l0_delta];
7848 1 : let image_layers = vec![image_layer];
7849 :
7850 1 : let (tenant, ctx) = harness.load().await;
7851 1 : let timeline = tenant
7852 1 : .create_test_timeline_with_layers(
7853 1 : TimelineId::generate(),
7854 1 : Lsn(0x10),
7855 1 : PgMajorVersion::PG14,
7856 1 : &ctx,
7857 1 : Vec::new(), // in-memory layers
7858 1 : delta_layers,
7859 1 : image_layers,
7860 1 : Lsn(0x100),
7861 1 : )
7862 1 : .await
7863 1 : .unwrap();
7864 :
7865 : // Layer visibility is an input to heatmap generation, so refresh it first
7866 1 : timeline.update_layer_visibility().await.unwrap();
7867 :
7868 1 : let heatmap = timeline
7869 1 : .generate_heatmap()
7870 1 : .await
7871 1 : .expect("Infallible while timeline is not shut down");
7872 :
7873 : // Both layers should be in the heatmap
7874 1 : assert!(heatmap.all_layers().count() > 0);
7875 :
7876 : // Now simulate a migration.
7877 1 : timeline
7878 1 : .previous_heatmap
7879 1 : .store(Some(Arc::new(PreviousHeatmap::Active {
7880 1 : heatmap: heatmap.clone(),
7881 1 : read_at: std::time::Instant::now(),
7882 1 : end_lsn: None,
7883 1 : })));
7884 :
7885 : // Evict all the layers in the previous heatmap
7886 1 : let guard = timeline.layers.read(LayerManagerLockHolder::Testing).await;
7887 1 : let forever = std::time::Duration::from_secs(120);
7888 3 : for layer in guard.likely_resident_layers() {
7889 3 : layer.evict_and_wait(forever).await.unwrap();
7890 : }
7891 1 : drop(guard);
7892 :
7893 : // Generate a new heatmap and check that the previous heatmap
7894 : // has been marked obsolete.
7895 1 : let post_eviction_heatmap = timeline
7896 1 : .generate_heatmap()
7897 1 : .await
7898 1 : .expect("Infallible while timeline is not shut down");
7899 :
7900 1 : assert_eq!(post_eviction_heatmap.all_layers().count(), 0);
7901 1 : assert!(matches!(
7902 1 : timeline.previous_heatmap.load().as_deref(),
7903 1 : Some(PreviousHeatmap::Obsolete)
7904 1 : ));
7905 1 : }
7906 :
7907 : #[tokio::test]
7908 1 : async fn two_layer_eviction_attempts_at_the_same_time() {
7909 1 : let harness = TenantHarness::create("two_layer_eviction_attempts_at_the_same_time")
7910 1 : .await
7911 1 : .unwrap();
7912 :
7913 1 : let (tenant, ctx) = harness.load().await;
7914 1 : let timeline = tenant
7915 1 : .create_test_timeline(
7916 1 : TimelineId::generate(),
7917 1 : Lsn(0x10),
7918 1 : PgMajorVersion::PG14,
7919 1 : &ctx,
7920 1 : )
7921 1 : .await
7922 1 : .unwrap();
7923 :
7924 1 : let layer = find_some_layer(&timeline).await;
7925 1 : let layer = layer
7926 1 : .keep_resident()
7927 1 : .await
7928 1 : .expect("no download => no downloading errors")
7929 1 : .drop_eviction_guard();
7930 :
7931 1 : let forever = std::time::Duration::from_secs(120);
7932 :
7933 1 : let first = layer.evict_and_wait(forever);
7934 1 : let second = layer.evict_and_wait(forever);
7935 :
7936 1 : let (first, second) = tokio::join!(first, second);
7937 :
7938 1 : let res = layer.keep_resident().await;
7939 1 : assert!(res.is_none(), "{res:?}");
7940 :
7941 1 : match (first, second) {
7942 1 : (Ok(()), Ok(())) => {
7943 1 : // because there are no more timeline locks being taken on eviction path, we can
7944 1 : // witness all three outcomes here.
7945 1 : }
7946 1 : (Ok(()), Err(EvictionError::NotFound)) | (Err(EvictionError::NotFound), Ok(())) => {
7947 0 : // if one completes before the other, this is fine just as well.
7948 0 : }
7949 1 : other => unreachable!("unexpected {:?}", other),
7950 1 : }
7951 1 : }
7952 :
7953 1 : async fn find_some_layer(timeline: &Timeline) -> Layer {
7954 1 : let layers = timeline
7955 1 : .layers
7956 1 : .read(LayerManagerLockHolder::GetLayerMapInfo)
7957 1 : .await;
7958 1 : let desc = layers
7959 1 : .layer_map()
7960 1 : .unwrap()
7961 1 : .iter_historic_layers()
7962 1 : .next()
7963 1 : .expect("must find one layer to evict");
7964 :
7965 1 : layers.get_from_desc(&desc)
7966 1 : }
7967 : }
|