LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 903780b8ddc62f532be8f220102da7b91c63a235.info Lines: 63.4 % 3367 2133
Test Date: 2024-10-25 10:10:57 Functions: 57.3 % 323 185

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

Generated by: LCOV version 2.1-beta