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