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