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

Generated by: LCOV version 2.1-beta