LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 65975feb441523e1ae5866ecbec0610188cb8ce3.info Lines: 61.6 % 3817 2352
Test Date: 2025-02-12 20:31:43 Functions: 58.6 % 336 197

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

Generated by: LCOV version 2.1-beta