LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 5e392a02abbad1ab595f4dba672e219a49f7f539.info Lines: 65.7 % 4377 2875
Test Date: 2025-04-11 22:43:24 Functions: 58.2 % 373 217

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

Generated by: LCOV version 2.1-beta