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

Generated by: LCOV version 2.1-beta