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(crate) 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 606820 : pub(crate) async fn get(
963 606820 : &self,
964 606820 : key: Key,
965 606820 : lsn: Lsn,
966 606820 : ctx: &RequestContext,
967 606820 : ) -> Result<Bytes, PageReconstructError> {
968 606820 : if !lsn.is_valid() {
969 0 : return Err(PageReconstructError::Other(anyhow::anyhow!("Invalid LSN")));
970 606820 : }
971 606820 :
972 606820 : // This check is debug-only because of the cost of hashing, and because it's a double-check: we
973 606820 : // already checked the key against the shard_identity when looking up the Timeline from
974 606820 : // page_service.
975 606820 : debug_assert!(!self.shard_identity.is_key_disposable(&key));
976 :
977 606820 : self.timeline_get_throttle.throttle(ctx, 1).await;
978 :
979 606820 : let keyspace = KeySpace {
980 606820 : ranges: vec![key..key.next()],
981 606820 : };
982 606820 :
983 606820 : // Initialise the reconstruct state for the key with the cache
984 606820 : // entry returned above.
985 606820 : let mut reconstruct_state = ValuesReconstructState::new();
986 :
987 606820 : let vectored_res = self
988 606820 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
989 183123 : .await;
990 :
991 606820 : let key_value = vectored_res?.pop_first();
992 606814 : match key_value {
993 606802 : Some((got_key, value)) => {
994 606802 : 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 606802 : 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 606820 : }
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 626662 : pub(super) async fn get_vectored_impl(
1162 626662 : &self,
1163 626662 : keyspace: KeySpace,
1164 626662 : lsn: Lsn,
1165 626662 : reconstruct_state: &mut ValuesReconstructState,
1166 626662 : ctx: &RequestContext,
1167 626662 : ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
1168 626662 : let get_kind = if keyspace.total_raw_size() == 1 {
1169 626226 : GetKind::Singular
1170 : } else {
1171 436 : GetKind::Vectored
1172 : };
1173 :
1174 626662 : let get_data_timer = crate::metrics::GET_RECONSTRUCT_DATA_TIME
1175 626662 : .for_get_kind(get_kind)
1176 626662 : .start_timer();
1177 626662 : self.get_vectored_reconstruct_data(keyspace.clone(), lsn, reconstruct_state, ctx)
1178 192289 : .await?;
1179 626646 : get_data_timer.stop_and_record();
1180 626646 :
1181 626646 : let reconstruct_timer = crate::metrics::RECONSTRUCT_TIME
1182 626646 : .for_get_kind(get_kind)
1183 626646 : .start_timer();
1184 626646 : let mut results: BTreeMap<Key, Result<Bytes, PageReconstructError>> = BTreeMap::new();
1185 626646 : let layers_visited = reconstruct_state.get_layers_visited();
1186 :
1187 666972 : for (key, res) in std::mem::take(&mut reconstruct_state.keys) {
1188 666972 : match res {
1189 0 : Err(err) => {
1190 0 : results.insert(key, Err(err));
1191 0 : }
1192 666972 : Ok(state) => {
1193 666972 : let state = ValueReconstructState::from(state);
1194 :
1195 666972 : let reconstruct_res = self.reconstruct_value(key, lsn, state).await;
1196 666972 : results.insert(key, reconstruct_res);
1197 : }
1198 : }
1199 : }
1200 626646 : reconstruct_timer.stop_and_record();
1201 626646 :
1202 626646 : // For aux file keys (v1 or v2) the vectored read path does not return an error
1203 626646 : // when they're missing. Instead they are omitted from the resulting btree
1204 626646 : // (this is a requirement, not a bug). Skip updating the metric in these cases
1205 626646 : // to avoid infinite results.
1206 626646 : if !results.is_empty() {
1207 626440 : let avg = layers_visited as f64 / results.len() as f64;
1208 626440 : 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 626440 : }
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 626440 : crate::metrics::VEC_READ_NUM_LAYERS_VISITED.observe(avg);
1226 206 : }
1227 :
1228 626646 : Ok(results)
1229 626662 : }
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 226785 : pub(crate) async fn wait_lsn(
1292 226785 : &self,
1293 226785 : lsn: Lsn,
1294 226785 : who_is_waiting: WaitLsnWaiter<'_>,
1295 226785 : ctx: &RequestContext, /* Prepare for use by cancellation */
1296 226785 : ) -> Result<(), WaitLsnError> {
1297 226785 : let state = self.current_state();
1298 226785 : if self.cancel.is_cancelled() || matches!(state, TimelineState::Stopping) {
1299 0 : return Err(WaitLsnError::Shutdown);
1300 226785 : } else if !matches!(state, TimelineState::Active) {
1301 0 : return Err(WaitLsnError::BadState(state));
1302 226785 : }
1303 226785 :
1304 226785 : if cfg!(debug_assertions) {
1305 226785 : 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 226785 : _ => {}
1324 : }
1325 0 : }
1326 :
1327 226785 : let _timer = crate::metrics::WAIT_LSN_TIME.start_timer();
1328 226785 :
1329 226785 : match self
1330 226785 : .last_record_lsn
1331 226785 : .wait_for_timeout(lsn, self.conf.wait_lsn_timeout)
1332 0 : .await
1333 : {
1334 226785 : 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 226785 : }
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 37181 : .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 37181 : 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 227795 : pub(crate) fn current_state(&self) -> TimelineState {
1903 227795 : self.state.borrow().clone()
1904 227795 : }
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 226787 : pub(crate) async fn wait_to_become_active(
1927 226787 : &self,
1928 226787 : _ctx: &RequestContext, // Prepare for use by cancellation
1929 226787 : ) -> Result<(), TimelineState> {
1930 226787 : let mut receiver = self.state.subscribe();
1931 : loop {
1932 226787 : let current_state = receiver.borrow().clone();
1933 226787 : 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 226785 : 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 226787 : }
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: &AttachedTenantConf) {
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.tenant_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 :
2191 0 : self.remote_client.update_config(&new_conf.location);
2192 0 :
2193 0 : self.metrics
2194 0 : .evictions_with_low_residence_duration
2195 0 : .write()
2196 0 : .unwrap()
2197 0 : .change_threshold(
2198 0 : &tenant_id_str,
2199 0 : &shard_id_str,
2200 0 : &timeline_id_str,
2201 0 : new_threshold,
2202 0 : );
2203 0 : }
2204 0 : }
2205 :
2206 : /// Open a Timeline handle.
2207 : ///
2208 : /// Loads the metadata for the timeline into memory, but not the layer map.
2209 : #[allow(clippy::too_many_arguments)]
2210 418 : pub(super) fn new(
2211 418 : conf: &'static PageServerConf,
2212 418 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
2213 418 : metadata: &TimelineMetadata,
2214 418 : ancestor: Option<Arc<Timeline>>,
2215 418 : timeline_id: TimelineId,
2216 418 : tenant_shard_id: TenantShardId,
2217 418 : generation: Generation,
2218 418 : shard_identity: ShardIdentity,
2219 418 : walredo_mgr: Option<Arc<super::WalRedoManager>>,
2220 418 : resources: TimelineResources,
2221 418 : pg_version: u32,
2222 418 : state: TimelineState,
2223 418 : attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
2224 418 : create_idempotency: crate::tenant::CreateTimelineIdempotency,
2225 418 : cancel: CancellationToken,
2226 418 : ) -> Arc<Self> {
2227 418 : let disk_consistent_lsn = metadata.disk_consistent_lsn();
2228 418 : let (state, _) = watch::channel(state);
2229 418 :
2230 418 : let (layer_flush_start_tx, _) = tokio::sync::watch::channel((0, disk_consistent_lsn));
2231 418 : let (layer_flush_done_tx, _) = tokio::sync::watch::channel((0, Ok(())));
2232 418 :
2233 418 : let evictions_low_residence_duration_metric_threshold = {
2234 418 : let loaded_tenant_conf = tenant_conf.load();
2235 418 : Self::get_evictions_low_residence_duration_metric_threshold(
2236 418 : &loaded_tenant_conf.tenant_conf,
2237 418 : &conf.default_tenant_conf,
2238 418 : )
2239 : };
2240 :
2241 418 : if let Some(ancestor) = &ancestor {
2242 230 : let mut ancestor_gc_info = ancestor.gc_info.write().unwrap();
2243 230 : // If we construct an explicit timeline object, it's obviously not offloaded
2244 230 : let is_offloaded = MaybeOffloaded::No;
2245 230 : ancestor_gc_info.insert_child(timeline_id, metadata.ancestor_lsn(), is_offloaded);
2246 230 : }
2247 :
2248 418 : Arc::new_cyclic(|myself| {
2249 418 : let metrics = TimelineMetrics::new(
2250 418 : &tenant_shard_id,
2251 418 : &timeline_id,
2252 418 : crate::metrics::EvictionsWithLowResidenceDurationBuilder::new(
2253 418 : "mtime",
2254 418 : evictions_low_residence_duration_metric_threshold,
2255 418 : ),
2256 418 : );
2257 418 : let aux_file_metrics = metrics.aux_file_size_gauge.clone();
2258 :
2259 418 : let mut result = Timeline {
2260 418 : conf,
2261 418 : tenant_conf,
2262 418 : myself: myself.clone(),
2263 418 : timeline_id,
2264 418 : tenant_shard_id,
2265 418 : generation,
2266 418 : shard_identity,
2267 418 : pg_version,
2268 418 : layers: Default::default(),
2269 418 :
2270 418 : walredo_mgr,
2271 418 : walreceiver: Mutex::new(None),
2272 418 :
2273 418 : remote_client: Arc::new(resources.remote_client),
2274 418 :
2275 418 : // initialize in-memory 'last_record_lsn' from 'disk_consistent_lsn'.
2276 418 : last_record_lsn: SeqWait::new(RecordLsn {
2277 418 : last: disk_consistent_lsn,
2278 418 : prev: metadata.prev_record_lsn().unwrap_or(Lsn(0)),
2279 418 : }),
2280 418 : disk_consistent_lsn: AtomicLsn::new(disk_consistent_lsn.0),
2281 418 :
2282 418 : last_freeze_at: AtomicLsn::new(disk_consistent_lsn.0),
2283 418 : last_freeze_ts: RwLock::new(Instant::now()),
2284 418 :
2285 418 : loaded_at: (disk_consistent_lsn, SystemTime::now()),
2286 418 :
2287 418 : ancestor_timeline: ancestor,
2288 418 : ancestor_lsn: metadata.ancestor_lsn(),
2289 418 :
2290 418 : metrics,
2291 418 :
2292 418 : query_metrics: crate::metrics::SmgrQueryTimePerTimeline::new(
2293 418 : &tenant_shard_id,
2294 418 : &timeline_id,
2295 418 : ),
2296 418 :
2297 2926 : directory_metrics: array::from_fn(|_| AtomicU64::new(0)),
2298 418 :
2299 418 : flush_loop_state: Mutex::new(FlushLoopState::NotStarted),
2300 418 :
2301 418 : layer_flush_start_tx,
2302 418 : layer_flush_done_tx,
2303 418 :
2304 418 : write_lock: tokio::sync::Mutex::new(None),
2305 418 :
2306 418 : gc_info: std::sync::RwLock::new(GcInfo::default()),
2307 418 :
2308 418 : latest_gc_cutoff_lsn: Rcu::new(metadata.latest_gc_cutoff_lsn()),
2309 418 : initdb_lsn: metadata.initdb_lsn(),
2310 418 :
2311 418 : current_logical_size: if disk_consistent_lsn.is_valid() {
2312 : // we're creating timeline data with some layer files existing locally,
2313 : // need to recalculate timeline's logical size based on data in the layers.
2314 234 : LogicalSize::deferred_initial(disk_consistent_lsn)
2315 : } else {
2316 : // we're creating timeline data without any layers existing locally,
2317 : // initial logical size is 0.
2318 184 : LogicalSize::empty_initial()
2319 : },
2320 418 : partitioning: tokio::sync::Mutex::new((
2321 418 : (KeyPartitioning::new(), KeyPartitioning::new().into_sparse()),
2322 418 : Lsn(0),
2323 418 : )),
2324 418 : repartition_threshold: 0,
2325 418 : last_image_layer_creation_check_at: AtomicLsn::new(0),
2326 418 : last_image_layer_creation_check_instant: Mutex::new(None),
2327 418 :
2328 418 : last_received_wal: Mutex::new(None),
2329 418 : rel_size_cache: RwLock::new(RelSizeCache {
2330 418 : complete_as_of: disk_consistent_lsn,
2331 418 : map: HashMap::new(),
2332 418 : }),
2333 418 :
2334 418 : download_all_remote_layers_task_info: RwLock::new(None),
2335 418 :
2336 418 : state,
2337 418 :
2338 418 : eviction_task_timeline_state: tokio::sync::Mutex::new(
2339 418 : EvictionTaskTimelineState::default(),
2340 418 : ),
2341 418 : delete_progress: TimelineDeleteProgress::default(),
2342 418 :
2343 418 : cancel,
2344 418 : gate: Gate::default(),
2345 418 :
2346 418 : compaction_lock: tokio::sync::Mutex::default(),
2347 418 : gc_lock: tokio::sync::Mutex::default(),
2348 418 :
2349 418 : standby_horizon: AtomicLsn::new(0),
2350 418 :
2351 418 : timeline_get_throttle: resources.timeline_get_throttle,
2352 418 :
2353 418 : aux_file_size_estimator: AuxFileSizeEstimator::new(aux_file_metrics),
2354 418 :
2355 418 : #[cfg(test)]
2356 418 : extra_test_dense_keyspace: ArcSwap::new(Arc::new(KeySpace::default())),
2357 418 :
2358 418 : l0_flush_global_state: resources.l0_flush_global_state,
2359 418 :
2360 418 : handles: Default::default(),
2361 418 :
2362 418 : attach_wal_lag_cooldown,
2363 418 :
2364 418 : create_idempotency,
2365 418 : };
2366 418 :
2367 418 : result.repartition_threshold =
2368 418 : result.get_checkpoint_distance() / REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE;
2369 418 :
2370 418 : result
2371 418 : .metrics
2372 418 : .last_record_gauge
2373 418 : .set(disk_consistent_lsn.0 as i64);
2374 418 : result
2375 418 : })
2376 418 : }
2377 :
2378 588 : pub(super) fn maybe_spawn_flush_loop(self: &Arc<Self>) {
2379 588 : let Ok(guard) = self.gate.enter() else {
2380 0 : info!("cannot start flush loop when the timeline gate has already been closed");
2381 0 : return;
2382 : };
2383 588 : let mut flush_loop_state = self.flush_loop_state.lock().unwrap();
2384 588 : match *flush_loop_state {
2385 412 : FlushLoopState::NotStarted => (),
2386 : FlushLoopState::Running { .. } => {
2387 176 : info!(
2388 0 : "skipping attempt to start flush_loop twice {}/{}",
2389 0 : self.tenant_shard_id, self.timeline_id
2390 : );
2391 176 : return;
2392 : }
2393 : FlushLoopState::Exited => {
2394 0 : warn!(
2395 0 : "ignoring attempt to restart exited flush_loop {}/{}",
2396 0 : self.tenant_shard_id, self.timeline_id
2397 : );
2398 0 : return;
2399 : }
2400 : }
2401 :
2402 412 : let layer_flush_start_rx = self.layer_flush_start_tx.subscribe();
2403 412 : let self_clone = Arc::clone(self);
2404 412 :
2405 412 : debug!("spawning flush loop");
2406 412 : *flush_loop_state = FlushLoopState::Running {
2407 412 : #[cfg(test)]
2408 412 : expect_initdb_optimization: false,
2409 412 : #[cfg(test)]
2410 412 : initdb_optimization_count: 0,
2411 412 : };
2412 412 : task_mgr::spawn(
2413 412 : task_mgr::BACKGROUND_RUNTIME.handle(),
2414 412 : task_mgr::TaskKind::LayerFlushTask,
2415 412 : self.tenant_shard_id,
2416 412 : Some(self.timeline_id),
2417 412 : "layer flush task",
2418 412 : async move {
2419 412 : let _guard = guard;
2420 412 : let background_ctx = RequestContext::todo_child(TaskKind::LayerFlushTask, DownloadBehavior::Error);
2421 18046 : self_clone.flush_loop(layer_flush_start_rx, &background_ctx).await;
2422 10 : let mut flush_loop_state = self_clone.flush_loop_state.lock().unwrap();
2423 10 : assert!(matches!(*flush_loop_state, FlushLoopState::Running{..}));
2424 10 : *flush_loop_state = FlushLoopState::Exited;
2425 10 : Ok(())
2426 10 : }
2427 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))
2428 : );
2429 588 : }
2430 :
2431 : /// Creates and starts the wal receiver.
2432 : ///
2433 : /// This function is expected to be called at most once per Timeline's lifecycle
2434 : /// when the timeline is activated.
2435 0 : fn launch_wal_receiver(
2436 0 : self: &Arc<Self>,
2437 0 : ctx: &RequestContext,
2438 0 : broker_client: BrokerClientChannel,
2439 0 : ) {
2440 0 : info!(
2441 0 : "launching WAL receiver for timeline {} of tenant {}",
2442 0 : self.timeline_id, self.tenant_shard_id
2443 : );
2444 :
2445 0 : let tenant_conf = self.tenant_conf.load();
2446 0 : let wal_connect_timeout = tenant_conf
2447 0 : .tenant_conf
2448 0 : .walreceiver_connect_timeout
2449 0 : .unwrap_or(self.conf.default_tenant_conf.walreceiver_connect_timeout);
2450 0 : let lagging_wal_timeout = tenant_conf
2451 0 : .tenant_conf
2452 0 : .lagging_wal_timeout
2453 0 : .unwrap_or(self.conf.default_tenant_conf.lagging_wal_timeout);
2454 0 : let max_lsn_wal_lag = tenant_conf
2455 0 : .tenant_conf
2456 0 : .max_lsn_wal_lag
2457 0 : .unwrap_or(self.conf.default_tenant_conf.max_lsn_wal_lag);
2458 0 :
2459 0 : let mut guard = self.walreceiver.lock().unwrap();
2460 0 : assert!(
2461 0 : guard.is_none(),
2462 0 : "multiple launches / re-launches of WAL receiver are not supported"
2463 : );
2464 0 : *guard = Some(WalReceiver::start(
2465 0 : Arc::clone(self),
2466 0 : WalReceiverConf {
2467 0 : wal_connect_timeout,
2468 0 : lagging_wal_timeout,
2469 0 : max_lsn_wal_lag,
2470 0 : auth_token: crate::config::SAFEKEEPER_AUTH_TOKEN.get().cloned(),
2471 0 : availability_zone: self.conf.availability_zone.clone(),
2472 0 : ingest_batch_size: self.conf.ingest_batch_size,
2473 0 : },
2474 0 : broker_client,
2475 0 : ctx,
2476 0 : ));
2477 0 : }
2478 :
2479 : /// Initialize with an empty layer map. Used when creating a new timeline.
2480 412 : pub(super) fn init_empty_layer_map(&self, start_lsn: Lsn) {
2481 412 : let mut layers = self.layers.try_write().expect(
2482 412 : "in the context where we call this function, no other task has access to the object",
2483 412 : );
2484 412 : layers
2485 412 : .open_mut()
2486 412 : .expect("in this context the LayerManager must still be open")
2487 412 : .initialize_empty(Lsn(start_lsn.0));
2488 412 : }
2489 :
2490 : /// Scan the timeline directory, cleanup, populate the layer map, and schedule uploads for local-only
2491 : /// files.
2492 6 : pub(super) async fn load_layer_map(
2493 6 : &self,
2494 6 : disk_consistent_lsn: Lsn,
2495 6 : index_part: IndexPart,
2496 6 : ) -> anyhow::Result<()> {
2497 : use init::{Decision::*, Discovered, DismissedLayer};
2498 : use LayerName::*;
2499 :
2500 6 : let mut guard = self.layers.write().await;
2501 :
2502 6 : let timer = self.metrics.load_layer_map_histo.start_timer();
2503 6 :
2504 6 : // Scan timeline directory and create ImageLayerName and DeltaFilename
2505 6 : // structs representing all files on disk
2506 6 : let timeline_path = self
2507 6 : .conf
2508 6 : .timeline_path(&self.tenant_shard_id, &self.timeline_id);
2509 6 : let conf = self.conf;
2510 6 : let span = tracing::Span::current();
2511 6 :
2512 6 : // Copy to move into the task we're about to spawn
2513 6 : let this = self.myself.upgrade().expect("&self method holds the arc");
2514 :
2515 6 : let (loaded_layers, needs_cleanup, total_physical_size) = tokio::task::spawn_blocking({
2516 6 : move || {
2517 6 : let _g = span.entered();
2518 6 : let discovered = init::scan_timeline_dir(&timeline_path)?;
2519 6 : let mut discovered_layers = Vec::with_capacity(discovered.len());
2520 6 : let mut unrecognized_files = Vec::new();
2521 6 :
2522 6 : let mut path = timeline_path;
2523 :
2524 22 : for discovered in discovered {
2525 16 : let (name, kind) = match discovered {
2526 16 : Discovered::Layer(layer_file_name, local_metadata) => {
2527 16 : discovered_layers.push((layer_file_name, local_metadata));
2528 16 : continue;
2529 : }
2530 0 : Discovered::IgnoredBackup(path) => {
2531 0 : std::fs::remove_file(path)
2532 0 : .or_else(fs_ext::ignore_not_found)
2533 0 : .fatal_err("Removing .old file");
2534 0 : continue;
2535 : }
2536 0 : Discovered::Unknown(file_name) => {
2537 0 : // we will later error if there are any
2538 0 : unrecognized_files.push(file_name);
2539 0 : continue;
2540 : }
2541 0 : Discovered::Ephemeral(name) => (name, "old ephemeral file"),
2542 0 : Discovered::Temporary(name) => (name, "temporary timeline file"),
2543 0 : Discovered::TemporaryDownload(name) => (name, "temporary download"),
2544 : };
2545 0 : path.push(Utf8Path::new(&name));
2546 0 : init::cleanup(&path, kind)?;
2547 0 : path.pop();
2548 : }
2549 :
2550 6 : if !unrecognized_files.is_empty() {
2551 : // assume that if there are any there are many many.
2552 0 : let n = unrecognized_files.len();
2553 0 : let first = &unrecognized_files[..n.min(10)];
2554 0 : anyhow::bail!(
2555 0 : "unrecognized files in timeline dir (total {n}), first 10: {first:?}"
2556 0 : );
2557 6 : }
2558 6 :
2559 6 : let decided = init::reconcile(discovered_layers, &index_part, disk_consistent_lsn);
2560 6 :
2561 6 : let mut loaded_layers = Vec::new();
2562 6 : let mut needs_cleanup = Vec::new();
2563 6 : let mut total_physical_size = 0;
2564 :
2565 22 : for (name, decision) in decided {
2566 16 : let decision = match decision {
2567 16 : Ok(decision) => decision,
2568 0 : Err(DismissedLayer::Future { local }) => {
2569 0 : if let Some(local) = local {
2570 0 : init::cleanup_future_layer(
2571 0 : &local.local_path,
2572 0 : &name,
2573 0 : disk_consistent_lsn,
2574 0 : )?;
2575 0 : }
2576 0 : needs_cleanup.push(name);
2577 0 : continue;
2578 : }
2579 0 : Err(DismissedLayer::LocalOnly(local)) => {
2580 0 : init::cleanup_local_only_file(&name, &local)?;
2581 : // this file never existed remotely, we will have to do rework
2582 0 : continue;
2583 : }
2584 0 : Err(DismissedLayer::BadMetadata(local)) => {
2585 0 : init::cleanup_local_file_for_remote(&local)?;
2586 : // this file never existed remotely, we will have to do rework
2587 0 : continue;
2588 : }
2589 : };
2590 :
2591 16 : match &name {
2592 12 : Delta(d) => assert!(d.lsn_range.end <= disk_consistent_lsn + 1),
2593 4 : Image(i) => assert!(i.lsn <= disk_consistent_lsn),
2594 : }
2595 :
2596 16 : tracing::debug!(layer=%name, ?decision, "applied");
2597 :
2598 16 : let layer = match decision {
2599 16 : Resident { local, remote } => {
2600 16 : total_physical_size += local.file_size;
2601 16 : Layer::for_resident(conf, &this, local.local_path, name, remote)
2602 16 : .drop_eviction_guard()
2603 : }
2604 0 : Evicted(remote) => Layer::for_evicted(conf, &this, name, remote),
2605 : };
2606 :
2607 16 : loaded_layers.push(layer);
2608 : }
2609 6 : Ok((loaded_layers, needs_cleanup, total_physical_size))
2610 6 : }
2611 6 : })
2612 1 : .await
2613 6 : .map_err(anyhow::Error::new)
2614 6 : .and_then(|x| x)?;
2615 :
2616 6 : let num_layers = loaded_layers.len();
2617 6 :
2618 6 : guard
2619 6 : .open_mut()
2620 6 : .expect("layermanager must be open during init")
2621 6 : .initialize_local_layers(loaded_layers, disk_consistent_lsn + 1);
2622 6 :
2623 6 : self.remote_client
2624 6 : .schedule_layer_file_deletion(&needs_cleanup)?;
2625 6 : self.remote_client
2626 6 : .schedule_index_upload_for_file_changes()?;
2627 : // This barrier orders above DELETEs before any later operations.
2628 : // This is critical because code executing after the barrier might
2629 : // create again objects with the same key that we just scheduled for deletion.
2630 : // For example, if we just scheduled deletion of an image layer "from the future",
2631 : // later compaction might run again and re-create the same image layer.
2632 : // "from the future" here means an image layer whose LSN is > IndexPart::disk_consistent_lsn.
2633 : // "same" here means same key range and LSN.
2634 : //
2635 : // Without a barrier between above DELETEs and the re-creation's PUTs,
2636 : // the upload queue may execute the PUT first, then the DELETE.
2637 : // In our example, we will end up with an IndexPart referencing a non-existent object.
2638 : //
2639 : // 1. a future image layer is created and uploaded
2640 : // 2. ps restart
2641 : // 3. the future layer from (1) is deleted during load layer map
2642 : // 4. image layer is re-created and uploaded
2643 : // 5. deletion queue would like to delete (1) but actually deletes (4)
2644 : // 6. delete by name works as expected, but it now deletes the wrong (later) version
2645 : //
2646 : // See https://github.com/neondatabase/neon/issues/5878
2647 : //
2648 : // NB: generation numbers naturally protect against this because they disambiguate
2649 : // (1) and (4)
2650 6 : self.remote_client.schedule_barrier()?;
2651 : // Tenant::create_timeline will wait for these uploads to happen before returning, or
2652 : // on retry.
2653 :
2654 : // Now that we have the full layer map, we may calculate the visibility of layers within it (a global scan)
2655 6 : drop(guard); // drop write lock, update_layer_visibility will take a read lock.
2656 6 : self.update_layer_visibility().await?;
2657 :
2658 6 : info!(
2659 0 : "loaded layer map with {} layers at {}, total physical size: {}",
2660 : num_layers, disk_consistent_lsn, total_physical_size
2661 : );
2662 :
2663 6 : timer.stop_and_record();
2664 6 : Ok(())
2665 6 : }
2666 :
2667 : /// Retrieve current logical size of the timeline.
2668 : ///
2669 : /// The size could be lagging behind the actual number, in case
2670 : /// the initial size calculation has not been run (gets triggered on the first size access).
2671 : ///
2672 : /// return size and boolean flag that shows if the size is exact
2673 0 : pub(crate) fn get_current_logical_size(
2674 0 : self: &Arc<Self>,
2675 0 : priority: GetLogicalSizePriority,
2676 0 : ctx: &RequestContext,
2677 0 : ) -> logical_size::CurrentLogicalSize {
2678 0 : if !self.tenant_shard_id.is_shard_zero() {
2679 : // Logical size is only accurately maintained on shard zero: when called elsewhere, for example
2680 : // when HTTP API is serving a GET for timeline zero, return zero
2681 0 : return logical_size::CurrentLogicalSize::Approximate(logical_size::Approximate::zero());
2682 0 : }
2683 0 :
2684 0 : let current_size = self.current_logical_size.current_size();
2685 0 : debug!("Current size: {current_size:?}");
2686 :
2687 0 : match (current_size.accuracy(), priority) {
2688 0 : (logical_size::Accuracy::Exact, _) => (), // nothing to do
2689 0 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::Background) => {
2690 0 : // background task will eventually deliver an exact value, we're in no rush
2691 0 : }
2692 : (logical_size::Accuracy::Approximate, GetLogicalSizePriority::User) => {
2693 : // background task is not ready, but user is asking for it now;
2694 : // => make the background task skip the line
2695 : // (The alternative would be to calculate the size here, but,
2696 : // it can actually take a long time if the user has a lot of rels.
2697 : // And we'll inevitable need it again; So, let the background task do the work.)
2698 0 : match self
2699 0 : .current_logical_size
2700 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
2701 0 : .get()
2702 : {
2703 0 : Some(cancel) => cancel.cancel(),
2704 : None => {
2705 0 : let state = self.current_state();
2706 0 : if matches!(
2707 0 : state,
2708 : TimelineState::Broken { .. } | TimelineState::Stopping
2709 0 : ) {
2710 0 :
2711 0 : // Can happen when timeline detail endpoint is used when deletion is ongoing (or its broken).
2712 0 : // Don't make noise.
2713 0 : } else {
2714 0 : warn!("unexpected: cancel_wait_for_background_loop_concurrency_limit_semaphore not set, priority-boosting of logical size calculation will not work");
2715 0 : debug_assert!(false);
2716 : }
2717 : }
2718 : };
2719 : }
2720 : }
2721 :
2722 0 : if let CurrentLogicalSize::Approximate(_) = ¤t_size {
2723 0 : if ctx.task_kind() == TaskKind::WalReceiverConnectionHandler {
2724 0 : let first = self
2725 0 : .current_logical_size
2726 0 : .did_return_approximate_to_walreceiver
2727 0 : .compare_exchange(
2728 0 : false,
2729 0 : true,
2730 0 : AtomicOrdering::Relaxed,
2731 0 : AtomicOrdering::Relaxed,
2732 0 : )
2733 0 : .is_ok();
2734 0 : if first {
2735 0 : crate::metrics::initial_logical_size::TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE.inc();
2736 0 : }
2737 0 : }
2738 0 : }
2739 :
2740 0 : current_size
2741 0 : }
2742 :
2743 0 : fn spawn_initial_logical_size_computation_task(self: &Arc<Self>, ctx: &RequestContext) {
2744 0 : let Some(initial_part_end) = self.current_logical_size.initial_part_end else {
2745 : // nothing to do for freshly created timelines;
2746 0 : assert_eq!(
2747 0 : self.current_logical_size.current_size().accuracy(),
2748 0 : logical_size::Accuracy::Exact,
2749 0 : );
2750 0 : self.current_logical_size.initialized.add_permits(1);
2751 0 : return;
2752 : };
2753 :
2754 0 : let cancel_wait_for_background_loop_concurrency_limit_semaphore = CancellationToken::new();
2755 0 : let token = cancel_wait_for_background_loop_concurrency_limit_semaphore.clone();
2756 0 : self.current_logical_size
2757 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore.set(token)
2758 0 : .expect("initial logical size calculation task must be spawned exactly once per Timeline object");
2759 0 :
2760 0 : let self_clone = Arc::clone(self);
2761 0 : let background_ctx = ctx.detached_child(
2762 0 : TaskKind::InitialLogicalSizeCalculation,
2763 0 : DownloadBehavior::Download,
2764 0 : );
2765 0 : task_mgr::spawn(
2766 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
2767 0 : task_mgr::TaskKind::InitialLogicalSizeCalculation,
2768 0 : self.tenant_shard_id,
2769 0 : Some(self.timeline_id),
2770 0 : "initial size calculation",
2771 : // NB: don't log errors here, task_mgr will do that.
2772 0 : async move {
2773 0 : let cancel = task_mgr::shutdown_token();
2774 0 : self_clone
2775 0 : .initial_logical_size_calculation_task(
2776 0 : initial_part_end,
2777 0 : cancel_wait_for_background_loop_concurrency_limit_semaphore,
2778 0 : cancel,
2779 0 : background_ctx,
2780 0 : )
2781 0 : .await;
2782 0 : Ok(())
2783 0 : }
2784 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)),
2785 : );
2786 0 : }
2787 :
2788 0 : async fn initial_logical_size_calculation_task(
2789 0 : self: Arc<Self>,
2790 0 : initial_part_end: Lsn,
2791 0 : skip_concurrency_limiter: CancellationToken,
2792 0 : cancel: CancellationToken,
2793 0 : background_ctx: RequestContext,
2794 0 : ) {
2795 0 : scopeguard::defer! {
2796 0 : // Irrespective of the outcome of this operation, we should unblock anyone waiting for it.
2797 0 : self.current_logical_size.initialized.add_permits(1);
2798 0 : }
2799 0 :
2800 0 : let try_once = |attempt: usize| {
2801 0 : let background_ctx = &background_ctx;
2802 0 : let self_ref = &self;
2803 0 : let skip_concurrency_limiter = &skip_concurrency_limiter;
2804 0 : async move {
2805 0 : let cancel = task_mgr::shutdown_token();
2806 0 : let wait_for_permit = super::tasks::concurrent_background_tasks_rate_limit_permit(
2807 0 : BackgroundLoopKind::InitialLogicalSizeCalculation,
2808 0 : background_ctx,
2809 0 : );
2810 :
2811 : use crate::metrics::initial_logical_size::StartCircumstances;
2812 0 : let (_maybe_permit, circumstances) = tokio::select! {
2813 0 : permit = wait_for_permit => {
2814 0 : (Some(permit), StartCircumstances::AfterBackgroundTasksRateLimit)
2815 : }
2816 0 : _ = self_ref.cancel.cancelled() => {
2817 0 : return Err(CalculateLogicalSizeError::Cancelled);
2818 : }
2819 0 : _ = cancel.cancelled() => {
2820 0 : return Err(CalculateLogicalSizeError::Cancelled);
2821 : },
2822 0 : () = skip_concurrency_limiter.cancelled() => {
2823 : // Some action that is part of a end user interaction requested logical size
2824 : // => break out of the rate limit
2825 : // TODO: ideally we'd not run on BackgroundRuntime but the requester's runtime;
2826 : // but then again what happens if they cancel; also, we should just be using
2827 : // one runtime across the entire process, so, let's leave this for now.
2828 0 : (None, StartCircumstances::SkippedConcurrencyLimiter)
2829 : }
2830 : };
2831 :
2832 0 : let metrics_guard = if attempt == 1 {
2833 0 : crate::metrics::initial_logical_size::START_CALCULATION.first(circumstances)
2834 : } else {
2835 0 : crate::metrics::initial_logical_size::START_CALCULATION.retry(circumstances)
2836 : };
2837 :
2838 0 : let calculated_size = self_ref
2839 0 : .logical_size_calculation_task(
2840 0 : initial_part_end,
2841 0 : LogicalSizeCalculationCause::Initial,
2842 0 : background_ctx,
2843 0 : )
2844 0 : .await?;
2845 :
2846 0 : self_ref
2847 0 : .trigger_aux_file_size_computation(initial_part_end, background_ctx)
2848 0 : .await?;
2849 :
2850 : // TODO: add aux file size to logical size
2851 :
2852 0 : Ok((calculated_size, metrics_guard))
2853 0 : }
2854 0 : };
2855 :
2856 0 : let retrying = async {
2857 0 : let mut attempt = 0;
2858 : loop {
2859 0 : attempt += 1;
2860 0 :
2861 0 : match try_once(attempt).await {
2862 0 : Ok(res) => return ControlFlow::Continue(res),
2863 0 : Err(CalculateLogicalSizeError::Cancelled) => return ControlFlow::Break(()),
2864 : Err(
2865 0 : e @ (CalculateLogicalSizeError::Decode(_)
2866 0 : | CalculateLogicalSizeError::PageRead(_)),
2867 0 : ) => {
2868 0 : warn!(attempt, "initial size calculation failed: {e:?}");
2869 : // exponential back-off doesn't make sense at these long intervals;
2870 : // use fixed retry interval with generous jitter instead
2871 0 : let sleep_duration = Duration::from_secs(
2872 0 : u64::try_from(
2873 0 : // 1hour base
2874 0 : (60_i64 * 60_i64)
2875 0 : // 10min jitter
2876 0 : + rand::thread_rng().gen_range(-10 * 60..10 * 60),
2877 0 : )
2878 0 : .expect("10min < 1hour"),
2879 0 : );
2880 0 : tokio::time::sleep(sleep_duration).await;
2881 : }
2882 : }
2883 : }
2884 0 : };
2885 :
2886 0 : let (calculated_size, metrics_guard) = tokio::select! {
2887 0 : res = retrying => {
2888 0 : match res {
2889 0 : ControlFlow::Continue(calculated_size) => calculated_size,
2890 0 : ControlFlow::Break(()) => return,
2891 : }
2892 : }
2893 0 : _ = cancel.cancelled() => {
2894 0 : return;
2895 : }
2896 : };
2897 :
2898 : // we cannot query current_logical_size.current_size() to know the current
2899 : // *negative* value, only truncated to u64.
2900 0 : let added = self
2901 0 : .current_logical_size
2902 0 : .size_added_after_initial
2903 0 : .load(AtomicOrdering::Relaxed);
2904 0 :
2905 0 : let sum = calculated_size.saturating_add_signed(added);
2906 0 :
2907 0 : // set the gauge value before it can be set in `update_current_logical_size`.
2908 0 : self.metrics.current_logical_size_gauge.set(sum);
2909 0 :
2910 0 : self.current_logical_size
2911 0 : .initial_logical_size
2912 0 : .set((calculated_size, metrics_guard.calculation_result_saved()))
2913 0 : .ok()
2914 0 : .expect("only this task sets it");
2915 0 : }
2916 :
2917 0 : pub(crate) fn spawn_ondemand_logical_size_calculation(
2918 0 : self: &Arc<Self>,
2919 0 : lsn: Lsn,
2920 0 : cause: LogicalSizeCalculationCause,
2921 0 : ctx: RequestContext,
2922 0 : ) -> oneshot::Receiver<Result<u64, CalculateLogicalSizeError>> {
2923 0 : let (sender, receiver) = oneshot::channel();
2924 0 : let self_clone = Arc::clone(self);
2925 0 : // XXX if our caller loses interest, i.e., ctx is cancelled,
2926 0 : // we should stop the size calculation work and return an error.
2927 0 : // That would require restructuring this function's API to
2928 0 : // return the result directly, instead of a Receiver for the result.
2929 0 : let ctx = ctx.detached_child(
2930 0 : TaskKind::OndemandLogicalSizeCalculation,
2931 0 : DownloadBehavior::Download,
2932 0 : );
2933 0 : task_mgr::spawn(
2934 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
2935 0 : task_mgr::TaskKind::OndemandLogicalSizeCalculation,
2936 0 : self.tenant_shard_id,
2937 0 : Some(self.timeline_id),
2938 0 : "ondemand logical size calculation",
2939 0 : async move {
2940 0 : let res = self_clone
2941 0 : .logical_size_calculation_task(lsn, cause, &ctx)
2942 0 : .await;
2943 0 : let _ = sender.send(res).ok();
2944 0 : Ok(()) // Receiver is responsible for handling errors
2945 0 : }
2946 0 : .in_current_span(),
2947 0 : );
2948 0 : receiver
2949 0 : }
2950 :
2951 : /// # Cancel-Safety
2952 : ///
2953 : /// This method is cancellation-safe.
2954 0 : #[instrument(skip_all)]
2955 : async fn logical_size_calculation_task(
2956 : self: &Arc<Self>,
2957 : lsn: Lsn,
2958 : cause: LogicalSizeCalculationCause,
2959 : ctx: &RequestContext,
2960 : ) -> Result<u64, CalculateLogicalSizeError> {
2961 : crate::span::debug_assert_current_span_has_tenant_and_timeline_id();
2962 : // We should never be calculating logical sizes on shard !=0, because these shards do not have
2963 : // accurate relation sizes, and they do not emit consumption metrics.
2964 : debug_assert!(self.tenant_shard_id.is_shard_zero());
2965 :
2966 : let guard = self
2967 : .gate
2968 : .enter()
2969 0 : .map_err(|_| CalculateLogicalSizeError::Cancelled)?;
2970 :
2971 : let self_calculation = Arc::clone(self);
2972 :
2973 0 : let mut calculation = pin!(async {
2974 0 : let ctx = ctx.attached_child();
2975 0 : self_calculation
2976 0 : .calculate_logical_size(lsn, cause, &guard, &ctx)
2977 0 : .await
2978 0 : });
2979 :
2980 : tokio::select! {
2981 : res = &mut calculation => { res }
2982 : _ = self.cancel.cancelled() => {
2983 : debug!("cancelling logical size calculation for timeline shutdown");
2984 : calculation.await
2985 : }
2986 : }
2987 : }
2988 :
2989 : /// Calculate the logical size of the database at the latest LSN.
2990 : ///
2991 : /// NOTE: counted incrementally, includes ancestors. This can be a slow operation,
2992 : /// especially if we need to download remote layers.
2993 : ///
2994 : /// # Cancel-Safety
2995 : ///
2996 : /// This method is cancellation-safe.
2997 0 : async fn calculate_logical_size(
2998 0 : &self,
2999 0 : up_to_lsn: Lsn,
3000 0 : cause: LogicalSizeCalculationCause,
3001 0 : _guard: &GateGuard,
3002 0 : ctx: &RequestContext,
3003 0 : ) -> Result<u64, CalculateLogicalSizeError> {
3004 0 : info!(
3005 0 : "Calculating logical size for timeline {} at {}",
3006 : self.timeline_id, up_to_lsn
3007 : );
3008 :
3009 0 : pausable_failpoint!("timeline-calculate-logical-size-pause");
3010 :
3011 : // See if we've already done the work for initial size calculation.
3012 : // This is a short-cut for timelines that are mostly unused.
3013 0 : if let Some(size) = self.current_logical_size.initialized_size(up_to_lsn) {
3014 0 : return Ok(size);
3015 0 : }
3016 0 : let storage_time_metrics = match cause {
3017 : LogicalSizeCalculationCause::Initial
3018 : | LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize
3019 0 : | LogicalSizeCalculationCause::TenantSizeHandler => &self.metrics.logical_size_histo,
3020 : LogicalSizeCalculationCause::EvictionTaskImitation => {
3021 0 : &self.metrics.imitate_logical_size_histo
3022 : }
3023 : };
3024 0 : let timer = storage_time_metrics.start_timer();
3025 0 : let logical_size = self
3026 0 : .get_current_logical_size_non_incremental(up_to_lsn, ctx)
3027 0 : .await?;
3028 0 : debug!("calculated logical size: {logical_size}");
3029 0 : timer.stop_and_record();
3030 0 : Ok(logical_size)
3031 0 : }
3032 :
3033 : /// Update current logical size, adding `delta' to the old value.
3034 270570 : fn update_current_logical_size(&self, delta: i64) {
3035 270570 : let logical_size = &self.current_logical_size;
3036 270570 : logical_size.increment_size(delta);
3037 270570 :
3038 270570 : // Also set the value in the prometheus gauge. Note that
3039 270570 : // there is a race condition here: if this is is called by two
3040 270570 : // threads concurrently, the prometheus gauge might be set to
3041 270570 : // one value while current_logical_size is set to the
3042 270570 : // other.
3043 270570 : match logical_size.current_size() {
3044 270570 : CurrentLogicalSize::Exact(ref new_current_size) => self
3045 270570 : .metrics
3046 270570 : .current_logical_size_gauge
3047 270570 : .set(new_current_size.into()),
3048 0 : CurrentLogicalSize::Approximate(_) => {
3049 0 : // don't update the gauge yet, this allows us not to update the gauge back and
3050 0 : // forth between the initial size calculation task.
3051 0 : }
3052 : }
3053 270570 : }
3054 :
3055 2834 : pub(crate) fn update_directory_entries_count(&self, kind: DirectoryKind, count: u64) {
3056 2834 : self.directory_metrics[kind.offset()].store(count, AtomicOrdering::Relaxed);
3057 2834 : let aux_metric =
3058 2834 : self.directory_metrics[DirectoryKind::AuxFiles.offset()].load(AtomicOrdering::Relaxed);
3059 2834 :
3060 2834 : let sum_of_entries = self
3061 2834 : .directory_metrics
3062 2834 : .iter()
3063 19838 : .map(|v| v.load(AtomicOrdering::Relaxed))
3064 2834 : .sum();
3065 : // Set a high general threshold and a lower threshold for the auxiliary files,
3066 : // as we can have large numbers of relations in the db directory.
3067 : const SUM_THRESHOLD: u64 = 5000;
3068 : const AUX_THRESHOLD: u64 = 1000;
3069 2834 : if sum_of_entries >= SUM_THRESHOLD || aux_metric >= AUX_THRESHOLD {
3070 0 : self.metrics
3071 0 : .directory_entries_count_gauge
3072 0 : .set(sum_of_entries);
3073 2834 : } else if let Some(metric) = Lazy::get(&self.metrics.directory_entries_count_gauge) {
3074 0 : metric.set(sum_of_entries);
3075 2834 : }
3076 2834 : }
3077 :
3078 0 : async fn find_layer(
3079 0 : &self,
3080 0 : layer_name: &LayerName,
3081 0 : ) -> Result<Option<Layer>, layer_manager::Shutdown> {
3082 0 : let guard = self.layers.read().await;
3083 0 : let layer = guard
3084 0 : .layer_map()?
3085 0 : .iter_historic_layers()
3086 0 : .find(|l| &l.layer_name() == layer_name)
3087 0 : .map(|found| guard.get_from_desc(&found));
3088 0 : Ok(layer)
3089 0 : }
3090 :
3091 : /// The timeline heatmap is a hint to secondary locations from the primary location,
3092 : /// indicating which layers are currently on-disk on the primary.
3093 : ///
3094 : /// None is returned if the Timeline is in a state where uploading a heatmap
3095 : /// doesn't make sense, such as shutting down or initializing. The caller
3096 : /// should treat this as a cue to simply skip doing any heatmap uploading
3097 : /// for this timeline.
3098 2 : pub(crate) async fn generate_heatmap(&self) -> Option<HeatMapTimeline> {
3099 2 : if !self.is_active() {
3100 0 : return None;
3101 2 : }
3102 :
3103 2 : let guard = self.layers.read().await;
3104 :
3105 10 : let resident = guard.likely_resident_layers().filter_map(|layer| {
3106 10 : match layer.visibility() {
3107 : LayerVisibilityHint::Visible => {
3108 : // Layer is visible to one or more read LSNs: elegible for inclusion in layer map
3109 8 : let last_activity_ts = layer.latest_activity();
3110 8 : Some((layer.layer_desc(), layer.metadata(), last_activity_ts))
3111 : }
3112 : LayerVisibilityHint::Covered => {
3113 : // Layer is resident but unlikely to be read: not elegible for inclusion in heatmap.
3114 2 : None
3115 : }
3116 : }
3117 10 : });
3118 2 :
3119 2 : let mut layers = resident.collect::<Vec<_>>();
3120 2 :
3121 2 : // Sort layers in order of which to download first. For a large set of layers to download, we
3122 2 : // want to prioritize those layers which are most likely to still be in the resident many minutes
3123 2 : // or hours later:
3124 2 : // - Download L0s last, because they churn the fastest: L0s on a fast-writing tenant might
3125 2 : // only exist for a few minutes before being compacted into L1s.
3126 2 : // - For L1 & image layers, download most recent LSNs first: the older the LSN, the sooner
3127 2 : // the layer is likely to be covered by an image layer during compaction.
3128 14 : layers.sort_by_key(|(desc, _meta, _atime)| {
3129 14 : std::cmp::Reverse((
3130 14 : !LayerMap::is_l0(&desc.key_range, desc.is_delta),
3131 14 : desc.lsn_range.end,
3132 14 : ))
3133 14 : });
3134 2 :
3135 2 : let layers = layers
3136 2 : .into_iter()
3137 8 : .map(|(desc, meta, atime)| HeatMapLayer::new(desc.layer_name(), meta, atime))
3138 2 : .collect();
3139 2 :
3140 2 : Some(HeatMapTimeline::new(self.timeline_id, layers))
3141 2 : }
3142 :
3143 : /// Returns true if the given lsn is or was an ancestor branchpoint.
3144 0 : pub(crate) fn is_ancestor_lsn(&self, lsn: Lsn) -> bool {
3145 0 : // upon timeline detach, we set the ancestor_lsn to Lsn::INVALID and the store the original
3146 0 : // branchpoint in the value in IndexPart::lineage
3147 0 : self.ancestor_lsn == lsn
3148 0 : || (self.ancestor_lsn == Lsn::INVALID
3149 0 : && self.remote_client.is_previous_ancestor_lsn(lsn))
3150 0 : }
3151 : }
3152 :
3153 : impl Timeline {
3154 : #[allow(clippy::doc_lazy_continuation)]
3155 : /// Get the data needed to reconstruct all keys in the provided keyspace
3156 : ///
3157 : /// The algorithm is as follows:
3158 : /// 1. While some keys are still not done and there's a timeline to visit:
3159 : /// 2. Visit the timeline (see [`Timeline::get_vectored_reconstruct_data_timeline`]:
3160 : /// 2.1: Build the fringe for the current keyspace
3161 : /// 2.2 Visit the newest layer from the fringe to collect all values for the range it
3162 : /// intersects
3163 : /// 2.3. Pop the timeline from the fringe
3164 : /// 2.4. If the fringe is empty, go back to 1
3165 626662 : async fn get_vectored_reconstruct_data(
3166 626662 : &self,
3167 626662 : mut keyspace: KeySpace,
3168 626662 : request_lsn: Lsn,
3169 626662 : reconstruct_state: &mut ValuesReconstructState,
3170 626662 : ctx: &RequestContext,
3171 626662 : ) -> Result<(), GetVectoredError> {
3172 626662 : let mut timeline_owned: Arc<Timeline>;
3173 626662 : let mut timeline = self;
3174 626662 :
3175 626662 : let mut cont_lsn = Lsn(request_lsn.0 + 1);
3176 :
3177 626660 : let missing_keyspace = loop {
3178 853447 : if self.cancel.is_cancelled() {
3179 0 : return Err(GetVectoredError::Cancelled);
3180 853447 : }
3181 :
3182 : let TimelineVisitOutcome {
3183 853447 : completed_keyspace: completed,
3184 853447 : image_covered_keyspace,
3185 853447 : } = Self::get_vectored_reconstruct_data_timeline(
3186 853447 : timeline,
3187 853447 : keyspace.clone(),
3188 853447 : cont_lsn,
3189 853447 : reconstruct_state,
3190 853447 : &self.cancel,
3191 853447 : ctx,
3192 853447 : )
3193 192289 : .await?;
3194 :
3195 853447 : keyspace.remove_overlapping_with(&completed);
3196 853447 :
3197 853447 : // Do not descend into the ancestor timeline for aux files.
3198 853447 : // We don't return a blanket [`GetVectoredError::MissingKey`] to avoid
3199 853447 : // stalling compaction.
3200 853447 : keyspace.remove_overlapping_with(&KeySpace {
3201 853447 : ranges: vec![NON_INHERITED_RANGE, NON_INHERITED_SPARSE_RANGE],
3202 853447 : });
3203 853447 :
3204 853447 : // Keyspace is fully retrieved
3205 853447 : if keyspace.is_empty() {
3206 626646 : break None;
3207 226801 : }
3208 :
3209 226801 : let Some(ancestor_timeline) = timeline.ancestor_timeline.as_ref() else {
3210 : // Not fully retrieved but no ancestor timeline.
3211 14 : break Some(keyspace);
3212 : };
3213 :
3214 : // Now we see if there are keys covered by the image layer but does not exist in the
3215 : // image layer, which means that the key does not exist.
3216 :
3217 : // The block below will stop the vectored search if any of the keys encountered an image layer
3218 : // which did not contain a snapshot for said key. Since we have already removed all completed
3219 : // keys from `keyspace`, we expect there to be no overlap between it and the image covered key
3220 : // space. If that's not the case, we had at least one key encounter a gap in the image layer
3221 : // and stop the search as a result of that.
3222 226787 : let removed = keyspace.remove_overlapping_with(&image_covered_keyspace);
3223 226787 : if !removed.is_empty() {
3224 0 : break Some(removed);
3225 226787 : }
3226 226787 : // If we reached this point, `remove_overlapping_with` should not have made any change to the
3227 226787 : // keyspace.
3228 226787 :
3229 226787 : // Take the min to avoid reconstructing a page with data newer than request Lsn.
3230 226787 : cont_lsn = std::cmp::min(Lsn(request_lsn.0 + 1), Lsn(timeline.ancestor_lsn.0 + 1));
3231 226787 : timeline_owned = timeline
3232 226787 : .get_ready_ancestor_timeline(ancestor_timeline, ctx)
3233 2 : .await?;
3234 226785 : timeline = &*timeline_owned;
3235 : };
3236 :
3237 626660 : if let Some(missing_keyspace) = missing_keyspace {
3238 14 : return Err(GetVectoredError::MissingKey(MissingKeyError {
3239 14 : key: missing_keyspace.start().unwrap(), /* better if we can store the full keyspace */
3240 14 : shard: self
3241 14 : .shard_identity
3242 14 : .get_shard_number(&missing_keyspace.start().unwrap()),
3243 14 : cont_lsn,
3244 14 : request_lsn,
3245 14 : ancestor_lsn: Some(timeline.ancestor_lsn),
3246 14 : backtrace: None,
3247 14 : }));
3248 626646 : }
3249 626646 :
3250 626646 : Ok(())
3251 626662 : }
3252 :
3253 : /// Collect the reconstruct data for a keyspace from the specified timeline.
3254 : ///
3255 : /// Maintain a fringe [`LayerFringe`] which tracks all the layers that intersect
3256 : /// the current keyspace. The current keyspace of the search at any given timeline
3257 : /// is the original keyspace minus all the keys that have been completed minus
3258 : /// any keys for which we couldn't find an intersecting layer. It's not tracked explicitly,
3259 : /// but if you merge all the keyspaces in the fringe, you get the "current keyspace".
3260 : ///
3261 : /// This is basically a depth-first search visitor implementation where a vertex
3262 : /// is the (layer, lsn range, key space) tuple. The fringe acts as the stack.
3263 : ///
3264 : /// At each iteration pop the top of the fringe (the layer with the highest Lsn)
3265 : /// and get all the required reconstruct data from the layer in one go.
3266 : ///
3267 : /// Returns the completed keyspace and the keyspaces with image coverage. The caller
3268 : /// decides how to deal with these two keyspaces.
3269 853447 : async fn get_vectored_reconstruct_data_timeline(
3270 853447 : timeline: &Timeline,
3271 853447 : keyspace: KeySpace,
3272 853447 : mut cont_lsn: Lsn,
3273 853447 : reconstruct_state: &mut ValuesReconstructState,
3274 853447 : cancel: &CancellationToken,
3275 853447 : ctx: &RequestContext,
3276 853447 : ) -> Result<TimelineVisitOutcome, GetVectoredError> {
3277 853447 : let mut unmapped_keyspace = keyspace.clone();
3278 853447 : let mut fringe = LayerFringe::new();
3279 853447 :
3280 853447 : let mut completed_keyspace = KeySpace::default();
3281 853447 : let mut image_covered_keyspace = KeySpaceRandomAccum::new();
3282 :
3283 : loop {
3284 1698427 : if cancel.is_cancelled() {
3285 0 : return Err(GetVectoredError::Cancelled);
3286 1698427 : }
3287 1698427 :
3288 1698427 : let (keys_done_last_step, keys_with_image_coverage) =
3289 1698427 : reconstruct_state.consume_done_keys();
3290 1698427 : unmapped_keyspace.remove_overlapping_with(&keys_done_last_step);
3291 1698427 : completed_keyspace.merge(&keys_done_last_step);
3292 1698427 : if let Some(keys_with_image_coverage) = keys_with_image_coverage {
3293 21808 : unmapped_keyspace
3294 21808 : .remove_overlapping_with(&KeySpace::single(keys_with_image_coverage.clone()));
3295 21808 : image_covered_keyspace.add_range(keys_with_image_coverage);
3296 1676619 : }
3297 :
3298 : // Do not descent any further if the last layer we visited
3299 : // completed all keys in the keyspace it inspected. This is not
3300 : // required for correctness, but avoids visiting extra layers
3301 : // which turns out to be a perf bottleneck in some cases.
3302 1698427 : if !unmapped_keyspace.is_empty() {
3303 1074025 : let guard = timeline.layers.read().await;
3304 1074025 : let layers = guard.layer_map()?;
3305 :
3306 1074025 : let in_memory_layer = layers.find_in_memory_layer(|l| {
3307 914614 : let start_lsn = l.get_lsn_range().start;
3308 914614 : cont_lsn > start_lsn
3309 1074025 : });
3310 1074025 :
3311 1074025 : match in_memory_layer {
3312 606411 : Some(l) => {
3313 606411 : let lsn_range = l.get_lsn_range().start..cont_lsn;
3314 606411 : fringe.update(
3315 606411 : ReadableLayer::InMemoryLayer(l),
3316 606411 : unmapped_keyspace.clone(),
3317 606411 : lsn_range,
3318 606411 : );
3319 606411 : }
3320 : None => {
3321 467636 : for range in unmapped_keyspace.ranges.iter() {
3322 467636 : let results = layers.range_search(range.clone(), cont_lsn);
3323 467636 :
3324 467636 : results
3325 467636 : .found
3326 467636 : .into_iter()
3327 467636 : .map(|(SearchResult { layer, lsn_floor }, keyspace_accum)| {
3328 238583 : (
3329 238583 : ReadableLayer::PersistentLayer(guard.get_from_desc(&layer)),
3330 238583 : keyspace_accum.to_keyspace(),
3331 238583 : lsn_floor..cont_lsn,
3332 238583 : )
3333 467636 : })
3334 467636 : .for_each(|(layer, keyspace, lsn_range)| {
3335 238583 : fringe.update(layer, keyspace, lsn_range)
3336 467636 : });
3337 467636 : }
3338 : }
3339 : }
3340 :
3341 : // It's safe to drop the layer map lock after planning the next round of reads.
3342 : // The fringe keeps readable handles for the layers which are safe to read even
3343 : // if layers were compacted or flushed.
3344 : //
3345 : // The more interesting consideration is: "Why is the read algorithm still correct
3346 : // if the layer map changes while it is operating?". Doing a vectored read on a
3347 : // timeline boils down to pushing an imaginary lsn boundary downwards for each range
3348 : // covered by the read. The layer map tells us how to move the lsn downwards for a
3349 : // range at *a particular point in time*. It is fine for the answer to be different
3350 : // at two different time points.
3351 1074025 : drop(guard);
3352 624402 : }
3353 :
3354 1698427 : if let Some((layer_to_read, keyspace_to_read, lsn_range)) = fringe.next_layer() {
3355 844980 : let next_cont_lsn = lsn_range.start;
3356 844980 : layer_to_read
3357 844980 : .get_values_reconstruct_data(
3358 844980 : keyspace_to_read.clone(),
3359 844980 : lsn_range,
3360 844980 : reconstruct_state,
3361 844980 : ctx,
3362 844980 : )
3363 183059 : .await?;
3364 :
3365 844980 : unmapped_keyspace = keyspace_to_read;
3366 844980 : cont_lsn = next_cont_lsn;
3367 844980 :
3368 844980 : reconstruct_state.on_layer_visited(&layer_to_read);
3369 : } else {
3370 853447 : break;
3371 853447 : }
3372 853447 : }
3373 853447 :
3374 853447 : Ok(TimelineVisitOutcome {
3375 853447 : completed_keyspace,
3376 853447 : image_covered_keyspace: image_covered_keyspace.consume_keyspace(),
3377 853447 : })
3378 853447 : }
3379 :
3380 226787 : async fn get_ready_ancestor_timeline(
3381 226787 : &self,
3382 226787 : ancestor: &Arc<Timeline>,
3383 226787 : ctx: &RequestContext,
3384 226787 : ) -> Result<Arc<Timeline>, GetReadyAncestorError> {
3385 226787 : // It's possible that the ancestor timeline isn't active yet, or
3386 226787 : // is active but hasn't yet caught up to the branch point. Wait
3387 226787 : // for it.
3388 226787 : //
3389 226787 : // This cannot happen while the pageserver is running normally,
3390 226787 : // because you cannot create a branch from a point that isn't
3391 226787 : // present in the pageserver yet. However, we don't wait for the
3392 226787 : // branch point to be uploaded to cloud storage before creating
3393 226787 : // a branch. I.e., the branch LSN need not be remote consistent
3394 226787 : // for the branching operation to succeed.
3395 226787 : //
3396 226787 : // Hence, if we try to load a tenant in such a state where
3397 226787 : // 1. the existence of the branch was persisted (in IndexPart and/or locally)
3398 226787 : // 2. but the ancestor state is behind branch_lsn because it was not yet persisted
3399 226787 : // then we will need to wait for the ancestor timeline to
3400 226787 : // re-stream WAL up to branch_lsn before we access it.
3401 226787 : //
3402 226787 : // How can a tenant get in such a state?
3403 226787 : // - ungraceful pageserver process exit
3404 226787 : // - detach+attach => this is a bug, https://github.com/neondatabase/neon/issues/4219
3405 226787 : //
3406 226787 : // NB: this could be avoided by requiring
3407 226787 : // branch_lsn >= remote_consistent_lsn
3408 226787 : // during branch creation.
3409 226787 : match ancestor.wait_to_become_active(ctx).await {
3410 226785 : Ok(()) => {}
3411 : Err(TimelineState::Stopping) => {
3412 : // If an ancestor is stopping, it means the tenant is stopping: handle this the same as if this timeline was stopping.
3413 0 : return Err(GetReadyAncestorError::Cancelled);
3414 : }
3415 2 : Err(state) => {
3416 2 : return Err(GetReadyAncestorError::BadState {
3417 2 : timeline_id: ancestor.timeline_id,
3418 2 : state,
3419 2 : });
3420 : }
3421 : }
3422 226785 : ancestor
3423 226785 : .wait_lsn(self.ancestor_lsn, WaitLsnWaiter::Timeline(self), ctx)
3424 0 : .await
3425 226785 : .map_err(|e| match e {
3426 0 : e @ WaitLsnError::Timeout(_) => GetReadyAncestorError::AncestorLsnTimeout(e),
3427 0 : WaitLsnError::Shutdown => GetReadyAncestorError::Cancelled,
3428 0 : WaitLsnError::BadState(state) => GetReadyAncestorError::BadState {
3429 0 : timeline_id: ancestor.timeline_id,
3430 0 : state,
3431 0 : },
3432 226785 : })?;
3433 :
3434 226785 : Ok(ancestor.clone())
3435 226787 : }
3436 :
3437 151304 : pub(crate) fn get_shard_identity(&self) -> &ShardIdentity {
3438 151304 : &self.shard_identity
3439 151304 : }
3440 :
3441 : #[inline(always)]
3442 0 : pub(crate) fn shard_timeline_id(&self) -> ShardTimelineId {
3443 0 : ShardTimelineId {
3444 0 : shard_index: ShardIndex {
3445 0 : shard_number: self.shard_identity.number,
3446 0 : shard_count: self.shard_identity.count,
3447 0 : },
3448 0 : timeline_id: self.timeline_id,
3449 0 : }
3450 0 : }
3451 :
3452 : /// Returns a non-frozen open in-memory layer for ingestion.
3453 : ///
3454 : /// Takes a witness of timeline writer state lock being held, because it makes no sense to call
3455 : /// this function without holding the mutex.
3456 1268 : async fn get_layer_for_write(
3457 1268 : &self,
3458 1268 : lsn: Lsn,
3459 1268 : _guard: &tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
3460 1268 : ctx: &RequestContext,
3461 1268 : ) -> anyhow::Result<Arc<InMemoryLayer>> {
3462 1268 : let mut guard = self.layers.write().await;
3463 1268 : let gate_guard = self.gate.enter().context("enter gate for inmem layer")?;
3464 :
3465 1268 : let last_record_lsn = self.get_last_record_lsn();
3466 1268 : ensure!(
3467 1268 : lsn > last_record_lsn,
3468 0 : "cannot modify relation after advancing last_record_lsn (incoming_lsn={}, last_record_lsn={})",
3469 : lsn,
3470 : last_record_lsn,
3471 : );
3472 :
3473 1268 : let layer = guard
3474 1268 : .open_mut()?
3475 1268 : .get_layer_for_write(
3476 1268 : lsn,
3477 1268 : self.conf,
3478 1268 : self.timeline_id,
3479 1268 : self.tenant_shard_id,
3480 1268 : gate_guard,
3481 1268 : ctx,
3482 1268 : )
3483 719 : .await?;
3484 1268 : Ok(layer)
3485 1268 : }
3486 :
3487 5279064 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
3488 5279064 : assert!(new_lsn.is_aligned());
3489 :
3490 5279064 : self.metrics.last_record_gauge.set(new_lsn.0 as i64);
3491 5279064 : self.last_record_lsn.advance(new_lsn);
3492 5279064 : }
3493 :
3494 : /// Freeze any existing open in-memory layer and unconditionally notify the flush loop.
3495 : ///
3496 : /// Unconditional flush loop notification is given because in sharded cases we will want to
3497 : /// leave an Lsn gap. Unsharded tenants do not have Lsn gaps.
3498 1172 : async fn freeze_inmem_layer_at(
3499 1172 : &self,
3500 1172 : at: Lsn,
3501 1172 : write_lock: &mut tokio::sync::MutexGuard<'_, Option<TimelineWriterState>>,
3502 1172 : ) -> Result<u64, FlushLayerError> {
3503 1172 : let frozen = {
3504 1172 : let mut guard = self.layers.write().await;
3505 1172 : guard
3506 1172 : .open_mut()?
3507 1172 : .try_freeze_in_memory_layer(at, &self.last_freeze_at, write_lock)
3508 0 : .await
3509 : };
3510 :
3511 1172 : if frozen {
3512 1144 : let now = Instant::now();
3513 1144 : *(self.last_freeze_ts.write().unwrap()) = now;
3514 1144 : }
3515 :
3516 : // Increment the flush cycle counter and wake up the flush task.
3517 : // Remember the new value, so that when we listen for the flush
3518 : // to finish, we know when the flush that we initiated has
3519 : // finished, instead of some other flush that was started earlier.
3520 1172 : let mut my_flush_request = 0;
3521 1172 :
3522 1172 : let flush_loop_state = { *self.flush_loop_state.lock().unwrap() };
3523 1172 : if !matches!(flush_loop_state, FlushLoopState::Running { .. }) {
3524 0 : return Err(FlushLayerError::NotRunning(flush_loop_state));
3525 1172 : }
3526 1172 :
3527 1172 : self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
3528 1172 : my_flush_request = *counter + 1;
3529 1172 : *counter = my_flush_request;
3530 1172 : *lsn = std::cmp::max(at, *lsn);
3531 1172 : });
3532 1172 :
3533 1172 : assert_ne!(my_flush_request, 0);
3534 :
3535 1172 : Ok(my_flush_request)
3536 1172 : }
3537 :
3538 : /// Layer flusher task's main loop.
3539 412 : async fn flush_loop(
3540 412 : self: &Arc<Self>,
3541 412 : mut layer_flush_start_rx: tokio::sync::watch::Receiver<(u64, Lsn)>,
3542 412 : ctx: &RequestContext,
3543 412 : ) {
3544 412 : info!("started flush loop");
3545 : loop {
3546 1546 : tokio::select! {
3547 1546 : _ = self.cancel.cancelled() => {
3548 10 : info!("shutting down layer flush task due to Timeline::cancel");
3549 10 : break;
3550 : },
3551 1546 : _ = layer_flush_start_rx.changed() => {}
3552 1134 : }
3553 1134 : trace!("waking up");
3554 1134 : let (flush_counter, frozen_to_lsn) = *layer_flush_start_rx.borrow();
3555 1134 :
3556 1134 : // The highest LSN to which we flushed in the loop over frozen layers
3557 1134 : let mut flushed_to_lsn = Lsn(0);
3558 :
3559 1134 : let result = loop {
3560 2278 : if self.cancel.is_cancelled() {
3561 0 : info!("dropping out of flush loop for timeline shutdown");
3562 : // Note: we do not bother transmitting into [`layer_flush_done_tx`], because
3563 : // anyone waiting on that will respect self.cancel as well: they will stop
3564 : // waiting at the same time we as drop out of this loop.
3565 0 : return;
3566 2278 : }
3567 2278 :
3568 2278 : let timer = self.metrics.flush_time_histo.start_timer();
3569 :
3570 : let num_frozen_layers;
3571 : let frozen_layer_total_size;
3572 2278 : let layer_to_flush = {
3573 2278 : let guard = self.layers.read().await;
3574 2278 : let Ok(lm) = guard.layer_map() else {
3575 0 : info!("dropping out of flush loop for timeline shutdown");
3576 0 : return;
3577 : };
3578 2278 : num_frozen_layers = lm.frozen_layers.len();
3579 2278 : frozen_layer_total_size = lm
3580 2278 : .frozen_layers
3581 2278 : .iter()
3582 2278 : .map(|l| l.estimated_in_mem_size())
3583 2278 : .sum::<u64>();
3584 2278 : lm.frozen_layers.front().cloned()
3585 : // drop 'layers' lock to allow concurrent reads and writes
3586 : };
3587 2278 : let Some(layer_to_flush) = layer_to_flush else {
3588 1134 : break Ok(());
3589 : };
3590 1144 : if num_frozen_layers
3591 1144 : > std::cmp::max(
3592 1144 : self.get_compaction_threshold(),
3593 1144 : DEFAULT_COMPACTION_THRESHOLD,
3594 1144 : )
3595 0 : && frozen_layer_total_size >= /* 128 MB */ 128000000
3596 : {
3597 0 : tracing::warn!(
3598 0 : "too many frozen layers: {num_frozen_layers} layers with estimated in-mem size of {frozen_layer_total_size} bytes",
3599 : );
3600 1144 : }
3601 17087 : match self.flush_frozen_layer(layer_to_flush, ctx).await {
3602 1144 : Ok(this_layer_to_lsn) => {
3603 1144 : flushed_to_lsn = std::cmp::max(flushed_to_lsn, this_layer_to_lsn);
3604 1144 : }
3605 : Err(FlushLayerError::Cancelled) => {
3606 0 : info!("dropping out of flush loop for timeline shutdown");
3607 0 : return;
3608 : }
3609 0 : err @ Err(
3610 0 : FlushLayerError::NotRunning(_)
3611 0 : | FlushLayerError::Other(_)
3612 0 : | FlushLayerError::CreateImageLayersError(_),
3613 0 : ) => {
3614 0 : error!("could not flush frozen layer: {err:?}");
3615 0 : break err.map(|_| ());
3616 : }
3617 : }
3618 1144 : timer.stop_and_record();
3619 : };
3620 :
3621 : // Unsharded tenants should never advance their LSN beyond the end of the
3622 : // highest layer they write: such gaps between layer data and the frozen LSN
3623 : // are only legal on sharded tenants.
3624 1134 : debug_assert!(
3625 1134 : self.shard_identity.count.count() > 1
3626 1134 : || flushed_to_lsn >= frozen_to_lsn
3627 67 : || !flushed_to_lsn.is_valid()
3628 : );
3629 :
3630 1134 : if flushed_to_lsn < frozen_to_lsn && self.shard_identity.count.count() > 1 {
3631 : // If our layer flushes didn't carry disk_consistent_lsn up to the `to_lsn` advertised
3632 : // to us via layer_flush_start_rx, then advance it here.
3633 : //
3634 : // This path is only taken for tenants with multiple shards: single sharded tenants should
3635 : // never encounter a gap in the wal.
3636 0 : let old_disk_consistent_lsn = self.disk_consistent_lsn.load();
3637 0 : tracing::debug!("Advancing disk_consistent_lsn across layer gap {old_disk_consistent_lsn}->{frozen_to_lsn}");
3638 0 : if self.set_disk_consistent_lsn(frozen_to_lsn) {
3639 0 : if let Err(e) = self.schedule_uploads(frozen_to_lsn, vec![]) {
3640 0 : tracing::warn!("Failed to schedule metadata upload after updating disk_consistent_lsn: {e}");
3641 0 : }
3642 0 : }
3643 1134 : }
3644 :
3645 : // Notify any listeners that we're done
3646 1134 : let _ = self
3647 1134 : .layer_flush_done_tx
3648 1134 : .send_replace((flush_counter, result));
3649 : }
3650 10 : }
3651 :
3652 : /// Waits any flush request created by [`Self::freeze_inmem_layer_at`] to complete.
3653 1092 : async fn wait_flush_completion(&self, request: u64) -> Result<(), FlushLayerError> {
3654 1092 : let mut rx = self.layer_flush_done_tx.subscribe();
3655 : loop {
3656 : {
3657 2181 : let (last_result_counter, last_result) = &*rx.borrow();
3658 2181 : if *last_result_counter >= request {
3659 1092 : if let Err(err) = last_result {
3660 : // We already logged the original error in
3661 : // flush_loop. We cannot propagate it to the caller
3662 : // here, because it might not be Cloneable
3663 0 : return Err(err.clone());
3664 : } else {
3665 1092 : return Ok(());
3666 : }
3667 1089 : }
3668 1089 : }
3669 1089 : trace!("waiting for flush to complete");
3670 1089 : tokio::select! {
3671 1089 : rx_e = rx.changed() => {
3672 1089 : rx_e.map_err(|_| FlushLayerError::NotRunning(*self.flush_loop_state.lock().unwrap()))?;
3673 : },
3674 : // Cancellation safety: we are not leaving an I/O in-flight for the flush, we're just ignoring
3675 : // the notification from [`flush_loop`] that it completed.
3676 1089 : _ = self.cancel.cancelled() => {
3677 0 : tracing::info!("Cancelled layer flush due on timeline shutdown");
3678 0 : return Ok(())
3679 : }
3680 : };
3681 1089 : trace!("done")
3682 : }
3683 1092 : }
3684 :
3685 : /// Flush one frozen in-memory layer to disk, as a new delta layer.
3686 : ///
3687 : /// Return value is the last lsn (inclusive) of the layer that was frozen.
3688 1144 : #[instrument(skip_all, fields(layer=%frozen_layer))]
3689 : async fn flush_frozen_layer(
3690 : self: &Arc<Self>,
3691 : frozen_layer: Arc<InMemoryLayer>,
3692 : ctx: &RequestContext,
3693 : ) -> Result<Lsn, FlushLayerError> {
3694 : debug_assert_current_span_has_tenant_and_timeline_id();
3695 :
3696 : // As a special case, when we have just imported an image into the repository,
3697 : // instead of writing out a L0 delta layer, we directly write out image layer
3698 : // files instead. This is possible as long as *all* the data imported into the
3699 : // repository have the same LSN.
3700 : let lsn_range = frozen_layer.get_lsn_range();
3701 :
3702 : // Whether to directly create image layers for this flush, or flush them as delta layers
3703 : let create_image_layer =
3704 : lsn_range.start == self.initdb_lsn && lsn_range.end == Lsn(self.initdb_lsn.0 + 1);
3705 :
3706 : #[cfg(test)]
3707 : {
3708 : match &mut *self.flush_loop_state.lock().unwrap() {
3709 : FlushLoopState::NotStarted | FlushLoopState::Exited => {
3710 : panic!("flush loop not running")
3711 : }
3712 : FlushLoopState::Running {
3713 : expect_initdb_optimization,
3714 : initdb_optimization_count,
3715 : ..
3716 : } => {
3717 : if create_image_layer {
3718 : *initdb_optimization_count += 1;
3719 : } else {
3720 : assert!(!*expect_initdb_optimization, "expected initdb optimization");
3721 : }
3722 : }
3723 : }
3724 : }
3725 :
3726 : let (layers_to_upload, delta_layer_to_add) = if create_image_layer {
3727 : // Note: The 'ctx' in use here has DownloadBehavior::Error. We should not
3728 : // require downloading anything during initial import.
3729 : let ((rel_partition, metadata_partition), _lsn) = self
3730 : .repartition(
3731 : self.initdb_lsn,
3732 : self.get_compaction_target_size(),
3733 : EnumSet::empty(),
3734 : ctx,
3735 : )
3736 : .await
3737 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e.into()))?;
3738 :
3739 : if self.cancel.is_cancelled() {
3740 : return Err(FlushLayerError::Cancelled);
3741 : }
3742 :
3743 : let mut layers_to_upload = Vec::new();
3744 : layers_to_upload.extend(
3745 : self.create_image_layers(
3746 : &rel_partition,
3747 : self.initdb_lsn,
3748 : ImageLayerCreationMode::Initial,
3749 : ctx,
3750 : )
3751 : .await?,
3752 : );
3753 : if !metadata_partition.parts.is_empty() {
3754 : assert_eq!(
3755 : metadata_partition.parts.len(),
3756 : 1,
3757 : "currently sparse keyspace should only contain a single metadata keyspace"
3758 : );
3759 : layers_to_upload.extend(
3760 : self.create_image_layers(
3761 : // Safety: create_image_layers treat sparse keyspaces differently that it does not scan
3762 : // every single key within the keyspace, and therefore, it's safe to force converting it
3763 : // into a dense keyspace before calling this function.
3764 : &metadata_partition.into_dense(),
3765 : self.initdb_lsn,
3766 : ImageLayerCreationMode::Initial,
3767 : ctx,
3768 : )
3769 : .await?,
3770 : );
3771 : }
3772 :
3773 : (layers_to_upload, None)
3774 : } else {
3775 : // Normal case, write out a L0 delta layer file.
3776 : // `create_delta_layer` will not modify the layer map.
3777 : // We will remove frozen layer and add delta layer in one atomic operation later.
3778 : let Some(layer) = self
3779 : .create_delta_layer(&frozen_layer, None, ctx)
3780 : .await
3781 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?
3782 : else {
3783 : panic!("delta layer cannot be empty if no filter is applied");
3784 : };
3785 : (
3786 : // FIXME: even though we have a single image and single delta layer assumption
3787 : // we push them to vec
3788 : vec![layer.clone()],
3789 : Some(layer),
3790 : )
3791 : };
3792 :
3793 : pausable_failpoint!("flush-layer-cancel-after-writing-layer-out-pausable");
3794 :
3795 : if self.cancel.is_cancelled() {
3796 : return Err(FlushLayerError::Cancelled);
3797 : }
3798 :
3799 : let disk_consistent_lsn = Lsn(lsn_range.end.0 - 1);
3800 :
3801 : // The new on-disk layers are now in the layer map. We can remove the
3802 : // in-memory layer from the map now. The flushed layer is stored in
3803 : // the mapping in `create_delta_layer`.
3804 : {
3805 : let mut guard = self.layers.write().await;
3806 :
3807 : guard.open_mut()?.finish_flush_l0_layer(
3808 : delta_layer_to_add.as_ref(),
3809 : &frozen_layer,
3810 : &self.metrics,
3811 : );
3812 :
3813 : if self.set_disk_consistent_lsn(disk_consistent_lsn) {
3814 : // Schedule remote uploads that will reflect our new disk_consistent_lsn
3815 : self.schedule_uploads(disk_consistent_lsn, layers_to_upload)
3816 0 : .map_err(|e| FlushLayerError::from_anyhow(self, e))?;
3817 : }
3818 : // release lock on 'layers'
3819 : };
3820 :
3821 : // Backpressure mechanism: wait with continuation of the flush loop until we have uploaded all layer files.
3822 : // This makes us refuse ingest until the new layers have been persisted to the remote.
3823 : self.remote_client
3824 : .wait_completion()
3825 : .await
3826 0 : .map_err(|e| match e {
3827 : WaitCompletionError::UploadQueueShutDownOrStopped
3828 : | WaitCompletionError::NotInitialized(
3829 : NotInitialized::ShuttingDown | NotInitialized::Stopped,
3830 0 : ) => FlushLayerError::Cancelled,
3831 : WaitCompletionError::NotInitialized(NotInitialized::Uninitialized) => {
3832 0 : FlushLayerError::Other(anyhow!(e).into())
3833 : }
3834 0 : })?;
3835 :
3836 : // FIXME: between create_delta_layer and the scheduling of the upload in `update_metadata_file`,
3837 : // a compaction can delete the file and then it won't be available for uploads any more.
3838 : // We still schedule the upload, resulting in an error, but ideally we'd somehow avoid this
3839 : // race situation.
3840 : // See https://github.com/neondatabase/neon/issues/4526
3841 : pausable_failpoint!("flush-frozen-pausable");
3842 :
3843 : // This failpoint is used by another test case `test_pageserver_recovery`.
3844 : fail_point!("flush-frozen-exit");
3845 :
3846 : Ok(Lsn(lsn_range.end.0 - 1))
3847 : }
3848 :
3849 : /// Return true if the value changed
3850 : ///
3851 : /// This function must only be used from the layer flush task.
3852 1144 : fn set_disk_consistent_lsn(&self, new_value: Lsn) -> bool {
3853 1144 : let old_value = self.disk_consistent_lsn.fetch_max(new_value);
3854 1144 : assert!(new_value >= old_value, "disk_consistent_lsn must be growing monotonously at runtime; current {old_value}, offered {new_value}");
3855 1144 : new_value != old_value
3856 1144 : }
3857 :
3858 : /// Update metadata file
3859 1146 : fn schedule_uploads(
3860 1146 : &self,
3861 1146 : disk_consistent_lsn: Lsn,
3862 1146 : layers_to_upload: impl IntoIterator<Item = ResidentLayer>,
3863 1146 : ) -> anyhow::Result<()> {
3864 1146 : // We can only save a valid 'prev_record_lsn' value on disk if we
3865 1146 : // flushed *all* in-memory changes to disk. We only track
3866 1146 : // 'prev_record_lsn' in memory for the latest processed record, so we
3867 1146 : // don't remember what the correct value that corresponds to some old
3868 1146 : // LSN is. But if we flush everything, then the value corresponding
3869 1146 : // current 'last_record_lsn' is correct and we can store it on disk.
3870 1146 : let RecordLsn {
3871 1146 : last: last_record_lsn,
3872 1146 : prev: prev_record_lsn,
3873 1146 : } = self.last_record_lsn.load();
3874 1146 : let ondisk_prev_record_lsn = if disk_consistent_lsn == last_record_lsn {
3875 1066 : Some(prev_record_lsn)
3876 : } else {
3877 80 : None
3878 : };
3879 :
3880 1146 : let update = crate::tenant::metadata::MetadataUpdate::new(
3881 1146 : disk_consistent_lsn,
3882 1146 : ondisk_prev_record_lsn,
3883 1146 : *self.latest_gc_cutoff_lsn.read(),
3884 1146 : );
3885 1146 :
3886 1146 : fail_point!("checkpoint-before-saving-metadata", |x| bail!(
3887 0 : "{}",
3888 0 : x.unwrap()
3889 1146 : ));
3890 :
3891 2302 : for layer in layers_to_upload {
3892 1156 : self.remote_client.schedule_layer_file_upload(layer)?;
3893 : }
3894 1146 : self.remote_client
3895 1146 : .schedule_index_upload_for_metadata_update(&update)?;
3896 :
3897 1146 : Ok(())
3898 1146 : }
3899 :
3900 0 : pub(crate) async fn preserve_initdb_archive(&self) -> anyhow::Result<()> {
3901 0 : self.remote_client
3902 0 : .preserve_initdb_archive(
3903 0 : &self.tenant_shard_id.tenant_id,
3904 0 : &self.timeline_id,
3905 0 : &self.cancel,
3906 0 : )
3907 0 : .await
3908 0 : }
3909 :
3910 : // Write out the given frozen in-memory layer as a new L0 delta file. This L0 file will not be tracked
3911 : // in layer map immediately. The caller is responsible to put it into the layer map.
3912 968 : async fn create_delta_layer(
3913 968 : self: &Arc<Self>,
3914 968 : frozen_layer: &Arc<InMemoryLayer>,
3915 968 : key_range: Option<Range<Key>>,
3916 968 : ctx: &RequestContext,
3917 968 : ) -> anyhow::Result<Option<ResidentLayer>> {
3918 968 : let self_clone = Arc::clone(self);
3919 968 : let frozen_layer = Arc::clone(frozen_layer);
3920 968 : let ctx = ctx.attached_child();
3921 968 : let work = async move {
3922 968 : let Some((desc, path)) = frozen_layer
3923 968 : .write_to_disk(&ctx, key_range, self_clone.l0_flush_global_state.inner())
3924 10257 : .await?
3925 : else {
3926 0 : return Ok(None);
3927 : };
3928 968 : let new_delta = Layer::finish_creating(self_clone.conf, &self_clone, desc, &path)?;
3929 :
3930 : // The write_to_disk() above calls writer.finish() which already did the fsync of the inodes.
3931 : // We just need to fsync the directory in which these inodes are linked,
3932 : // which we know to be the timeline directory.
3933 : //
3934 : // We use fatal_err() below because the after write_to_disk returns with success,
3935 : // the in-memory state of the filesystem already has the layer file in its final place,
3936 : // and subsequent pageserver code could think it's durable while it really isn't.
3937 968 : let timeline_dir = VirtualFile::open(
3938 968 : &self_clone
3939 968 : .conf
3940 968 : .timeline_path(&self_clone.tenant_shard_id, &self_clone.timeline_id),
3941 968 : &ctx,
3942 968 : )
3943 490 : .await
3944 968 : .fatal_err("VirtualFile::open for timeline dir fsync");
3945 968 : timeline_dir
3946 968 : .sync_all()
3947 484 : .await
3948 968 : .fatal_err("VirtualFile::sync_all timeline dir");
3949 968 : anyhow::Ok(Some(new_delta))
3950 968 : };
3951 : // Before tokio-epoll-uring, we ran write_to_disk & the sync_all inside spawn_blocking.
3952 : // Preserve that behavior to maintain the same behavior for `virtual_file_io_engine=std-fs`.
3953 : use crate::virtual_file::io_engine::IoEngine;
3954 968 : match crate::virtual_file::io_engine::get() {
3955 0 : IoEngine::NotSet => panic!("io engine not set"),
3956 : IoEngine::StdFs => {
3957 484 : let span = tracing::info_span!("blocking");
3958 484 : tokio::task::spawn_blocking({
3959 484 : move || Handle::current().block_on(work.instrument(span))
3960 484 : })
3961 484 : .await
3962 484 : .context("spawn_blocking")
3963 484 : .and_then(|x| x)
3964 : }
3965 : #[cfg(target_os = "linux")]
3966 11226 : IoEngine::TokioEpollUring => work.await,
3967 : }
3968 968 : }
3969 :
3970 540 : async fn repartition(
3971 540 : &self,
3972 540 : lsn: Lsn,
3973 540 : partition_size: u64,
3974 540 : flags: EnumSet<CompactFlags>,
3975 540 : ctx: &RequestContext,
3976 540 : ) -> Result<((KeyPartitioning, SparseKeyPartitioning), Lsn), CompactionError> {
3977 540 : let Ok(mut partitioning_guard) = self.partitioning.try_lock() else {
3978 : // NB: there are two callers, one is the compaction task, of which there is only one per struct Tenant and hence Timeline.
3979 : // The other is the initdb optimization in flush_frozen_layer, used by `boostrap_timeline`, which runs before `.activate()`
3980 : // and hence before the compaction task starts.
3981 0 : return Err(CompactionError::Other(anyhow!(
3982 0 : "repartition() called concurrently, this should not happen"
3983 0 : )));
3984 : };
3985 540 : let ((dense_partition, sparse_partition), partition_lsn) = &*partitioning_guard;
3986 540 : if lsn < *partition_lsn {
3987 0 : return Err(CompactionError::Other(anyhow!(
3988 0 : "repartition() called with LSN going backwards, this should not happen"
3989 0 : )));
3990 540 : }
3991 540 :
3992 540 : let distance = lsn.0 - partition_lsn.0;
3993 540 : if *partition_lsn != Lsn(0)
3994 262 : && distance <= self.repartition_threshold
3995 262 : && !flags.contains(CompactFlags::ForceRepartition)
3996 : {
3997 248 : debug!(
3998 : distance,
3999 : threshold = self.repartition_threshold,
4000 0 : "no repartitioning needed"
4001 : );
4002 248 : return Ok((
4003 248 : (dense_partition.clone(), sparse_partition.clone()),
4004 248 : *partition_lsn,
4005 248 : ));
4006 292 : }
4007 :
4008 15853 : let (dense_ks, sparse_ks) = self.collect_keyspace(lsn, ctx).await?;
4009 292 : let dense_partitioning = dense_ks.partition(&self.shard_identity, partition_size);
4010 292 : let sparse_partitioning = SparseKeyPartitioning {
4011 292 : parts: vec![sparse_ks],
4012 292 : }; // no partitioning for metadata keys for now
4013 292 : *partitioning_guard = ((dense_partitioning, sparse_partitioning), lsn);
4014 292 :
4015 292 : Ok((partitioning_guard.0.clone(), partitioning_guard.1))
4016 540 : }
4017 :
4018 : // Is it time to create a new image layer for the given partition?
4019 14 : async fn time_for_new_image_layer(&self, partition: &KeySpace, lsn: Lsn) -> bool {
4020 14 : let threshold = self.get_image_creation_threshold();
4021 :
4022 14 : let guard = self.layers.read().await;
4023 14 : let Ok(layers) = guard.layer_map() else {
4024 0 : return false;
4025 : };
4026 :
4027 14 : let mut max_deltas = 0;
4028 28 : for part_range in &partition.ranges {
4029 14 : let image_coverage = layers.image_coverage(part_range, lsn);
4030 28 : for (img_range, last_img) in image_coverage {
4031 14 : let img_lsn = if let Some(last_img) = last_img {
4032 0 : last_img.get_lsn_range().end
4033 : } else {
4034 14 : Lsn(0)
4035 : };
4036 : // Let's consider an example:
4037 : //
4038 : // delta layer with LSN range 71-81
4039 : // delta layer with LSN range 81-91
4040 : // delta layer with LSN range 91-101
4041 : // image layer at LSN 100
4042 : //
4043 : // If 'lsn' is still 100, i.e. no new WAL has been processed since the last image layer,
4044 : // there's no need to create a new one. We check this case explicitly, to avoid passing
4045 : // a bogus range to count_deltas below, with start > end. It's even possible that there
4046 : // are some delta layers *later* than current 'lsn', if more WAL was processed and flushed
4047 : // after we read last_record_lsn, which is passed here in the 'lsn' argument.
4048 14 : if img_lsn < lsn {
4049 14 : let num_deltas =
4050 14 : layers.count_deltas(&img_range, &(img_lsn..lsn), Some(threshold));
4051 14 :
4052 14 : max_deltas = max_deltas.max(num_deltas);
4053 14 : if num_deltas >= threshold {
4054 0 : debug!(
4055 0 : "key range {}-{}, has {} deltas on this timeline in LSN range {}..{}",
4056 : img_range.start, img_range.end, num_deltas, img_lsn, lsn
4057 : );
4058 0 : return true;
4059 14 : }
4060 0 : }
4061 : }
4062 : }
4063 :
4064 14 : debug!(
4065 : max_deltas,
4066 0 : "none of the partitioned ranges had >= {threshold} deltas"
4067 : );
4068 14 : false
4069 14 : }
4070 :
4071 : /// Create image layers for Postgres data. Assumes the caller passes a partition that is not too large,
4072 : /// so that at most one image layer will be produced from this function.
4073 202 : async fn create_image_layer_for_rel_blocks(
4074 202 : self: &Arc<Self>,
4075 202 : partition: &KeySpace,
4076 202 : mut image_layer_writer: ImageLayerWriter,
4077 202 : lsn: Lsn,
4078 202 : ctx: &RequestContext,
4079 202 : img_range: Range<Key>,
4080 202 : start: Key,
4081 202 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4082 202 : let mut wrote_keys = false;
4083 202 :
4084 202 : let mut key_request_accum = KeySpaceAccum::new();
4085 1344 : for range in &partition.ranges {
4086 1142 : let mut key = range.start;
4087 2472 : while key < range.end {
4088 : // Decide whether to retain this key: usually we do, but sharded tenants may
4089 : // need to drop keys that don't belong to them. If we retain the key, add it
4090 : // to `key_request_accum` for later issuing a vectored get
4091 1330 : if self.shard_identity.is_key_disposable(&key) {
4092 0 : debug!(
4093 0 : "Dropping key {} during compaction (it belongs on shard {:?})",
4094 0 : key,
4095 0 : self.shard_identity.get_shard_number(&key)
4096 : );
4097 1330 : } else {
4098 1330 : key_request_accum.add_key(key);
4099 1330 : }
4100 :
4101 1330 : let last_key_in_range = key.next() == range.end;
4102 1330 : key = key.next();
4103 1330 :
4104 1330 : // Maybe flush `key_rest_accum`
4105 1330 : if key_request_accum.raw_size() >= Timeline::MAX_GET_VECTORED_KEYS
4106 1330 : || (last_key_in_range && key_request_accum.raw_size() > 0)
4107 : {
4108 1142 : let results = self
4109 1142 : .get_vectored(key_request_accum.consume_keyspace(), lsn, ctx)
4110 50 : .await?;
4111 :
4112 1142 : if self.cancel.is_cancelled() {
4113 0 : return Err(CreateImageLayersError::Cancelled);
4114 1142 : }
4115 :
4116 2472 : for (img_key, img) in results {
4117 1330 : let img = match img {
4118 1330 : Ok(img) => img,
4119 0 : Err(err) => {
4120 0 : // If we fail to reconstruct a VM or FSM page, we can zero the
4121 0 : // page without losing any actual user data. That seems better
4122 0 : // than failing repeatedly and getting stuck.
4123 0 : //
4124 0 : // We had a bug at one point, where we truncated the FSM and VM
4125 0 : // in the pageserver, but the Postgres didn't know about that
4126 0 : // and continued to generate incremental WAL records for pages
4127 0 : // that didn't exist in the pageserver. Trying to replay those
4128 0 : // WAL records failed to find the previous image of the page.
4129 0 : // This special case allows us to recover from that situation.
4130 0 : // See https://github.com/neondatabase/neon/issues/2601.
4131 0 : //
4132 0 : // Unfortunately we cannot do this for the main fork, or for
4133 0 : // any metadata keys, keys, as that would lead to actual data
4134 0 : // loss.
4135 0 : if img_key.is_rel_fsm_block_key() || img_key.is_rel_vm_block_key() {
4136 0 : warn!("could not reconstruct FSM or VM key {img_key}, filling with zeros: {err:?}");
4137 0 : ZERO_PAGE.clone()
4138 : } else {
4139 0 : return Err(CreateImageLayersError::from(err));
4140 : }
4141 : }
4142 : };
4143 :
4144 : // Write all the keys we just read into our new image layer.
4145 1460 : image_layer_writer.put_image(img_key, img, ctx).await?;
4146 1330 : wrote_keys = true;
4147 : }
4148 188 : }
4149 : }
4150 : }
4151 :
4152 202 : if wrote_keys {
4153 : // Normal path: we have written some data into the new image layer for this
4154 : // partition, so flush it to disk.
4155 406 : let (desc, path) = image_layer_writer.finish(ctx).await?;
4156 202 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
4157 202 : info!("created image layer for rel {}", image_layer.local_path());
4158 202 : Ok(ImageLayerCreationOutcome {
4159 202 : image: Some(image_layer),
4160 202 : next_start_key: img_range.end,
4161 202 : })
4162 : } else {
4163 : // Special case: the image layer may be empty if this is a sharded tenant and the
4164 : // partition does not cover any keys owned by this shard. In this case, to ensure
4165 : // we don't leave gaps between image layers, leave `start` where it is, so that the next
4166 : // layer we write will cover the key range that we just scanned.
4167 0 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
4168 0 : Ok(ImageLayerCreationOutcome {
4169 0 : image: None,
4170 0 : next_start_key: start,
4171 0 : })
4172 : }
4173 202 : }
4174 :
4175 : /// Create an image layer for metadata keys. This function produces one image layer for all metadata
4176 : /// keys for now. Because metadata keys cannot exceed basebackup size limit, the image layer for it
4177 : /// would not be too large to fit in a single image layer.
4178 : #[allow(clippy::too_many_arguments)]
4179 192 : async fn create_image_layer_for_metadata_keys(
4180 192 : self: &Arc<Self>,
4181 192 : partition: &KeySpace,
4182 192 : mut image_layer_writer: ImageLayerWriter,
4183 192 : lsn: Lsn,
4184 192 : ctx: &RequestContext,
4185 192 : img_range: Range<Key>,
4186 192 : mode: ImageLayerCreationMode,
4187 192 : start: Key,
4188 192 : ) -> Result<ImageLayerCreationOutcome, CreateImageLayersError> {
4189 192 : // Metadata keys image layer creation.
4190 192 : let mut reconstruct_state = ValuesReconstructState::default();
4191 192 : let begin = Instant::now();
4192 192 : let data = self
4193 192 : .get_vectored_impl(partition.clone(), lsn, &mut reconstruct_state, ctx)
4194 1053 : .await?;
4195 192 : let (data, total_kb_retrieved, total_keys_retrieved) = {
4196 192 : let mut new_data = BTreeMap::new();
4197 192 : let mut total_kb_retrieved = 0;
4198 192 : let mut total_keys_retrieved = 0;
4199 10204 : for (k, v) in data {
4200 10012 : let v = v?;
4201 10012 : total_kb_retrieved += KEY_SIZE + v.len();
4202 10012 : total_keys_retrieved += 1;
4203 10012 : new_data.insert(k, v);
4204 : }
4205 192 : (new_data, total_kb_retrieved / 1024, total_keys_retrieved)
4206 192 : };
4207 192 : let delta_files_accessed = reconstruct_state.get_delta_layers_visited();
4208 192 : let elapsed = begin.elapsed();
4209 192 :
4210 192 : let trigger_generation = delta_files_accessed as usize >= MAX_AUX_FILE_V2_DELTAS;
4211 192 : info!(
4212 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()
4213 : );
4214 :
4215 192 : if !trigger_generation && mode == ImageLayerCreationMode::Try {
4216 2 : return Ok(ImageLayerCreationOutcome {
4217 2 : image: None,
4218 2 : next_start_key: img_range.end,
4219 2 : });
4220 190 : }
4221 190 : if self.cancel.is_cancelled() {
4222 0 : return Err(CreateImageLayersError::Cancelled);
4223 190 : }
4224 190 : let mut wrote_any_image = false;
4225 10202 : for (k, v) in data {
4226 10012 : if v.is_empty() {
4227 : // the key has been deleted, it does not need an image
4228 : // in metadata keyspace, an empty image == tombstone
4229 8 : continue;
4230 10004 : }
4231 10004 : wrote_any_image = true;
4232 10004 :
4233 10004 : // No need to handle sharding b/c metadata keys are always on the 0-th shard.
4234 10004 :
4235 10004 : // TODO: split image layers to avoid too large layer files. Too large image files are not handled
4236 10004 : // on the normal data path either.
4237 10160 : image_layer_writer.put_image(k, v, ctx).await?;
4238 : }
4239 :
4240 190 : if wrote_any_image {
4241 : // Normal path: we have written some data into the new image layer for this
4242 : // partition, so flush it to disk.
4243 24 : let (desc, path) = image_layer_writer.finish(ctx).await?;
4244 12 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
4245 12 : info!(
4246 0 : "created image layer for metadata {}",
4247 0 : image_layer.local_path()
4248 : );
4249 12 : Ok(ImageLayerCreationOutcome {
4250 12 : image: Some(image_layer),
4251 12 : next_start_key: img_range.end,
4252 12 : })
4253 : } else {
4254 : // Special case: the image layer may be empty if this is a sharded tenant and the
4255 : // partition does not cover any keys owned by this shard. In this case, to ensure
4256 : // we don't leave gaps between image layers, leave `start` where it is, so that the next
4257 : // layer we write will cover the key range that we just scanned.
4258 178 : tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
4259 178 : Ok(ImageLayerCreationOutcome {
4260 178 : image: None,
4261 178 : next_start_key: start,
4262 178 : })
4263 : }
4264 192 : }
4265 :
4266 : /// Predicate function which indicates whether we should check if new image layers
4267 : /// are required. Since checking if new image layers are required is expensive in
4268 : /// terms of CPU, we only do it in the following cases:
4269 : /// 1. If the timeline has ingested sufficient WAL to justify the cost
4270 : /// 2. If enough time has passed since the last check:
4271 : /// 1. For large tenants, we wish to perform the check more often since they
4272 : /// suffer from the lack of image layers
4273 : /// 2. For small tenants (that can mostly fit in RAM), we use a much longer interval
4274 716 : fn should_check_if_image_layers_required(self: &Arc<Timeline>, lsn: Lsn) -> bool {
4275 : const LARGE_TENANT_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
4276 :
4277 716 : let last_checks_at = self.last_image_layer_creation_check_at.load();
4278 716 : let distance = lsn
4279 716 : .checked_sub(last_checks_at)
4280 716 : .expect("Attempt to compact with LSN going backwards");
4281 716 : let min_distance =
4282 716 : self.get_image_layer_creation_check_threshold() as u64 * self.get_checkpoint_distance();
4283 716 :
4284 716 : let distance_based_decision = distance.0 >= min_distance;
4285 716 :
4286 716 : let mut time_based_decision = false;
4287 716 : let mut last_check_instant = self.last_image_layer_creation_check_instant.lock().unwrap();
4288 716 : if let CurrentLogicalSize::Exact(logical_size) = self.current_logical_size.current_size() {
4289 614 : let check_required_after = if Into::<u64>::into(&logical_size) >= LARGE_TENANT_THRESHOLD
4290 : {
4291 0 : self.get_checkpoint_timeout()
4292 : } else {
4293 614 : Duration::from_secs(3600 * 48)
4294 : };
4295 :
4296 614 : time_based_decision = match *last_check_instant {
4297 438 : Some(last_check) => {
4298 438 : let elapsed = last_check.elapsed();
4299 438 : elapsed >= check_required_after
4300 : }
4301 176 : None => true,
4302 : };
4303 102 : }
4304 :
4305 : // Do the expensive delta layer counting only if this timeline has ingested sufficient
4306 : // WAL since the last check or a checkpoint timeout interval has elapsed since the last
4307 : // check.
4308 716 : let decision = distance_based_decision || time_based_decision;
4309 :
4310 716 : if decision {
4311 178 : self.last_image_layer_creation_check_at.store(lsn);
4312 178 : *last_check_instant = Some(Instant::now());
4313 538 : }
4314 :
4315 716 : decision
4316 716 : }
4317 :
4318 716 : #[tracing::instrument(skip_all, fields(%lsn, %mode))]
4319 : async fn create_image_layers(
4320 : self: &Arc<Timeline>,
4321 : partitioning: &KeyPartitioning,
4322 : lsn: Lsn,
4323 : mode: ImageLayerCreationMode,
4324 : ctx: &RequestContext,
4325 : ) -> Result<Vec<ResidentLayer>, CreateImageLayersError> {
4326 : let timer = self.metrics.create_images_time_histo.start_timer();
4327 : let mut image_layers = Vec::new();
4328 :
4329 : // We need to avoid holes between generated image layers.
4330 : // Otherwise LayerMap::image_layer_exists will return false if key range of some layer is covered by more than one
4331 : // image layer with hole between them. In this case such layer can not be utilized by GC.
4332 : //
4333 : // How such hole between partitions can appear?
4334 : // if we have relation with relid=1 and size 100 and relation with relid=2 with size 200 then result of
4335 : // KeySpace::partition may contain partitions <100000000..100000099> and <200000000..200000199>.
4336 : // If there is delta layer <100000000..300000000> then it never be garbage collected because
4337 : // image layers <100000000..100000099> and <200000000..200000199> are not completely covering it.
4338 : let mut start = Key::MIN;
4339 :
4340 : let check_for_image_layers = self.should_check_if_image_layers_required(lsn);
4341 :
4342 : for partition in partitioning.parts.iter() {
4343 : if self.cancel.is_cancelled() {
4344 : return Err(CreateImageLayersError::Cancelled);
4345 : }
4346 :
4347 : let img_range = start..partition.ranges.last().unwrap().end;
4348 : let compact_metadata = partition.overlaps(&Key::metadata_key_range());
4349 : if compact_metadata {
4350 : for range in &partition.ranges {
4351 : assert!(
4352 : range.start.field1 >= METADATA_KEY_BEGIN_PREFIX
4353 : && range.end.field1 <= METADATA_KEY_END_PREFIX,
4354 : "metadata keys must be partitioned separately"
4355 : );
4356 : }
4357 : if mode == ImageLayerCreationMode::Try && !check_for_image_layers {
4358 : // Skip compaction if there are not enough updates. Metadata compaction will do a scan and
4359 : // might mess up with evictions.
4360 : start = img_range.end;
4361 : continue;
4362 : }
4363 : // For initial and force modes, we always generate image layers for metadata keys.
4364 : } else if let ImageLayerCreationMode::Try = mode {
4365 : // check_for_image_layers = false -> skip
4366 : // check_for_image_layers = true -> check time_for_new_image_layer -> skip/generate
4367 : if !check_for_image_layers || !self.time_for_new_image_layer(partition, lsn).await {
4368 : start = img_range.end;
4369 : continue;
4370 : }
4371 : }
4372 : if let ImageLayerCreationMode::Force = mode {
4373 : // When forced to create image layers, we might try and create them where they already
4374 : // exist. This mode is only used in tests/debug.
4375 : let layers = self.layers.read().await;
4376 : if layers.contains_key(&PersistentLayerKey {
4377 : key_range: img_range.clone(),
4378 : lsn_range: PersistentLayerDesc::image_layer_lsn_range(lsn),
4379 : is_delta: false,
4380 : }) {
4381 : tracing::info!(
4382 : "Skipping image layer at {lsn} {}..{}, already exists",
4383 : img_range.start,
4384 : img_range.end
4385 : );
4386 : start = img_range.end;
4387 : continue;
4388 : }
4389 : }
4390 :
4391 : let image_layer_writer = ImageLayerWriter::new(
4392 : self.conf,
4393 : self.timeline_id,
4394 : self.tenant_shard_id,
4395 : &img_range,
4396 : lsn,
4397 : ctx,
4398 : )
4399 : .await?;
4400 :
4401 0 : fail_point!("image-layer-writer-fail-before-finish", |_| {
4402 0 : Err(CreateImageLayersError::Other(anyhow::anyhow!(
4403 0 : "failpoint image-layer-writer-fail-before-finish"
4404 0 : )))
4405 0 : });
4406 :
4407 : if !compact_metadata {
4408 : let ImageLayerCreationOutcome {
4409 : image,
4410 : next_start_key,
4411 : } = self
4412 : .create_image_layer_for_rel_blocks(
4413 : partition,
4414 : image_layer_writer,
4415 : lsn,
4416 : ctx,
4417 : img_range,
4418 : start,
4419 : )
4420 : .await?;
4421 :
4422 : start = next_start_key;
4423 : image_layers.extend(image);
4424 : } else {
4425 : let ImageLayerCreationOutcome {
4426 : image,
4427 : next_start_key,
4428 : } = self
4429 : .create_image_layer_for_metadata_keys(
4430 : partition,
4431 : image_layer_writer,
4432 : lsn,
4433 : ctx,
4434 : img_range,
4435 : mode,
4436 : start,
4437 : )
4438 : .await?;
4439 : start = next_start_key;
4440 : image_layers.extend(image);
4441 : }
4442 : }
4443 :
4444 : let mut guard = self.layers.write().await;
4445 :
4446 : // FIXME: we could add the images to be uploaded *before* returning from here, but right
4447 : // now they are being scheduled outside of write lock; current way is inconsistent with
4448 : // compaction lock order.
4449 : guard
4450 : .open_mut()?
4451 : .track_new_image_layers(&image_layers, &self.metrics);
4452 : drop_wlock(guard);
4453 : timer.stop_and_record();
4454 :
4455 : // Creating image layers may have caused some previously visible layers to be covered
4456 : if !image_layers.is_empty() {
4457 : self.update_layer_visibility().await?;
4458 : }
4459 :
4460 : Ok(image_layers)
4461 : }
4462 :
4463 : /// Wait until the background initial logical size calculation is complete, or
4464 : /// this Timeline is shut down. Calling this function will cause the initial
4465 : /// logical size calculation to skip waiting for the background jobs barrier.
4466 0 : pub(crate) async fn await_initial_logical_size(self: Arc<Self>) {
4467 0 : if !self.shard_identity.is_shard_zero() {
4468 : // We don't populate logical size on shard >0: skip waiting for it.
4469 0 : return;
4470 0 : }
4471 0 :
4472 0 : if self.remote_client.is_deleting() {
4473 : // The timeline was created in a deletion-resume state, we don't expect logical size to be populated
4474 0 : return;
4475 0 : }
4476 0 :
4477 0 : if self.current_logical_size.current_size().is_exact() {
4478 : // root timelines are initialized with exact count, but never start the background
4479 : // calculation
4480 0 : return;
4481 0 : }
4482 :
4483 0 : if let Some(await_bg_cancel) = self
4484 0 : .current_logical_size
4485 0 : .cancel_wait_for_background_loop_concurrency_limit_semaphore
4486 0 : .get()
4487 0 : {
4488 0 : await_bg_cancel.cancel();
4489 0 : } else {
4490 : // We should not wait if we were not able to explicitly instruct
4491 : // the logical size cancellation to skip the concurrency limit semaphore.
4492 : // TODO: this is an unexpected case. We should restructure so that it
4493 : // can't happen.
4494 0 : tracing::warn!(
4495 0 : "await_initial_logical_size: can't get semaphore cancel token, skipping"
4496 : );
4497 0 : debug_assert!(false);
4498 : }
4499 :
4500 0 : tokio::select!(
4501 0 : _ = self.current_logical_size.initialized.acquire() => {},
4502 0 : _ = self.cancel.cancelled() => {}
4503 : )
4504 0 : }
4505 :
4506 : /// Detach this timeline from its ancestor by copying all of ancestors layers as this
4507 : /// Timelines layers up to the ancestor_lsn.
4508 : ///
4509 : /// Requires a timeline that:
4510 : /// - has an ancestor to detach from
4511 : /// - the ancestor does not have an ancestor -- follows from the original RFC limitations, not
4512 : /// a technical requirement
4513 : ///
4514 : /// After the operation has been started, it cannot be canceled. Upon restart it needs to be
4515 : /// polled again until completion.
4516 : ///
4517 : /// During the operation all timelines sharing the data with this timeline will be reparented
4518 : /// from our ancestor to be branches of this timeline.
4519 0 : pub(crate) async fn prepare_to_detach_from_ancestor(
4520 0 : self: &Arc<Timeline>,
4521 0 : tenant: &crate::tenant::Tenant,
4522 0 : options: detach_ancestor::Options,
4523 0 : ctx: &RequestContext,
4524 0 : ) -> Result<detach_ancestor::Progress, detach_ancestor::Error> {
4525 0 : detach_ancestor::prepare(self, tenant, options, ctx).await
4526 0 : }
4527 :
4528 : /// Second step of detach from ancestor; detaches the `self` from it's current ancestor and
4529 : /// reparents any reparentable children of previous ancestor.
4530 : ///
4531 : /// This method is to be called while holding the TenantManager's tenant slot, so during this
4532 : /// method we cannot be deleted nor can any timeline be deleted. After this method returns
4533 : /// successfully, tenant must be reloaded.
4534 : ///
4535 : /// Final step will be to [`Self::complete_detaching_timeline_ancestor`] after optionally
4536 : /// resetting the tenant.
4537 0 : pub(crate) async fn detach_from_ancestor_and_reparent(
4538 0 : self: &Arc<Timeline>,
4539 0 : tenant: &crate::tenant::Tenant,
4540 0 : prepared: detach_ancestor::PreparedTimelineDetach,
4541 0 : ctx: &RequestContext,
4542 0 : ) -> Result<detach_ancestor::DetachingAndReparenting, detach_ancestor::Error> {
4543 0 : detach_ancestor::detach_and_reparent(self, tenant, prepared, ctx).await
4544 0 : }
4545 :
4546 : /// Final step which unblocks the GC.
4547 : ///
4548 : /// The tenant must've been reset if ancestry was modified previously (in tenant manager).
4549 0 : pub(crate) async fn complete_detaching_timeline_ancestor(
4550 0 : self: &Arc<Timeline>,
4551 0 : tenant: &crate::tenant::Tenant,
4552 0 : attempt: detach_ancestor::Attempt,
4553 0 : ctx: &RequestContext,
4554 0 : ) -> Result<(), detach_ancestor::Error> {
4555 0 : detach_ancestor::complete(self, tenant, attempt, ctx).await
4556 0 : }
4557 : }
4558 :
4559 : impl Drop for Timeline {
4560 10 : fn drop(&mut self) {
4561 10 : if let Some(ancestor) = &self.ancestor_timeline {
4562 : // This lock should never be poisoned, but in case it is we do a .map() instead of
4563 : // an unwrap(), to avoid panicking in a destructor and thereby aborting the process.
4564 4 : if let Ok(mut gc_info) = ancestor.gc_info.write() {
4565 4 : if !gc_info.remove_child_not_offloaded(self.timeline_id) {
4566 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
4567 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
4568 4 : }
4569 0 : }
4570 6 : }
4571 10 : }
4572 : }
4573 :
4574 : /// Top-level failure to compact.
4575 0 : #[derive(Debug, thiserror::Error)]
4576 : pub(crate) enum CompactionError {
4577 : #[error("The timeline or pageserver is shutting down")]
4578 : ShuttingDown,
4579 : /// Compaction tried to offload a timeline and failed
4580 : #[error("Failed to offload timeline: {0}")]
4581 : Offload(OffloadError),
4582 : /// Compaction cannot be done right now; page reconstruction and so on.
4583 : #[error(transparent)]
4584 : Other(anyhow::Error),
4585 : }
4586 :
4587 : impl From<OffloadError> for CompactionError {
4588 0 : fn from(e: OffloadError) -> Self {
4589 0 : match e {
4590 0 : OffloadError::Cancelled => Self::ShuttingDown,
4591 0 : _ => Self::Offload(e),
4592 : }
4593 0 : }
4594 : }
4595 :
4596 : impl CompactionError {
4597 0 : pub fn is_cancelled(&self) -> bool {
4598 0 : matches!(self, CompactionError::ShuttingDown)
4599 0 : }
4600 : }
4601 :
4602 : impl From<CollectKeySpaceError> for CompactionError {
4603 0 : fn from(err: CollectKeySpaceError) -> Self {
4604 0 : match err {
4605 : CollectKeySpaceError::Cancelled
4606 : | CollectKeySpaceError::PageRead(PageReconstructError::Cancelled) => {
4607 0 : CompactionError::ShuttingDown
4608 : }
4609 0 : e => CompactionError::Other(e.into()),
4610 : }
4611 0 : }
4612 : }
4613 :
4614 : impl From<super::upload_queue::NotInitialized> for CompactionError {
4615 0 : fn from(value: super::upload_queue::NotInitialized) -> Self {
4616 0 : match value {
4617 : super::upload_queue::NotInitialized::Uninitialized => {
4618 0 : CompactionError::Other(anyhow::anyhow!(value))
4619 : }
4620 : super::upload_queue::NotInitialized::ShuttingDown
4621 0 : | super::upload_queue::NotInitialized::Stopped => CompactionError::ShuttingDown,
4622 : }
4623 0 : }
4624 : }
4625 :
4626 : impl From<super::storage_layer::layer::DownloadError> for CompactionError {
4627 0 : fn from(e: super::storage_layer::layer::DownloadError) -> Self {
4628 0 : match e {
4629 : super::storage_layer::layer::DownloadError::TimelineShutdown
4630 : | super::storage_layer::layer::DownloadError::DownloadCancelled => {
4631 0 : CompactionError::ShuttingDown
4632 : }
4633 : super::storage_layer::layer::DownloadError::ContextAndConfigReallyDeniesDownloads
4634 : | super::storage_layer::layer::DownloadError::DownloadRequired
4635 : | super::storage_layer::layer::DownloadError::NotFile(_)
4636 : | super::storage_layer::layer::DownloadError::DownloadFailed
4637 : | super::storage_layer::layer::DownloadError::PreStatFailed(_) => {
4638 0 : CompactionError::Other(anyhow::anyhow!(e))
4639 : }
4640 : #[cfg(test)]
4641 : super::storage_layer::layer::DownloadError::Failpoint(_) => {
4642 0 : CompactionError::Other(anyhow::anyhow!(e))
4643 : }
4644 : }
4645 0 : }
4646 : }
4647 :
4648 : impl From<layer_manager::Shutdown> for CompactionError {
4649 0 : fn from(_: layer_manager::Shutdown) -> Self {
4650 0 : CompactionError::ShuttingDown
4651 0 : }
4652 : }
4653 :
4654 : #[serde_as]
4655 196 : #[derive(serde::Serialize)]
4656 : struct RecordedDuration(#[serde_as(as = "serde_with::DurationMicroSeconds")] Duration);
4657 :
4658 : #[derive(Default)]
4659 : enum DurationRecorder {
4660 : #[default]
4661 : NotStarted,
4662 : Recorded(RecordedDuration, tokio::time::Instant),
4663 : }
4664 :
4665 : impl DurationRecorder {
4666 504 : fn till_now(&self) -> DurationRecorder {
4667 504 : match self {
4668 : DurationRecorder::NotStarted => {
4669 0 : panic!("must only call on recorded measurements")
4670 : }
4671 504 : DurationRecorder::Recorded(_, ended) => {
4672 504 : let now = tokio::time::Instant::now();
4673 504 : DurationRecorder::Recorded(RecordedDuration(now - *ended), now)
4674 504 : }
4675 504 : }
4676 504 : }
4677 196 : fn into_recorded(self) -> Option<RecordedDuration> {
4678 196 : match self {
4679 0 : DurationRecorder::NotStarted => None,
4680 196 : DurationRecorder::Recorded(recorded, _) => Some(recorded),
4681 : }
4682 196 : }
4683 : }
4684 :
4685 : /// Descriptor for a delta layer used in testing infra. The start/end key/lsn range of the
4686 : /// delta layer might be different from the min/max key/lsn in the delta layer. Therefore,
4687 : /// the layer descriptor requires the user to provide the ranges, which should cover all
4688 : /// keys specified in the `data` field.
4689 : #[cfg(test)]
4690 : #[derive(Clone)]
4691 : pub struct DeltaLayerTestDesc {
4692 : pub lsn_range: Range<Lsn>,
4693 : pub key_range: Range<Key>,
4694 : pub data: Vec<(Key, Lsn, Value)>,
4695 : }
4696 :
4697 : #[cfg(test)]
4698 : impl DeltaLayerTestDesc {
4699 2 : pub fn new(lsn_range: Range<Lsn>, key_range: Range<Key>, data: Vec<(Key, Lsn, Value)>) -> Self {
4700 2 : Self {
4701 2 : lsn_range,
4702 2 : key_range,
4703 2 : data,
4704 2 : }
4705 2 : }
4706 :
4707 72 : pub fn new_with_inferred_key_range(
4708 72 : lsn_range: Range<Lsn>,
4709 72 : data: Vec<(Key, Lsn, Value)>,
4710 72 : ) -> Self {
4711 196 : let key_min = data.iter().map(|(key, _, _)| key).min().unwrap();
4712 196 : let key_max = data.iter().map(|(key, _, _)| key).max().unwrap();
4713 72 : Self {
4714 72 : key_range: (*key_min)..(key_max.next()),
4715 72 : lsn_range,
4716 72 : data,
4717 72 : }
4718 72 : }
4719 :
4720 10 : pub(crate) fn layer_name(&self) -> LayerName {
4721 10 : LayerName::Delta(super::storage_layer::DeltaLayerName {
4722 10 : key_range: self.key_range.clone(),
4723 10 : lsn_range: self.lsn_range.clone(),
4724 10 : })
4725 10 : }
4726 : }
4727 :
4728 : impl Timeline {
4729 28 : async fn finish_compact_batch(
4730 28 : self: &Arc<Self>,
4731 28 : new_deltas: &[ResidentLayer],
4732 28 : new_images: &[ResidentLayer],
4733 28 : layers_to_remove: &[Layer],
4734 28 : ) -> Result<(), CompactionError> {
4735 28 : let mut guard = tokio::select! {
4736 28 : guard = self.layers.write() => guard,
4737 28 : _ = self.cancel.cancelled() => {
4738 0 : return Err(CompactionError::ShuttingDown);
4739 : }
4740 : };
4741 :
4742 28 : let mut duplicated_layers = HashSet::new();
4743 28 :
4744 28 : let mut insert_layers = Vec::with_capacity(new_deltas.len());
4745 :
4746 336 : for l in new_deltas {
4747 308 : if guard.contains(l.as_ref()) {
4748 : // expected in tests
4749 0 : tracing::error!(layer=%l, "duplicated L1 layer");
4750 :
4751 : // good ways to cause a duplicate: we repeatedly error after taking the writelock
4752 : // `guard` on self.layers. as of writing this, there are no error returns except
4753 : // for compact_level0_phase1 creating an L0, which does not happen in practice
4754 : // because we have not implemented L0 => L0 compaction.
4755 0 : duplicated_layers.insert(l.layer_desc().key());
4756 308 : } else if LayerMap::is_l0(&l.layer_desc().key_range, l.layer_desc().is_delta) {
4757 0 : return Err(CompactionError::Other(anyhow::anyhow!("compaction generates a L0 layer file as output, which will cause infinite compaction.")));
4758 308 : } else {
4759 308 : insert_layers.push(l.clone());
4760 308 : }
4761 : }
4762 :
4763 : // only remove those inputs which were not outputs
4764 28 : let remove_layers: Vec<Layer> = layers_to_remove
4765 28 : .iter()
4766 402 : .filter(|l| !duplicated_layers.contains(&l.layer_desc().key()))
4767 28 : .cloned()
4768 28 : .collect();
4769 28 :
4770 28 : if !new_images.is_empty() {
4771 0 : guard
4772 0 : .open_mut()?
4773 0 : .track_new_image_layers(new_images, &self.metrics);
4774 28 : }
4775 :
4776 28 : guard
4777 28 : .open_mut()?
4778 28 : .finish_compact_l0(&remove_layers, &insert_layers, &self.metrics);
4779 28 :
4780 28 : self.remote_client
4781 28 : .schedule_compaction_update(&remove_layers, new_deltas)?;
4782 :
4783 28 : drop_wlock(guard);
4784 28 :
4785 28 : Ok(())
4786 28 : }
4787 :
4788 0 : async fn rewrite_layers(
4789 0 : self: &Arc<Self>,
4790 0 : mut replace_layers: Vec<(Layer, ResidentLayer)>,
4791 0 : mut drop_layers: Vec<Layer>,
4792 0 : ) -> Result<(), CompactionError> {
4793 0 : let mut guard = self.layers.write().await;
4794 :
4795 : // Trim our lists in case our caller (compaction) raced with someone else (GC) removing layers: we want
4796 : // to avoid double-removing, and avoid rewriting something that was removed.
4797 0 : replace_layers.retain(|(l, _)| guard.contains(l));
4798 0 : drop_layers.retain(|l| guard.contains(l));
4799 0 :
4800 0 : guard
4801 0 : .open_mut()?
4802 0 : .rewrite_layers(&replace_layers, &drop_layers, &self.metrics);
4803 0 :
4804 0 : let upload_layers: Vec<_> = replace_layers.into_iter().map(|r| r.1).collect();
4805 0 :
4806 0 : self.remote_client
4807 0 : .schedule_compaction_update(&drop_layers, &upload_layers)?;
4808 :
4809 0 : Ok(())
4810 0 : }
4811 :
4812 : /// Schedules the uploads of the given image layers
4813 364 : fn upload_new_image_layers(
4814 364 : self: &Arc<Self>,
4815 364 : new_images: impl IntoIterator<Item = ResidentLayer>,
4816 364 : ) -> Result<(), super::upload_queue::NotInitialized> {
4817 390 : for layer in new_images {
4818 26 : self.remote_client.schedule_layer_file_upload(layer)?;
4819 : }
4820 : // should any new image layer been created, not uploading index_part will
4821 : // result in a mismatch between remote_physical_size and layermap calculated
4822 : // size, which will fail some tests, but should not be an issue otherwise.
4823 364 : self.remote_client
4824 364 : .schedule_index_upload_for_file_changes()?;
4825 364 : Ok(())
4826 364 : }
4827 :
4828 0 : async fn find_gc_time_cutoff(
4829 0 : &self,
4830 0 : pitr: Duration,
4831 0 : cancel: &CancellationToken,
4832 0 : ctx: &RequestContext,
4833 0 : ) -> Result<Option<Lsn>, PageReconstructError> {
4834 0 : debug_assert_current_span_has_tenant_and_timeline_id();
4835 0 : if self.shard_identity.is_shard_zero() {
4836 : // Shard Zero has SLRU data and can calculate the PITR time -> LSN mapping itself
4837 0 : let now = SystemTime::now();
4838 0 : let time_range = if pitr == Duration::ZERO {
4839 0 : humantime::parse_duration(DEFAULT_PITR_INTERVAL).expect("constant is invalid")
4840 : } else {
4841 0 : pitr
4842 : };
4843 :
4844 : // If PITR is so large or `now` is so small that this underflows, we will retain no history (highly unexpected case)
4845 0 : let time_cutoff = now.checked_sub(time_range).unwrap_or(now);
4846 0 : let timestamp = to_pg_timestamp(time_cutoff);
4847 :
4848 0 : let time_cutoff = match self.find_lsn_for_timestamp(timestamp, cancel, ctx).await? {
4849 0 : LsnForTimestamp::Present(lsn) => Some(lsn),
4850 0 : LsnForTimestamp::Future(lsn) => {
4851 0 : // The timestamp is in the future. That sounds impossible,
4852 0 : // but what it really means is that there hasn't been
4853 0 : // any commits since the cutoff timestamp.
4854 0 : //
4855 0 : // In this case we should use the LSN of the most recent commit,
4856 0 : // which is implicitly the last LSN in the log.
4857 0 : debug!("future({})", lsn);
4858 0 : Some(self.get_last_record_lsn())
4859 : }
4860 0 : LsnForTimestamp::Past(lsn) => {
4861 0 : debug!("past({})", lsn);
4862 0 : None
4863 : }
4864 0 : LsnForTimestamp::NoData(lsn) => {
4865 0 : debug!("nodata({})", lsn);
4866 0 : None
4867 : }
4868 : };
4869 0 : Ok(time_cutoff)
4870 : } else {
4871 : // Shards other than shard zero cannot do timestamp->lsn lookups, and must instead learn their GC cutoff
4872 : // from shard zero's index. The index doesn't explicitly tell us the time cutoff, but we may assume that
4873 : // the point up to which shard zero's last_gc_cutoff has advanced will either be the time cutoff, or a
4874 : // space cutoff that we would also have respected ourselves.
4875 0 : match self
4876 0 : .remote_client
4877 0 : .download_foreign_index(ShardNumber(0), cancel)
4878 0 : .await
4879 : {
4880 0 : Ok((index_part, index_generation, _index_mtime)) => {
4881 0 : tracing::info!("GC loaded shard zero metadata (gen {index_generation:?}): latest_gc_cutoff_lsn: {}",
4882 0 : index_part.metadata.latest_gc_cutoff_lsn());
4883 0 : Ok(Some(index_part.metadata.latest_gc_cutoff_lsn()))
4884 : }
4885 : Err(DownloadError::NotFound) => {
4886 : // This is unexpected, because during timeline creations shard zero persists to remote
4887 : // storage before other shards are called, and during timeline deletion non-zeroth shards are
4888 : // deleted before the zeroth one. However, it should be harmless: if we somehow end up in this
4889 : // state, then shard zero should _eventually_ write an index when it GCs.
4890 0 : tracing::warn!("GC couldn't find shard zero's index for timeline");
4891 0 : Ok(None)
4892 : }
4893 0 : Err(e) => {
4894 0 : // TODO: this function should return a different error type than page reconstruct error
4895 0 : Err(PageReconstructError::Other(anyhow::anyhow!(e)))
4896 : }
4897 : }
4898 :
4899 : // TODO: after reading shard zero's GC cutoff, we should validate its generation with the storage
4900 : // controller. Otherwise, it is possible that we see the GC cutoff go backwards while shard zero
4901 : // is going through a migration if we read the old location's index and it has GC'd ahead of the
4902 : // new location. This is legal in principle, but problematic in practice because it might result
4903 : // in a timeline creation succeeding on shard zero ('s new location) but then failing on other shards
4904 : // because they have GC'd past the branch point.
4905 : }
4906 0 : }
4907 :
4908 : /// Find the Lsns above which layer files need to be retained on
4909 : /// garbage collection.
4910 : ///
4911 : /// We calculate two cutoffs, one based on time and one based on WAL size. `pitr`
4912 : /// controls the time cutoff (or ZERO to disable time-based retention), and `space_cutoff` controls
4913 : /// the space-based retention.
4914 : ///
4915 : /// This function doesn't simply to calculate time & space based retention: it treats time-based
4916 : /// retention as authoritative if enabled, and falls back to space-based retention if calculating
4917 : /// the LSN for a time point isn't possible. Therefore the GcCutoffs::horizon in the response might
4918 : /// be different to the `space_cutoff` input. Callers should treat the min() of the two cutoffs
4919 : /// in the response as the GC cutoff point for the timeline.
4920 4 : #[instrument(skip_all, fields(timeline_id=%self.timeline_id))]
4921 : pub(super) async fn find_gc_cutoffs(
4922 : &self,
4923 : space_cutoff: Lsn,
4924 : pitr: Duration,
4925 : cancel: &CancellationToken,
4926 : ctx: &RequestContext,
4927 : ) -> Result<GcCutoffs, PageReconstructError> {
4928 : let _timer = self
4929 : .metrics
4930 : .find_gc_cutoffs_histo
4931 : .start_timer()
4932 : .record_on_drop();
4933 :
4934 : pausable_failpoint!("Timeline::find_gc_cutoffs-pausable");
4935 :
4936 : if cfg!(test) {
4937 : // Unit tests which specify zero PITR interval expect to avoid doing any I/O for timestamp lookup
4938 : if pitr == Duration::ZERO {
4939 : return Ok(GcCutoffs {
4940 : time: self.get_last_record_lsn(),
4941 : space: space_cutoff,
4942 : });
4943 : }
4944 : }
4945 :
4946 : // Calculate a time-based limit on how much to retain:
4947 : // - if PITR interval is set, then this is our cutoff.
4948 : // - if PITR interval is not set, then we do a lookup
4949 : // based on DEFAULT_PITR_INTERVAL, so that size-based retention does not result in keeping history around permanently on idle databases.
4950 : let time_cutoff = self.find_gc_time_cutoff(pitr, cancel, ctx).await?;
4951 :
4952 : Ok(match (pitr, time_cutoff) {
4953 : (Duration::ZERO, Some(time_cutoff)) => {
4954 : // PITR is not set. Retain the size-based limit, or the default time retention,
4955 : // whichever requires less data.
4956 : GcCutoffs {
4957 : time: self.get_last_record_lsn(),
4958 : space: std::cmp::max(time_cutoff, space_cutoff),
4959 : }
4960 : }
4961 : (Duration::ZERO, None) => {
4962 : // PITR is not set, and time lookup failed
4963 : GcCutoffs {
4964 : time: self.get_last_record_lsn(),
4965 : space: space_cutoff,
4966 : }
4967 : }
4968 : (_, None) => {
4969 : // PITR interval is set & we didn't look up a timestamp successfully. Conservatively assume PITR
4970 : // cannot advance beyond what was already GC'd, and respect space-based retention
4971 : GcCutoffs {
4972 : time: *self.get_latest_gc_cutoff_lsn(),
4973 : space: space_cutoff,
4974 : }
4975 : }
4976 : (_, Some(time_cutoff)) => {
4977 : // PITR interval is set and we looked up timestamp successfully. Ignore
4978 : // size based retention and make time cutoff authoritative
4979 : GcCutoffs {
4980 : time: time_cutoff,
4981 : space: time_cutoff,
4982 : }
4983 : }
4984 : })
4985 : }
4986 :
4987 : /// Garbage collect layer files on a timeline that are no longer needed.
4988 : ///
4989 : /// Currently, we don't make any attempt at removing unneeded page versions
4990 : /// within a layer file. We can only remove the whole file if it's fully
4991 : /// obsolete.
4992 4 : pub(super) async fn gc(&self) -> Result<GcResult, GcError> {
4993 : // this is most likely the background tasks, but it might be the spawned task from
4994 : // immediate_gc
4995 4 : let _g = tokio::select! {
4996 4 : guard = self.gc_lock.lock() => guard,
4997 4 : _ = self.cancel.cancelled() => return Ok(GcResult::default()),
4998 : };
4999 4 : let timer = self.metrics.garbage_collect_histo.start_timer();
5000 4 :
5001 4 : fail_point!("before-timeline-gc");
5002 4 :
5003 4 : // Is the timeline being deleted?
5004 4 : if self.is_stopping() {
5005 0 : return Err(GcError::TimelineCancelled);
5006 4 : }
5007 4 :
5008 4 : let (space_cutoff, time_cutoff, retain_lsns, max_lsn_with_valid_lease) = {
5009 4 : let gc_info = self.gc_info.read().unwrap();
5010 4 :
5011 4 : let space_cutoff = min(gc_info.cutoffs.space, self.get_disk_consistent_lsn());
5012 4 : let time_cutoff = gc_info.cutoffs.time;
5013 4 : let retain_lsns = gc_info
5014 4 : .retain_lsns
5015 4 : .iter()
5016 4 : .map(|(lsn, _child_id, _is_offloaded)| *lsn)
5017 4 : .collect();
5018 4 :
5019 4 : // Gets the maximum LSN that holds the valid lease.
5020 4 : //
5021 4 : // Caveat: `refresh_gc_info` is in charged of updating the lease map.
5022 4 : // Here, we do not check for stale leases again.
5023 4 : let max_lsn_with_valid_lease = gc_info.leases.last_key_value().map(|(lsn, _)| *lsn);
5024 4 :
5025 4 : (
5026 4 : space_cutoff,
5027 4 : time_cutoff,
5028 4 : retain_lsns,
5029 4 : max_lsn_with_valid_lease,
5030 4 : )
5031 4 : };
5032 4 :
5033 4 : let mut new_gc_cutoff = Lsn::min(space_cutoff, time_cutoff);
5034 4 : let standby_horizon = self.standby_horizon.load();
5035 4 : // Hold GC for the standby, but as a safety guard do it only within some
5036 4 : // reasonable lag.
5037 4 : if standby_horizon != Lsn::INVALID {
5038 0 : if let Some(standby_lag) = new_gc_cutoff.checked_sub(standby_horizon) {
5039 : const MAX_ALLOWED_STANDBY_LAG: u64 = 10u64 << 30; // 10 GB
5040 0 : if standby_lag.0 < MAX_ALLOWED_STANDBY_LAG {
5041 0 : new_gc_cutoff = Lsn::min(standby_horizon, new_gc_cutoff);
5042 0 : trace!("holding off GC for standby apply LSN {}", standby_horizon);
5043 : } else {
5044 0 : warn!(
5045 0 : "standby is lagging for more than {}MB, not holding gc for it",
5046 0 : MAX_ALLOWED_STANDBY_LAG / 1024 / 1024
5047 : )
5048 : }
5049 0 : }
5050 4 : }
5051 :
5052 : // Reset standby horizon to ignore it if it is not updated till next GC.
5053 : // It is an easy way to unset it when standby disappears without adding
5054 : // more conf options.
5055 4 : self.standby_horizon.store(Lsn::INVALID);
5056 4 : self.metrics
5057 4 : .standby_horizon_gauge
5058 4 : .set(Lsn::INVALID.0 as i64);
5059 :
5060 4 : let res = self
5061 4 : .gc_timeline(
5062 4 : space_cutoff,
5063 4 : time_cutoff,
5064 4 : retain_lsns,
5065 4 : max_lsn_with_valid_lease,
5066 4 : new_gc_cutoff,
5067 4 : )
5068 4 : .instrument(
5069 4 : info_span!("gc_timeline", timeline_id = %self.timeline_id, cutoff = %new_gc_cutoff),
5070 : )
5071 0 : .await?;
5072 :
5073 : // only record successes
5074 4 : timer.stop_and_record();
5075 4 :
5076 4 : Ok(res)
5077 4 : }
5078 :
5079 4 : async fn gc_timeline(
5080 4 : &self,
5081 4 : space_cutoff: Lsn,
5082 4 : time_cutoff: Lsn,
5083 4 : retain_lsns: Vec<Lsn>,
5084 4 : max_lsn_with_valid_lease: Option<Lsn>,
5085 4 : new_gc_cutoff: Lsn,
5086 4 : ) -> Result<GcResult, GcError> {
5087 4 : // FIXME: if there is an ongoing detach_from_ancestor, we should just skip gc
5088 4 :
5089 4 : let now = SystemTime::now();
5090 4 : let mut result: GcResult = GcResult::default();
5091 4 :
5092 4 : // Nothing to GC. Return early.
5093 4 : let latest_gc_cutoff = *self.get_latest_gc_cutoff_lsn();
5094 4 : if latest_gc_cutoff >= new_gc_cutoff {
5095 0 : info!(
5096 0 : "Nothing to GC: new_gc_cutoff_lsn {new_gc_cutoff}, latest_gc_cutoff_lsn {latest_gc_cutoff}",
5097 : );
5098 0 : return Ok(result);
5099 4 : }
5100 :
5101 : // We need to ensure that no one tries to read page versions or create
5102 : // branches at a point before latest_gc_cutoff_lsn. See branch_timeline()
5103 : // for details. This will block until the old value is no longer in use.
5104 : //
5105 : // The GC cutoff should only ever move forwards.
5106 4 : let waitlist = {
5107 4 : let write_guard = self.latest_gc_cutoff_lsn.lock_for_write();
5108 4 : if *write_guard > new_gc_cutoff {
5109 0 : return Err(GcError::BadLsn {
5110 0 : why: format!(
5111 0 : "Cannot move GC cutoff LSN backwards (was {}, new {})",
5112 0 : *write_guard, new_gc_cutoff
5113 0 : ),
5114 0 : });
5115 4 : }
5116 4 :
5117 4 : write_guard.store_and_unlock(new_gc_cutoff)
5118 4 : };
5119 4 : waitlist.wait().await;
5120 :
5121 4 : info!("GC starting");
5122 :
5123 4 : debug!("retain_lsns: {:?}", retain_lsns);
5124 :
5125 4 : let mut layers_to_remove = Vec::new();
5126 :
5127 : // Scan all layers in the timeline (remote or on-disk).
5128 : //
5129 : // Garbage collect the layer if all conditions are satisfied:
5130 : // 1. it is older than cutoff LSN;
5131 : // 2. it is older than PITR interval;
5132 : // 3. it doesn't need to be retained for 'retain_lsns';
5133 : // 4. it does not need to be kept for LSNs holding valid leases.
5134 : // 5. newer on-disk image layers cover the layer's whole key range
5135 : //
5136 : // TODO holding a write lock is too agressive and avoidable
5137 4 : let mut guard = self.layers.write().await;
5138 4 : let layers = guard.layer_map()?;
5139 24 : 'outer: for l in layers.iter_historic_layers() {
5140 24 : result.layers_total += 1;
5141 24 :
5142 24 : // 1. Is it newer than GC horizon cutoff point?
5143 24 : if l.get_lsn_range().end > space_cutoff {
5144 2 : info!(
5145 0 : "keeping {} because it's newer than space_cutoff {}",
5146 0 : l.layer_name(),
5147 : space_cutoff,
5148 : );
5149 2 : result.layers_needed_by_cutoff += 1;
5150 2 : continue 'outer;
5151 22 : }
5152 22 :
5153 22 : // 2. It is newer than PiTR cutoff point?
5154 22 : if l.get_lsn_range().end > time_cutoff {
5155 0 : info!(
5156 0 : "keeping {} because it's newer than time_cutoff {}",
5157 0 : l.layer_name(),
5158 : time_cutoff,
5159 : );
5160 0 : result.layers_needed_by_pitr += 1;
5161 0 : continue 'outer;
5162 22 : }
5163 :
5164 : // 3. Is it needed by a child branch?
5165 : // NOTE With that we would keep data that
5166 : // might be referenced by child branches forever.
5167 : // We can track this in child timeline GC and delete parent layers when
5168 : // they are no longer needed. This might be complicated with long inheritance chains.
5169 : //
5170 : // TODO Vec is not a great choice for `retain_lsns`
5171 22 : for retain_lsn in &retain_lsns {
5172 : // start_lsn is inclusive
5173 0 : if &l.get_lsn_range().start <= retain_lsn {
5174 0 : info!(
5175 0 : "keeping {} because it's still might be referenced by child branch forked at {} is_dropped: xx is_incremental: {}",
5176 0 : l.layer_name(),
5177 0 : retain_lsn,
5178 0 : l.is_incremental(),
5179 : );
5180 0 : result.layers_needed_by_branches += 1;
5181 0 : continue 'outer;
5182 0 : }
5183 : }
5184 :
5185 : // 4. Is there a valid lease that requires us to keep this layer?
5186 22 : if let Some(lsn) = &max_lsn_with_valid_lease {
5187 : // keep if layer start <= any of the lease
5188 18 : if &l.get_lsn_range().start <= lsn {
5189 14 : info!(
5190 0 : "keeping {} because there is a valid lease preventing GC at {}",
5191 0 : l.layer_name(),
5192 : lsn,
5193 : );
5194 14 : result.layers_needed_by_leases += 1;
5195 14 : continue 'outer;
5196 4 : }
5197 4 : }
5198 :
5199 : // 5. Is there a later on-disk layer for this relation?
5200 : //
5201 : // The end-LSN is exclusive, while disk_consistent_lsn is
5202 : // inclusive. For example, if disk_consistent_lsn is 100, it is
5203 : // OK for a delta layer to have end LSN 101, but if the end LSN
5204 : // is 102, then it might not have been fully flushed to disk
5205 : // before crash.
5206 : //
5207 : // For example, imagine that the following layers exist:
5208 : //
5209 : // 1000 - image (A)
5210 : // 1000-2000 - delta (B)
5211 : // 2000 - image (C)
5212 : // 2000-3000 - delta (D)
5213 : // 3000 - image (E)
5214 : //
5215 : // If GC horizon is at 2500, we can remove layers A and B, but
5216 : // we cannot remove C, even though it's older than 2500, because
5217 : // the delta layer 2000-3000 depends on it.
5218 8 : if !layers
5219 8 : .image_layer_exists(&l.get_key_range(), &(l.get_lsn_range().end..new_gc_cutoff))
5220 : {
5221 6 : info!("keeping {} because it is the latest layer", l.layer_name());
5222 6 : result.layers_not_updated += 1;
5223 6 : continue 'outer;
5224 2 : }
5225 2 :
5226 2 : // We didn't find any reason to keep this file, so remove it.
5227 2 : info!(
5228 0 : "garbage collecting {} is_dropped: xx is_incremental: {}",
5229 0 : l.layer_name(),
5230 0 : l.is_incremental(),
5231 : );
5232 2 : layers_to_remove.push(l);
5233 : }
5234 :
5235 4 : if !layers_to_remove.is_empty() {
5236 : // Persist the new GC cutoff value before we actually remove anything.
5237 : // This unconditionally schedules also an index_part.json update, even though, we will
5238 : // be doing one a bit later with the unlinked gc'd layers.
5239 2 : let disk_consistent_lsn = self.disk_consistent_lsn.load();
5240 2 : self.schedule_uploads(disk_consistent_lsn, None)
5241 2 : .map_err(|e| {
5242 0 : if self.cancel.is_cancelled() {
5243 0 : GcError::TimelineCancelled
5244 : } else {
5245 0 : GcError::Remote(e)
5246 : }
5247 2 : })?;
5248 :
5249 2 : let gc_layers = layers_to_remove
5250 2 : .iter()
5251 2 : .map(|x| guard.get_from_desc(x))
5252 2 : .collect::<Vec<Layer>>();
5253 2 :
5254 2 : result.layers_removed = gc_layers.len() as u64;
5255 2 :
5256 2 : self.remote_client.schedule_gc_update(&gc_layers)?;
5257 :
5258 2 : guard.open_mut()?.finish_gc_timeline(&gc_layers);
5259 2 :
5260 2 : #[cfg(feature = "testing")]
5261 2 : {
5262 2 : result.doomed_layers = gc_layers;
5263 2 : }
5264 2 : }
5265 :
5266 4 : info!(
5267 0 : "GC completed removing {} layers, cutoff {}",
5268 : result.layers_removed, new_gc_cutoff
5269 : );
5270 :
5271 4 : result.elapsed = now.elapsed().unwrap_or(Duration::ZERO);
5272 4 : Ok(result)
5273 4 : }
5274 :
5275 : /// Reconstruct a value, using the given base image and WAL records in 'data'.
5276 667498 : async fn reconstruct_value(
5277 667498 : &self,
5278 667498 : key: Key,
5279 667498 : request_lsn: Lsn,
5280 667498 : mut data: ValueReconstructState,
5281 667498 : ) -> Result<Bytes, PageReconstructError> {
5282 667498 : // Perform WAL redo if needed
5283 667498 : data.records.reverse();
5284 667498 :
5285 667498 : // If we have a page image, and no WAL, we're all set
5286 667498 : if data.records.is_empty() {
5287 667088 : if let Some((img_lsn, img)) = &data.img {
5288 667088 : trace!(
5289 0 : "found page image for key {} at {}, no WAL redo required, req LSN {}",
5290 : key,
5291 : img_lsn,
5292 : request_lsn,
5293 : );
5294 667088 : Ok(img.clone())
5295 : } else {
5296 0 : Err(PageReconstructError::from(anyhow!(
5297 0 : "base image for {key} at {request_lsn} not found"
5298 0 : )))
5299 : }
5300 : } else {
5301 : // We need to do WAL redo.
5302 : //
5303 : // If we don't have a base image, then the oldest WAL record better initialize
5304 : // the page
5305 410 : if data.img.is_none() && !data.records.first().unwrap().1.will_init() {
5306 0 : Err(PageReconstructError::from(anyhow!(
5307 0 : "Base image for {} at {} not found, but got {} WAL records",
5308 0 : key,
5309 0 : request_lsn,
5310 0 : data.records.len()
5311 0 : )))
5312 : } else {
5313 410 : if data.img.is_some() {
5314 344 : trace!(
5315 0 : "found {} WAL records and a base image for {} at {}, performing WAL redo",
5316 0 : data.records.len(),
5317 : key,
5318 : request_lsn
5319 : );
5320 : } else {
5321 66 : trace!("found {} WAL records that will init the page for {} at {}, performing WAL redo", data.records.len(), key, request_lsn);
5322 : };
5323 410 : let res = self
5324 410 : .walredo_mgr
5325 410 : .as_ref()
5326 410 : .context("timeline has no walredo manager")
5327 410 : .map_err(PageReconstructError::WalRedo)?
5328 410 : .request_redo(key, request_lsn, data.img, data.records, self.pg_version)
5329 0 : .await;
5330 410 : let img = match res {
5331 410 : Ok(img) => img,
5332 0 : Err(walredo::Error::Cancelled) => return Err(PageReconstructError::Cancelled),
5333 0 : Err(walredo::Error::Other(e)) => {
5334 0 : return Err(PageReconstructError::WalRedo(
5335 0 : e.context("reconstruct a page image"),
5336 0 : ))
5337 : }
5338 : };
5339 410 : Ok(img)
5340 : }
5341 : }
5342 667498 : }
5343 :
5344 0 : pub(crate) async fn spawn_download_all_remote_layers(
5345 0 : self: Arc<Self>,
5346 0 : request: DownloadRemoteLayersTaskSpawnRequest,
5347 0 : ) -> Result<DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskInfo> {
5348 : use pageserver_api::models::DownloadRemoteLayersTaskState;
5349 :
5350 : // this is not really needed anymore; it has tests which really check the return value from
5351 : // http api. it would be better not to maintain this anymore.
5352 :
5353 0 : let mut status_guard = self.download_all_remote_layers_task_info.write().unwrap();
5354 0 : if let Some(st) = &*status_guard {
5355 0 : match &st.state {
5356 : DownloadRemoteLayersTaskState::Running => {
5357 0 : return Err(st.clone());
5358 : }
5359 : DownloadRemoteLayersTaskState::ShutDown
5360 0 : | DownloadRemoteLayersTaskState::Completed => {
5361 0 : *status_guard = None;
5362 0 : }
5363 : }
5364 0 : }
5365 :
5366 0 : let self_clone = Arc::clone(&self);
5367 0 : let task_id = task_mgr::spawn(
5368 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
5369 0 : task_mgr::TaskKind::DownloadAllRemoteLayers,
5370 0 : self.tenant_shard_id,
5371 0 : Some(self.timeline_id),
5372 0 : "download all remote layers task",
5373 0 : async move {
5374 0 : self_clone.download_all_remote_layers(request).await;
5375 0 : let mut status_guard = self_clone.download_all_remote_layers_task_info.write().unwrap();
5376 0 : match &mut *status_guard {
5377 : None => {
5378 0 : warn!("tasks status is supposed to be Some(), since we are running");
5379 : }
5380 0 : Some(st) => {
5381 0 : let exp_task_id = format!("{}", task_mgr::current_task_id().unwrap());
5382 0 : if st.task_id != exp_task_id {
5383 0 : warn!("task id changed while we were still running, expecting {} but have {}", exp_task_id, st.task_id);
5384 0 : } else {
5385 0 : st.state = DownloadRemoteLayersTaskState::Completed;
5386 0 : }
5387 : }
5388 : };
5389 0 : Ok(())
5390 0 : }
5391 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))
5392 : );
5393 :
5394 0 : let initial_info = DownloadRemoteLayersTaskInfo {
5395 0 : task_id: format!("{task_id}"),
5396 0 : state: DownloadRemoteLayersTaskState::Running,
5397 0 : total_layer_count: 0,
5398 0 : successful_download_count: 0,
5399 0 : failed_download_count: 0,
5400 0 : };
5401 0 : *status_guard = Some(initial_info.clone());
5402 0 :
5403 0 : Ok(initial_info)
5404 0 : }
5405 :
5406 0 : async fn download_all_remote_layers(
5407 0 : self: &Arc<Self>,
5408 0 : request: DownloadRemoteLayersTaskSpawnRequest,
5409 0 : ) {
5410 : use pageserver_api::models::DownloadRemoteLayersTaskState;
5411 :
5412 0 : let remaining = {
5413 0 : let guard = self.layers.read().await;
5414 0 : let Ok(lm) = guard.layer_map() else {
5415 : // technically here we could look into iterating accessible layers, but downloading
5416 : // all layers of a shutdown timeline makes no sense regardless.
5417 0 : tracing::info!("attempted to download all layers of shutdown timeline");
5418 0 : return;
5419 : };
5420 0 : lm.iter_historic_layers()
5421 0 : .map(|desc| guard.get_from_desc(&desc))
5422 0 : .collect::<Vec<_>>()
5423 0 : };
5424 0 : let total_layer_count = remaining.len();
5425 :
5426 : macro_rules! lock_status {
5427 : ($st:ident) => {
5428 : let mut st = self.download_all_remote_layers_task_info.write().unwrap();
5429 : let st = st
5430 : .as_mut()
5431 : .expect("this function is only called after the task has been spawned");
5432 : assert_eq!(
5433 : st.task_id,
5434 : format!(
5435 : "{}",
5436 : task_mgr::current_task_id().expect("we run inside a task_mgr task")
5437 : )
5438 : );
5439 : let $st = st;
5440 : };
5441 : }
5442 :
5443 : {
5444 0 : lock_status!(st);
5445 0 : st.total_layer_count = total_layer_count as u64;
5446 0 : }
5447 0 :
5448 0 : let mut remaining = remaining.into_iter();
5449 0 : let mut have_remaining = true;
5450 0 : let mut js = tokio::task::JoinSet::new();
5451 0 :
5452 0 : let cancel = task_mgr::shutdown_token();
5453 0 :
5454 0 : let limit = request.max_concurrent_downloads;
5455 :
5456 : loop {
5457 0 : while js.len() < limit.get() && have_remaining && !cancel.is_cancelled() {
5458 0 : let Some(next) = remaining.next() else {
5459 0 : have_remaining = false;
5460 0 : break;
5461 : };
5462 :
5463 0 : let span = tracing::info_span!("download", layer = %next);
5464 :
5465 0 : js.spawn(
5466 0 : async move {
5467 0 : let res = next.download().await;
5468 0 : (next, res)
5469 0 : }
5470 0 : .instrument(span),
5471 0 : );
5472 0 : }
5473 :
5474 0 : while let Some(res) = js.join_next().await {
5475 0 : match res {
5476 : Ok((_, Ok(_))) => {
5477 0 : lock_status!(st);
5478 0 : st.successful_download_count += 1;
5479 : }
5480 0 : Ok((layer, Err(e))) => {
5481 0 : tracing::error!(%layer, "download failed: {e:#}");
5482 0 : lock_status!(st);
5483 0 : st.failed_download_count += 1;
5484 : }
5485 0 : Err(je) if je.is_cancelled() => unreachable!("not used here"),
5486 0 : Err(je) if je.is_panic() => {
5487 0 : lock_status!(st);
5488 0 : st.failed_download_count += 1;
5489 : }
5490 0 : Err(je) => tracing::warn!("unknown joinerror: {je:?}"),
5491 : }
5492 : }
5493 :
5494 0 : if js.is_empty() && (!have_remaining || cancel.is_cancelled()) {
5495 0 : break;
5496 0 : }
5497 : }
5498 :
5499 : {
5500 0 : lock_status!(st);
5501 0 : st.state = DownloadRemoteLayersTaskState::Completed;
5502 : }
5503 0 : }
5504 :
5505 0 : pub(crate) fn get_download_all_remote_layers_task_info(
5506 0 : &self,
5507 0 : ) -> Option<DownloadRemoteLayersTaskInfo> {
5508 0 : self.download_all_remote_layers_task_info
5509 0 : .read()
5510 0 : .unwrap()
5511 0 : .clone()
5512 0 : }
5513 : }
5514 :
5515 : impl Timeline {
5516 : /// Returns non-remote layers for eviction.
5517 0 : pub(crate) async fn get_local_layers_for_disk_usage_eviction(&self) -> DiskUsageEvictionInfo {
5518 0 : let guard = self.layers.read().await;
5519 0 : let mut max_layer_size: Option<u64> = None;
5520 0 :
5521 0 : let resident_layers = guard
5522 0 : .likely_resident_layers()
5523 0 : .map(|layer| {
5524 0 : let file_size = layer.layer_desc().file_size;
5525 0 : max_layer_size = max_layer_size.map_or(Some(file_size), |m| Some(m.max(file_size)));
5526 0 :
5527 0 : let last_activity_ts = layer.latest_activity();
5528 0 :
5529 0 : EvictionCandidate {
5530 0 : layer: layer.to_owned().into(),
5531 0 : last_activity_ts,
5532 0 : relative_last_activity: finite_f32::FiniteF32::ZERO,
5533 0 : visibility: layer.visibility(),
5534 0 : }
5535 0 : })
5536 0 : .collect();
5537 0 :
5538 0 : DiskUsageEvictionInfo {
5539 0 : max_layer_size,
5540 0 : resident_layers,
5541 0 : }
5542 0 : }
5543 :
5544 1730 : pub(crate) fn get_shard_index(&self) -> ShardIndex {
5545 1730 : ShardIndex {
5546 1730 : shard_number: self.tenant_shard_id.shard_number,
5547 1730 : shard_count: self.tenant_shard_id.shard_count,
5548 1730 : }
5549 1730 : }
5550 :
5551 : /// Persistently blocks gc for `Manual` reason.
5552 : ///
5553 : /// Returns true if no such block existed before, false otherwise.
5554 0 : pub(crate) async fn block_gc(&self, tenant: &super::Tenant) -> anyhow::Result<bool> {
5555 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
5556 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
5557 0 : tenant.gc_block.insert(self, GcBlockingReason::Manual).await
5558 0 : }
5559 :
5560 : /// Persistently unblocks gc for `Manual` reason.
5561 0 : pub(crate) async fn unblock_gc(&self, tenant: &super::Tenant) -> anyhow::Result<()> {
5562 : use crate::tenant::remote_timeline_client::index::GcBlockingReason;
5563 0 : assert_eq!(self.tenant_shard_id, tenant.tenant_shard_id);
5564 0 : tenant.gc_block.remove(self, GcBlockingReason::Manual).await
5565 0 : }
5566 :
5567 : #[cfg(test)]
5568 40 : pub(super) fn force_advance_lsn(self: &Arc<Timeline>, new_lsn: Lsn) {
5569 40 : self.last_record_lsn.advance(new_lsn);
5570 40 : }
5571 :
5572 : #[cfg(test)]
5573 2 : pub(super) fn force_set_disk_consistent_lsn(&self, new_value: Lsn) {
5574 2 : self.disk_consistent_lsn.store(new_value);
5575 2 : }
5576 :
5577 : /// Force create an image layer and place it into the layer map.
5578 : ///
5579 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
5580 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
5581 : /// placed into the layer map in one run AND be validated.
5582 : #[cfg(test)]
5583 52 : pub(super) async fn force_create_image_layer(
5584 52 : self: &Arc<Timeline>,
5585 52 : lsn: Lsn,
5586 52 : mut images: Vec<(Key, Bytes)>,
5587 52 : check_start_lsn: Option<Lsn>,
5588 52 : ctx: &RequestContext,
5589 52 : ) -> anyhow::Result<()> {
5590 52 : let last_record_lsn = self.get_last_record_lsn();
5591 52 : assert!(
5592 52 : lsn <= last_record_lsn,
5593 0 : "advance last record lsn before inserting a layer, lsn={lsn}, last_record_lsn={last_record_lsn}"
5594 : );
5595 52 : if let Some(check_start_lsn) = check_start_lsn {
5596 52 : assert!(lsn >= check_start_lsn);
5597 0 : }
5598 126 : images.sort_unstable_by(|(ka, _), (kb, _)| ka.cmp(kb));
5599 52 : let min_key = *images.first().map(|(k, _)| k).unwrap();
5600 52 : let end_key = images.last().map(|(k, _)| k).unwrap().next();
5601 52 : let mut image_layer_writer = ImageLayerWriter::new(
5602 52 : self.conf,
5603 52 : self.timeline_id,
5604 52 : self.tenant_shard_id,
5605 52 : &(min_key..end_key),
5606 52 : lsn,
5607 52 : ctx,
5608 52 : )
5609 26 : .await?;
5610 230 : for (key, img) in images {
5611 178 : image_layer_writer.put_image(key, img, ctx).await?;
5612 : }
5613 104 : let (desc, path) = image_layer_writer.finish(ctx).await?;
5614 52 : let image_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
5615 52 : info!("force created image layer {}", image_layer.local_path());
5616 : {
5617 52 : let mut guard = self.layers.write().await;
5618 52 : guard.open_mut().unwrap().force_insert_layer(image_layer);
5619 52 : }
5620 52 :
5621 52 : Ok(())
5622 52 : }
5623 :
5624 : /// Force create a delta layer and place it into the layer map.
5625 : ///
5626 : /// DO NOT use this function directly. Use [`Tenant::branch_timeline_test_with_layers`]
5627 : /// or [`Tenant::create_test_timeline_with_layers`] to ensure all these layers are
5628 : /// placed into the layer map in one run AND be validated.
5629 : #[cfg(test)]
5630 74 : pub(super) async fn force_create_delta_layer(
5631 74 : self: &Arc<Timeline>,
5632 74 : mut deltas: DeltaLayerTestDesc,
5633 74 : check_start_lsn: Option<Lsn>,
5634 74 : ctx: &RequestContext,
5635 74 : ) -> anyhow::Result<()> {
5636 74 : let last_record_lsn = self.get_last_record_lsn();
5637 74 : deltas
5638 74 : .data
5639 124 : .sort_unstable_by(|(ka, la, _), (kb, lb, _)| (ka, la).cmp(&(kb, lb)));
5640 74 : assert!(deltas.data.first().unwrap().0 >= deltas.key_range.start);
5641 74 : assert!(deltas.data.last().unwrap().0 < deltas.key_range.end);
5642 272 : for (_, lsn, _) in &deltas.data {
5643 198 : assert!(deltas.lsn_range.start <= *lsn && *lsn < deltas.lsn_range.end);
5644 : }
5645 74 : assert!(
5646 74 : deltas.lsn_range.end <= last_record_lsn,
5647 0 : "advance last record lsn before inserting a layer, end_lsn={}, last_record_lsn={}",
5648 : deltas.lsn_range.end,
5649 : last_record_lsn
5650 : );
5651 74 : if let Some(check_start_lsn) = check_start_lsn {
5652 74 : assert!(deltas.lsn_range.start >= check_start_lsn);
5653 0 : }
5654 74 : let mut delta_layer_writer = DeltaLayerWriter::new(
5655 74 : self.conf,
5656 74 : self.timeline_id,
5657 74 : self.tenant_shard_id,
5658 74 : deltas.key_range.start,
5659 74 : deltas.lsn_range,
5660 74 : ctx,
5661 74 : )
5662 37 : .await?;
5663 272 : for (key, lsn, val) in deltas.data {
5664 198 : delta_layer_writer.put_value(key, lsn, val, ctx).await?;
5665 : }
5666 185 : let (desc, path) = delta_layer_writer.finish(deltas.key_range.end, ctx).await?;
5667 74 : let delta_layer = Layer::finish_creating(self.conf, self, desc, &path)?;
5668 74 : info!("force created delta layer {}", delta_layer.local_path());
5669 : {
5670 74 : let mut guard = self.layers.write().await;
5671 74 : guard.open_mut().unwrap().force_insert_layer(delta_layer);
5672 74 : }
5673 74 :
5674 74 : Ok(())
5675 74 : }
5676 :
5677 : /// Return all keys at the LSN in the image layers
5678 : #[cfg(test)]
5679 6 : pub(crate) async fn inspect_image_layers(
5680 6 : self: &Arc<Timeline>,
5681 6 : lsn: Lsn,
5682 6 : ctx: &RequestContext,
5683 6 : ) -> anyhow::Result<Vec<(Key, Bytes)>> {
5684 6 : let mut all_data = Vec::new();
5685 6 : let guard = self.layers.read().await;
5686 34 : for layer in guard.layer_map()?.iter_historic_layers() {
5687 34 : if !layer.is_delta() && layer.image_layer_lsn() == lsn {
5688 8 : let layer = guard.get_from_desc(&layer);
5689 8 : let mut reconstruct_data = ValuesReconstructState::default();
5690 8 : layer
5691 8 : .get_values_reconstruct_data(
5692 8 : KeySpace::single(Key::MIN..Key::MAX),
5693 8 : lsn..Lsn(lsn.0 + 1),
5694 8 : &mut reconstruct_data,
5695 8 : ctx,
5696 8 : )
5697 13 : .await?;
5698 74 : for (k, v) in reconstruct_data.keys {
5699 66 : all_data.push((k, v?.img.unwrap().1));
5700 : }
5701 26 : }
5702 : }
5703 6 : all_data.sort();
5704 6 : Ok(all_data)
5705 6 : }
5706 :
5707 : /// Get all historic layer descriptors in the layer map
5708 : #[cfg(test)]
5709 12 : pub(crate) async fn inspect_historic_layers(
5710 12 : self: &Arc<Timeline>,
5711 12 : ) -> anyhow::Result<Vec<super::storage_layer::PersistentLayerKey>> {
5712 12 : let mut layers = Vec::new();
5713 12 : let guard = self.layers.read().await;
5714 70 : for layer in guard.layer_map()?.iter_historic_layers() {
5715 70 : layers.push(layer.key());
5716 70 : }
5717 12 : Ok(layers)
5718 12 : }
5719 :
5720 : #[cfg(test)]
5721 10 : pub(crate) fn add_extra_test_dense_keyspace(&self, ks: KeySpace) {
5722 10 : let mut keyspace = self.extra_test_dense_keyspace.load().as_ref().clone();
5723 10 : keyspace.merge(&ks);
5724 10 : self.extra_test_dense_keyspace.store(Arc::new(keyspace));
5725 10 : }
5726 : }
5727 :
5728 : /// Tracking writes ingestion does to a particular in-memory layer.
5729 : ///
5730 : /// Cleared upon freezing a layer.
5731 : pub(crate) struct TimelineWriterState {
5732 : open_layer: Arc<InMemoryLayer>,
5733 : current_size: u64,
5734 : // Previous Lsn which passed through
5735 : prev_lsn: Option<Lsn>,
5736 : // Largest Lsn which passed through the current writer
5737 : max_lsn: Option<Lsn>,
5738 : // Cached details of the last freeze. Avoids going trough the atomic/lock on every put.
5739 : cached_last_freeze_at: Lsn,
5740 : }
5741 :
5742 : impl TimelineWriterState {
5743 1268 : fn new(open_layer: Arc<InMemoryLayer>, current_size: u64, last_freeze_at: Lsn) -> Self {
5744 1268 : Self {
5745 1268 : open_layer,
5746 1268 : current_size,
5747 1268 : prev_lsn: None,
5748 1268 : max_lsn: None,
5749 1268 : cached_last_freeze_at: last_freeze_at,
5750 1268 : }
5751 1268 : }
5752 : }
5753 :
5754 : /// Various functions to mutate the timeline.
5755 : // TODO Currently, Deref is used to allow easy access to read methods from this trait.
5756 : // This is probably considered a bad practice in Rust and should be fixed eventually,
5757 : // but will cause large code changes.
5758 : pub(crate) struct TimelineWriter<'a> {
5759 : tl: &'a Timeline,
5760 : write_guard: tokio::sync::MutexGuard<'a, Option<TimelineWriterState>>,
5761 : }
5762 :
5763 : impl Deref for TimelineWriter<'_> {
5764 : type Target = Timeline;
5765 :
5766 4807192 : fn deref(&self) -> &Self::Target {
5767 4807192 : self.tl
5768 4807192 : }
5769 : }
5770 :
5771 : #[derive(PartialEq)]
5772 : enum OpenLayerAction {
5773 : Roll,
5774 : Open,
5775 : None,
5776 : }
5777 :
5778 : impl<'a> TimelineWriter<'a> {
5779 4804204 : async fn handle_open_layer_action(
5780 4804204 : &mut self,
5781 4804204 : at: Lsn,
5782 4804204 : action: OpenLayerAction,
5783 4804204 : ctx: &RequestContext,
5784 4804204 : ) -> anyhow::Result<&Arc<InMemoryLayer>> {
5785 4804204 : match action {
5786 : OpenLayerAction::Roll => {
5787 80 : let freeze_at = self.write_guard.as_ref().unwrap().max_lsn.unwrap();
5788 80 : self.roll_layer(freeze_at).await?;
5789 80 : self.open_layer(at, ctx).await?;
5790 : }
5791 1188 : OpenLayerAction::Open => self.open_layer(at, ctx).await?,
5792 : OpenLayerAction::None => {
5793 4802936 : assert!(self.write_guard.is_some());
5794 : }
5795 : }
5796 :
5797 4804204 : Ok(&self.write_guard.as_ref().unwrap().open_layer)
5798 4804204 : }
5799 :
5800 1268 : async fn open_layer(&mut self, at: Lsn, ctx: &RequestContext) -> anyhow::Result<()> {
5801 1268 : let layer = self
5802 1268 : .tl
5803 1268 : .get_layer_for_write(at, &self.write_guard, ctx)
5804 719 : .await?;
5805 1268 : let initial_size = layer.size().await?;
5806 :
5807 1268 : let last_freeze_at = self.last_freeze_at.load();
5808 1268 : self.write_guard.replace(TimelineWriterState::new(
5809 1268 : layer,
5810 1268 : initial_size,
5811 1268 : last_freeze_at,
5812 1268 : ));
5813 1268 :
5814 1268 : Ok(())
5815 1268 : }
5816 :
5817 80 : async fn roll_layer(&mut self, freeze_at: Lsn) -> Result<(), FlushLayerError> {
5818 80 : let current_size = self.write_guard.as_ref().unwrap().current_size;
5819 80 :
5820 80 : // self.write_guard will be taken by the freezing
5821 80 : self.tl
5822 80 : .freeze_inmem_layer_at(freeze_at, &mut self.write_guard)
5823 4 : .await?;
5824 :
5825 80 : assert!(self.write_guard.is_none());
5826 :
5827 80 : if current_size >= self.get_checkpoint_distance() * 2 {
5828 0 : warn!("Flushed oversized open layer with size {}", current_size)
5829 80 : }
5830 :
5831 80 : Ok(())
5832 80 : }
5833 :
5834 4804204 : fn get_open_layer_action(&self, lsn: Lsn, new_value_size: u64) -> OpenLayerAction {
5835 4804204 : let state = &*self.write_guard;
5836 4804204 : let Some(state) = &state else {
5837 1188 : return OpenLayerAction::Open;
5838 : };
5839 :
5840 : #[cfg(feature = "testing")]
5841 4803016 : if state.cached_last_freeze_at < self.tl.last_freeze_at.load() {
5842 : // this check and assertion are not really needed because
5843 : // LayerManager::try_freeze_in_memory_layer will always clear out the
5844 : // TimelineWriterState if something is frozen. however, we can advance last_freeze_at when there
5845 : // is no TimelineWriterState.
5846 0 : assert!(
5847 0 : state.open_layer.end_lsn.get().is_some(),
5848 0 : "our open_layer must be outdated"
5849 : );
5850 :
5851 : // this would be a memory leak waiting to happen because the in-memory layer always has
5852 : // an index
5853 0 : panic!("BUG: TimelineWriterState held on to frozen in-memory layer.");
5854 4803016 : }
5855 4803016 :
5856 4803016 : if state.prev_lsn == Some(lsn) {
5857 : // Rolling mid LSN is not supported by [downstream code].
5858 : // Hence, only roll at LSN boundaries.
5859 : //
5860 : // [downstream code]: https://github.com/neondatabase/neon/pull/7993#discussion_r1633345422
5861 6 : return OpenLayerAction::None;
5862 4803010 : }
5863 4803010 :
5864 4803010 : if state.current_size == 0 {
5865 : // Don't roll empty layers
5866 0 : return OpenLayerAction::None;
5867 4803010 : }
5868 4803010 :
5869 4803010 : if self.tl.should_roll(
5870 4803010 : state.current_size,
5871 4803010 : state.current_size + new_value_size,
5872 4803010 : self.get_checkpoint_distance(),
5873 4803010 : lsn,
5874 4803010 : state.cached_last_freeze_at,
5875 4803010 : state.open_layer.get_opened_at(),
5876 4803010 : ) {
5877 80 : OpenLayerAction::Roll
5878 : } else {
5879 4802930 : OpenLayerAction::None
5880 : }
5881 4804204 : }
5882 :
5883 : /// Put a batch of keys at the specified Lsns.
5884 4804202 : pub(crate) async fn put_batch(
5885 4804202 : &mut self,
5886 4804202 : batch: SerializedValueBatch,
5887 4804202 : ctx: &RequestContext,
5888 4804202 : ) -> anyhow::Result<()> {
5889 4804202 : if batch.is_empty() {
5890 0 : return Ok(());
5891 4804202 : }
5892 4804202 :
5893 4804202 : let batch_max_lsn = batch.max_lsn;
5894 4804202 : let buf_size: u64 = batch.buffer_size() as u64;
5895 4804202 :
5896 4804202 : let action = self.get_open_layer_action(batch_max_lsn, buf_size);
5897 4804202 : let layer = self
5898 4804202 : .handle_open_layer_action(batch_max_lsn, action, ctx)
5899 723 : .await?;
5900 :
5901 4804202 : let res = layer.put_batch(batch, ctx).await;
5902 :
5903 4804202 : if res.is_ok() {
5904 4804202 : // Update the current size only when the entire write was ok.
5905 4804202 : // In case of failures, we may have had partial writes which
5906 4804202 : // render the size tracking out of sync. That's ok because
5907 4804202 : // the checkpoint distance should be significantly smaller
5908 4804202 : // than the S3 single shot upload limit of 5GiB.
5909 4804202 : let state = self.write_guard.as_mut().unwrap();
5910 4804202 :
5911 4804202 : state.current_size += buf_size;
5912 4804202 : state.prev_lsn = Some(batch_max_lsn);
5913 4804202 : state.max_lsn = std::cmp::max(state.max_lsn, Some(batch_max_lsn));
5914 4804202 : }
5915 :
5916 4804202 : res
5917 4804202 : }
5918 :
5919 : #[cfg(test)]
5920 : /// Test helper, for tests that would like to poke individual values without composing a batch
5921 4390154 : pub(crate) async fn put(
5922 4390154 : &mut self,
5923 4390154 : key: Key,
5924 4390154 : lsn: Lsn,
5925 4390154 : value: &Value,
5926 4390154 : ctx: &RequestContext,
5927 4390154 : ) -> anyhow::Result<()> {
5928 : use utils::bin_ser::BeSer;
5929 4390154 : if !key.is_valid_key_on_write_path() {
5930 0 : bail!(
5931 0 : "the request contains data not supported by pageserver at TimelineWriter::put: {}",
5932 0 : key
5933 0 : );
5934 4390154 : }
5935 4390154 : let val_ser_size = value.serialized_size().unwrap() as usize;
5936 4390154 : let batch = SerializedValueBatch::from_values(vec![(
5937 4390154 : key.to_compact(),
5938 4390154 : lsn,
5939 4390154 : val_ser_size,
5940 4390154 : value.clone(),
5941 4390154 : )]);
5942 4390154 :
5943 4390154 : self.put_batch(batch, ctx).await
5944 4390154 : }
5945 :
5946 2 : pub(crate) async fn delete_batch(
5947 2 : &mut self,
5948 2 : batch: &[(Range<Key>, Lsn)],
5949 2 : ctx: &RequestContext,
5950 2 : ) -> anyhow::Result<()> {
5951 2 : if let Some((_, lsn)) = batch.first() {
5952 2 : let action = self.get_open_layer_action(*lsn, 0);
5953 2 : let layer = self.handle_open_layer_action(*lsn, action, ctx).await?;
5954 2 : layer.put_tombstones(batch).await?;
5955 0 : }
5956 :
5957 2 : Ok(())
5958 2 : }
5959 :
5960 : /// Track the end of the latest digested WAL record.
5961 : /// Remember the (end of) last valid WAL record remembered in the timeline.
5962 : ///
5963 : /// Call this after you have finished writing all the WAL up to 'lsn'.
5964 : ///
5965 : /// 'lsn' must be aligned. This wakes up any wait_lsn() callers waiting for
5966 : /// the 'lsn' or anything older. The previous last record LSN is stored alongside
5967 : /// the latest and can be read.
5968 5279064 : pub(crate) fn finish_write(&self, new_lsn: Lsn) {
5969 5279064 : self.tl.finish_write(new_lsn);
5970 5279064 : }
5971 :
5972 270570 : pub(crate) fn update_current_logical_size(&self, delta: i64) {
5973 270570 : self.tl.update_current_logical_size(delta)
5974 270570 : }
5975 : }
5976 :
5977 : // We need TimelineWriter to be send in upcoming conversion of
5978 : // Timeline::layers to tokio::sync::RwLock.
5979 : #[test]
5980 2 : fn is_send() {
5981 2 : fn _assert_send<T: Send>() {}
5982 2 : _assert_send::<TimelineWriter<'_>>();
5983 2 : }
5984 :
5985 : #[cfg(test)]
5986 : mod tests {
5987 : use pageserver_api::key::Key;
5988 : use pageserver_api::value::Value;
5989 : use utils::{id::TimelineId, lsn::Lsn};
5990 :
5991 : use crate::tenant::{
5992 : harness::{test_img, TenantHarness},
5993 : layer_map::LayerMap,
5994 : storage_layer::{Layer, LayerName},
5995 : timeline::{DeltaLayerTestDesc, EvictionError},
5996 : Timeline,
5997 : };
5998 :
5999 : #[tokio::test]
6000 2 : async fn test_heatmap_generation() {
6001 2 : let harness = TenantHarness::create("heatmap_generation").await.unwrap();
6002 2 :
6003 2 : let covered_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
6004 2 : Lsn(0x10)..Lsn(0x20),
6005 2 : vec![(
6006 2 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
6007 2 : Lsn(0x11),
6008 2 : Value::Image(test_img("foo")),
6009 2 : )],
6010 2 : );
6011 2 : let visible_delta = DeltaLayerTestDesc::new_with_inferred_key_range(
6012 2 : Lsn(0x10)..Lsn(0x20),
6013 2 : vec![(
6014 2 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
6015 2 : Lsn(0x11),
6016 2 : Value::Image(test_img("foo")),
6017 2 : )],
6018 2 : );
6019 2 : let l0_delta = DeltaLayerTestDesc::new(
6020 2 : Lsn(0x20)..Lsn(0x30),
6021 2 : Key::from_hex("000000000000000000000000000000000000").unwrap()
6022 2 : ..Key::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(),
6023 2 : vec![(
6024 2 : Key::from_hex("720000000033333333444444445500000000").unwrap(),
6025 2 : Lsn(0x25),
6026 2 : Value::Image(test_img("foo")),
6027 2 : )],
6028 2 : );
6029 2 : let delta_layers = vec![
6030 2 : covered_delta.clone(),
6031 2 : visible_delta.clone(),
6032 2 : l0_delta.clone(),
6033 2 : ];
6034 2 :
6035 2 : let image_layer = (
6036 2 : Lsn(0x40),
6037 2 : vec![(
6038 2 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
6039 2 : test_img("bar"),
6040 2 : )],
6041 2 : );
6042 2 : let image_layers = vec![image_layer];
6043 2 :
6044 20 : let (tenant, ctx) = harness.load().await;
6045 2 : let timeline = tenant
6046 2 : .create_test_timeline_with_layers(
6047 2 : TimelineId::generate(),
6048 2 : Lsn(0x10),
6049 2 : 14,
6050 2 : &ctx,
6051 2 : delta_layers,
6052 2 : image_layers,
6053 2 : Lsn(0x100),
6054 2 : )
6055 31 : .await
6056 2 : .unwrap();
6057 2 :
6058 2 : // Layer visibility is an input to heatmap generation, so refresh it first
6059 2 : timeline.update_layer_visibility().await.unwrap();
6060 2 :
6061 2 : let heatmap = timeline
6062 2 : .generate_heatmap()
6063 2 : .await
6064 2 : .expect("Infallible while timeline is not shut down");
6065 2 :
6066 2 : assert_eq!(heatmap.timeline_id, timeline.timeline_id);
6067 2 :
6068 2 : // L0 should come last
6069 2 : assert_eq!(heatmap.layers.last().unwrap().name, l0_delta.layer_name());
6070 2 :
6071 2 : let mut last_lsn = Lsn::MAX;
6072 10 : for layer in heatmap.layers {
6073 2 : // Covered layer should be omitted
6074 8 : assert!(layer.name != covered_delta.layer_name());
6075 2 :
6076 8 : let layer_lsn = match &layer.name {
6077 4 : LayerName::Delta(d) => d.lsn_range.end,
6078 4 : LayerName::Image(i) => i.lsn,
6079 2 : };
6080 2 :
6081 2 : // Apart from L0s, newest Layers should come first
6082 8 : if !LayerMap::is_l0(layer.name.key_range(), layer.name.is_delta()) {
6083 6 : assert!(layer_lsn <= last_lsn);
6084 6 : last_lsn = layer_lsn;
6085 2 : }
6086 2 : }
6087 2 : }
6088 :
6089 : #[tokio::test]
6090 2 : async fn two_layer_eviction_attempts_at_the_same_time() {
6091 2 : let harness = TenantHarness::create("two_layer_eviction_attempts_at_the_same_time")
6092 2 : .await
6093 2 : .unwrap();
6094 2 :
6095 20 : let (tenant, ctx) = harness.load().await;
6096 2 : let timeline = tenant
6097 2 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
6098 6 : .await
6099 2 : .unwrap();
6100 2 :
6101 2 : let layer = find_some_layer(&timeline).await;
6102 2 : let layer = layer
6103 2 : .keep_resident()
6104 2 : .await
6105 2 : .expect("no download => no downloading errors")
6106 2 : .drop_eviction_guard();
6107 2 :
6108 2 : let forever = std::time::Duration::from_secs(120);
6109 2 :
6110 2 : let first = layer.evict_and_wait(forever);
6111 2 : let second = layer.evict_and_wait(forever);
6112 2 :
6113 2 : let (first, second) = tokio::join!(first, second);
6114 2 :
6115 2 : let res = layer.keep_resident().await;
6116 2 : assert!(res.is_none(), "{res:?}");
6117 2 :
6118 2 : match (first, second) {
6119 2 : (Ok(()), Ok(())) => {
6120 2 : // because there are no more timeline locks being taken on eviction path, we can
6121 2 : // witness all three outcomes here.
6122 2 : }
6123 2 : (Ok(()), Err(EvictionError::NotFound)) | (Err(EvictionError::NotFound), Ok(())) => {
6124 0 : // if one completes before the other, this is fine just as well.
6125 0 : }
6126 2 : other => unreachable!("unexpected {:?}", other),
6127 2 : }
6128 2 : }
6129 :
6130 2 : async fn find_some_layer(timeline: &Timeline) -> Layer {
6131 2 : let layers = timeline.layers.read().await;
6132 2 : let desc = layers
6133 2 : .layer_map()
6134 2 : .unwrap()
6135 2 : .iter_historic_layers()
6136 2 : .next()
6137 2 : .expect("must find one layer to evict");
6138 2 :
6139 2 : layers.get_from_desc(&desc)
6140 2 : }
6141 : }
|