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