LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: d427f6f28cacba33c85e3c88c25b596f8e14b0f1.info Lines: 63.5 % 4032 2559
Test Date: 2025-02-15 14:15:22 Functions: 59.2 % 343 203

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

Generated by: LCOV version 2.1-beta