LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 47d527da5e8405637e322911c55c08727c2fd272.info Lines: 63.5 % 3516 2232
Test Date: 2025-01-16 17:37:50 Functions: 59.7 % 315 188

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

Generated by: LCOV version 2.1-beta