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