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