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