LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 6d83f7aa7281c4d19897fe60ea895d095b0bd790.info Lines: 63.0 % 4218 2658
Test Date: 2025-03-03 21:26:05 Functions: 59.6 % 354 211

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

Generated by: LCOV version 2.1-beta