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