LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 63.0 % 3507 2209
Test Date: 2024-11-25 17:48:16 Functions: 56.1 % 344 193

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

Generated by: LCOV version 2.1-beta