LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: ae32e90d936a6b0438b35d9ab8babc961b1ac107.info Lines: 62.5 % 3708 2317
Test Date: 2025-01-29 17:08:55 Functions: 59.8 % 326 195

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

Generated by: LCOV version 2.1-beta