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