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