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