LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 98683a8629f0f7f0031d02e04512998d589d76ea.info Lines: 65.1 % 4372 2846
Test Date: 2025-04-11 16:58:57 Functions: 57.9 % 373 216

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

Generated by: LCOV version 2.1-beta