LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 685df7483efdc579d44aa7093bca9796bb9d088e.info Lines: 63.0 % 3508 2209
Test Date: 2024-11-25 17:08:35 Functions: 56.1 % 344 193

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

Generated by: LCOV version 2.1-beta