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