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