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

Generated by: LCOV version 2.1-beta