LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 66.0 % 4505 2975
Test Date: 2025-04-24 20:31:15 Functions: 59.7 % 392 234

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

Generated by: LCOV version 2.1-beta