LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 15f04989d2faf4ce76cecb56042184aca56ebae6.info Lines: 63.8 % 4392 2804
Test Date: 2025-07-14 11:50:36 Functions: 59.0 % 395 233

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

Generated by: LCOV version 2.1-beta