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