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

Generated by: LCOV version 2.1-beta