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