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