LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 157166bf1e7b60cf936c3c96f6e44d24268705a4.info Lines: 64.1 % 4321 2770
Test Date: 2025-07-08 19:05:57 Functions: 59.9 % 384 230

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

Generated by: LCOV version 2.1-beta