LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: b837401fb09d2d9818b70e630fdb67e9799b7b0d.info Lines: 57.0 % 2811 1603
Test Date: 2024-04-18 15:32:49 Functions: 46.4 % 373 173

            Line data    Source code
       1              : mod compaction;
       2              : pub mod delete;
       3              : mod eviction_task;
       4              : mod init;
       5              : pub mod layer_manager;
       6              : pub(crate) mod logical_size;
       7              : pub mod span;
       8              : pub mod uninit;
       9              : mod walreceiver;
      10              : 
      11              : use anyhow::{anyhow, bail, ensure, Context, Result};
      12              : use arc_swap::ArcSwap;
      13              : use bytes::Bytes;
      14              : use camino::Utf8Path;
      15              : use enumset::EnumSet;
      16              : use fail::fail_point;
      17              : use once_cell::sync::Lazy;
      18              : use pageserver_api::{
      19              :     key::AUX_FILES_KEY,
      20              :     keyspace::KeySpaceAccum,
      21              :     models::{
      22              :         CompactionAlgorithm, DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskSpawnRequest,
      23              :         EvictionPolicy, InMemoryLayerInfo, LayerMapInfo, TimelineState,
      24              :     },
      25              :     reltag::BlockNumber,
      26              :     shard::{ShardIdentity, TenantShardId},
      27              : };
      28              : use rand::Rng;
      29              : use serde_with::serde_as;
      30              : use storage_broker::BrokerClientChannel;
      31              : use tokio::{
      32              :     runtime::Handle,
      33              :     sync::{oneshot, watch},
      34              : };
      35              : use tokio_util::sync::CancellationToken;
      36              : use tracing::*;
      37              : use utils::{
      38              :     bin_ser::BeSer,
      39              :     sync::gate::{Gate, GateGuard},
      40              :     vec_map::VecMap,
      41              : };
      42              : 
      43              : use std::ops::{Deref, Range};
      44              : use std::pin::pin;
      45              : use std::sync::atomic::Ordering as AtomicOrdering;
      46              : use std::sync::{Arc, Mutex, RwLock, Weak};
      47              : use std::time::{Duration, Instant, SystemTime};
      48              : use std::{
      49              :     array,
      50              :     collections::{BTreeMap, HashMap, HashSet},
      51              :     sync::atomic::AtomicU64,
      52              : };
      53              : use std::{
      54              :     cmp::{max, min, Ordering},
      55              :     ops::ControlFlow,
      56              : };
      57              : 
      58              : use crate::deletion_queue::DeletionQueueClient;
      59              : use crate::tenant::timeline::logical_size::CurrentLogicalSize;
      60              : use crate::tenant::{
      61              :     layer_map::{LayerMap, SearchResult},
      62              :     metadata::TimelineMetadata,
      63              : };
      64              : use crate::{
      65              :     context::{DownloadBehavior, RequestContext},
      66              :     disk_usage_eviction_task::DiskUsageEvictionInfo,
      67              :     pgdatadir_mapping::CollectKeySpaceError,
      68              : };
      69              : use crate::{
      70              :     disk_usage_eviction_task::finite_f32,
      71              :     tenant::storage_layer::{
      72              :         AsLayerDesc, DeltaLayerWriter, EvictionError, ImageLayerWriter, InMemoryLayer, Layer,
      73              :         LayerAccessStatsReset, LayerFileName, ResidentLayer, ValueReconstructResult,
      74              :         ValueReconstructState, ValuesReconstructState,
      75              :     },
      76              : };
      77              : use crate::{
      78              :     disk_usage_eviction_task::EvictionCandidate, tenant::storage_layer::delta_layer::DeltaEntry,
      79              : };
      80              : use crate::{pgdatadir_mapping::LsnForTimestamp, tenant::tasks::BackgroundLoopKind};
      81              : use crate::{
      82              :     pgdatadir_mapping::{AuxFilesDirectory, DirectoryKind},
      83              :     virtual_file::{MaybeFatalIo, VirtualFile},
      84              : };
      85              : 
      86              : use crate::config::PageServerConf;
      87              : use crate::keyspace::{KeyPartitioning, KeySpace};
      88              : use crate::metrics::{
      89              :     TimelineMetrics, MATERIALIZED_PAGE_CACHE_HIT, MATERIALIZED_PAGE_CACHE_HIT_DIRECT,
      90              : };
      91              : use crate::pgdatadir_mapping::CalculateLogicalSizeError;
      92              : use crate::tenant::config::TenantConfOpt;
      93              : use pageserver_api::key::{is_inherited_key, is_rel_fsm_block_key, is_rel_vm_block_key};
      94              : use pageserver_api::reltag::RelTag;
      95              : use pageserver_api::shard::ShardIndex;
      96              : 
      97              : use postgres_connection::PgConnectionConfig;
      98              : use postgres_ffi::to_pg_timestamp;
      99              : use utils::{
     100              :     completion,
     101              :     generation::Generation,
     102              :     id::TimelineId,
     103              :     lsn::{AtomicLsn, Lsn, RecordLsn},
     104              :     seqwait::SeqWait,
     105              :     simple_rcu::{Rcu, RcuReadGuard},
     106              : };
     107              : 
     108              : use crate::page_cache;
     109              : use crate::repository::GcResult;
     110              : use crate::repository::{Key, Value};
     111              : use crate::task_mgr;
     112              : use crate::task_mgr::TaskKind;
     113              : use crate::ZERO_PAGE;
     114              : 
     115              : use self::delete::DeleteTimelineFlow;
     116              : pub(super) use self::eviction_task::EvictionTaskTenantState;
     117              : use self::eviction_task::EvictionTaskTimelineState;
     118              : use self::layer_manager::LayerManager;
     119              : use self::logical_size::LogicalSize;
     120              : use self::walreceiver::{WalReceiver, WalReceiverConf};
     121              : 
     122              : use super::config::TenantConf;
     123              : use super::secondary::heatmap::{HeatMapLayer, HeatMapTimeline};
     124              : use super::{debug_assert_current_span_has_tenant_and_timeline_id, AttachedTenantConf};
     125              : use super::{remote_timeline_client::index::IndexPart, storage_layer::LayerFringe};
     126              : use super::{remote_timeline_client::RemoteTimelineClient, storage_layer::ReadableLayer};
     127              : 
     128              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
     129              : pub(super) enum FlushLoopState {
     130              :     NotStarted,
     131              :     Running {
     132              :         #[cfg(test)]
     133              :         expect_initdb_optimization: bool,
     134              :         #[cfg(test)]
     135              :         initdb_optimization_count: usize,
     136              :     },
     137              :     Exited,
     138              : }
     139              : 
     140              : /// Wrapper for key range to provide reverse ordering by range length for BinaryHeap
     141              : #[derive(Debug, Clone, PartialEq, Eq)]
     142              : pub(crate) struct Hole {
     143              :     key_range: Range<Key>,
     144              :     coverage_size: usize,
     145              : }
     146              : 
     147              : impl Ord for Hole {
     148            0 :     fn cmp(&self, other: &Self) -> Ordering {
     149            0 :         other.coverage_size.cmp(&self.coverage_size) // inverse order
     150            0 :     }
     151              : }
     152              : 
     153              : impl PartialOrd for Hole {
     154            0 :     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
     155            0 :         Some(self.cmp(other))
     156            0 :     }
     157              : }
     158              : 
     159              : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
     160              : /// Can be removed after all refactors are done.
     161           42 : fn drop_rlock<T>(rlock: tokio::sync::OwnedRwLockReadGuard<T>) {
     162           42 :     drop(rlock)
     163           42 : }
     164              : 
     165              : /// Temporary function for immutable storage state refactor, ensures we are dropping mutex guard instead of other things.
     166              : /// Can be removed after all refactors are done.
     167          646 : fn drop_wlock<T>(rlock: tokio::sync::RwLockWriteGuard<'_, T>) {
     168          646 :     drop(rlock)
     169          646 : }
     170              : 
     171              : /// The outward-facing resources required to build a Timeline
     172              : pub struct TimelineResources {
     173              :     pub remote_client: Option<RemoteTimelineClient>,
     174              :     pub deletion_queue_client: DeletionQueueClient,
     175              :     pub timeline_get_throttle: Arc<
     176              :         crate::tenant::throttle::Throttle<&'static crate::metrics::tenant_throttling::TimelineGet>,
     177              :     >,
     178              : }
     179              : 
     180              : pub(crate) struct AuxFilesState {
     181              :     pub(crate) dir: Option<AuxFilesDirectory>,
     182              :     pub(crate) n_deltas: usize,
     183              : }
     184              : 
     185              : pub struct Timeline {
     186              :     conf: &'static PageServerConf,
     187              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     188              : 
     189              :     myself: Weak<Self>,
     190              : 
     191              :     pub(crate) tenant_shard_id: TenantShardId,
     192              :     pub timeline_id: TimelineId,
     193              : 
     194              :     /// The generation of the tenant that instantiated us: this is used for safety when writing remote objects.
     195              :     /// Never changes for the lifetime of this [`Timeline`] object.
     196              :     ///
     197              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     198              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     199              :     pub(crate) generation: Generation,
     200              : 
     201              :     /// The detailed sharding information from our parent Tenant.  This enables us to map keys
     202              :     /// to shards, and is constant through the lifetime of this Timeline.
     203              :     shard_identity: ShardIdentity,
     204              : 
     205              :     pub pg_version: u32,
     206              : 
     207              :     /// The tuple has two elements.
     208              :     /// 1. `LayerFileManager` keeps track of the various physical representations of the layer files (inmem, local, remote).
     209              :     /// 2. `LayerMap`, the acceleration data structure for `get_reconstruct_data`.
     210              :     ///
     211              :     /// `LayerMap` maps out the `(PAGE,LSN) / (KEY,LSN)` space, which is composed of `(KeyRange, LsnRange)` rectangles.
     212              :     /// We describe these rectangles through the `PersistentLayerDesc` struct.
     213              :     ///
     214              :     /// When we want to reconstruct a page, we first find the `PersistentLayerDesc`'s that we need for page reconstruction,
     215              :     /// using `LayerMap`. Then, we use `LayerFileManager` to get the `PersistentLayer`'s that correspond to the
     216              :     /// `PersistentLayerDesc`'s.
     217              :     ///
     218              :     /// Hence, it's important to keep things coherent. The `LayerFileManager` must always have an entry for all
     219              :     /// `PersistentLayerDesc`'s in the `LayerMap`. If it doesn't, `LayerFileManager::get_from_desc` will panic at
     220              :     /// runtime, e.g., during page reconstruction.
     221              :     ///
     222              :     /// In the future, we'll be able to split up the tuple of LayerMap and `LayerFileManager`,
     223              :     /// so that e.g. on-demand-download/eviction, and layer spreading, can operate just on `LayerFileManager`.
     224              :     pub(crate) layers: Arc<tokio::sync::RwLock<LayerManager>>,
     225              : 
     226              :     last_freeze_at: AtomicLsn,
     227              :     // Atomic would be more appropriate here.
     228              :     last_freeze_ts: RwLock<Instant>,
     229              : 
     230              :     // WAL redo manager. `None` only for broken tenants.
     231              :     walredo_mgr: Option<Arc<super::WalRedoManager>>,
     232              : 
     233              :     /// Remote storage client.
     234              :     /// See [`remote_timeline_client`](super::remote_timeline_client) module comment for details.
     235              :     pub remote_client: Option<Arc<RemoteTimelineClient>>,
     236              : 
     237              :     // What page versions do we hold in the repository? If we get a
     238              :     // request > last_record_lsn, we need to wait until we receive all
     239              :     // the WAL up to the request. The SeqWait provides functions for
     240              :     // that. TODO: If we get a request for an old LSN, such that the
     241              :     // versions have already been garbage collected away, we should
     242              :     // throw an error, but we don't track that currently.
     243              :     //
     244              :     // last_record_lsn.load().last points to the end of last processed WAL record.
     245              :     //
     246              :     // We also remember the starting point of the previous record in
     247              :     // 'last_record_lsn.load().prev'. It's used to set the xl_prev pointer of the
     248              :     // first WAL record when the node is started up. But here, we just
     249              :     // keep track of it.
     250              :     last_record_lsn: SeqWait<RecordLsn, Lsn>,
     251              : 
     252              :     // All WAL records have been processed and stored durably on files on
     253              :     // local disk, up to this LSN. On crash and restart, we need to re-process
     254              :     // the WAL starting from this point.
     255              :     //
     256              :     // Some later WAL records might have been processed and also flushed to disk
     257              :     // already, so don't be surprised to see some, but there's no guarantee on
     258              :     // them yet.
     259              :     disk_consistent_lsn: AtomicLsn,
     260              : 
     261              :     // Parent timeline that this timeline was branched from, and the LSN
     262              :     // of the branch point.
     263              :     ancestor_timeline: Option<Arc<Timeline>>,
     264              :     ancestor_lsn: Lsn,
     265              : 
     266              :     pub(super) metrics: TimelineMetrics,
     267              : 
     268              :     // `Timeline` doesn't write these metrics itself, but it manages the lifetime.  Code
     269              :     // in `crate::page_service` writes these metrics.
     270              :     pub(crate) query_metrics: crate::metrics::SmgrQueryTimePerTimeline,
     271              : 
     272              :     directory_metrics: [AtomicU64; DirectoryKind::KINDS_NUM],
     273              : 
     274              :     /// Ensures layers aren't frozen by checkpointer between
     275              :     /// [`Timeline::get_layer_for_write`] and layer reads.
     276              :     /// Locked automatically by [`TimelineWriter`] and checkpointer.
     277              :     /// Must always be acquired before the layer map/individual layer lock
     278              :     /// to avoid deadlock.
     279              :     write_lock: tokio::sync::Mutex<Option<TimelineWriterState>>,
     280              : 
     281              :     /// Used to avoid multiple `flush_loop` tasks running
     282              :     pub(super) flush_loop_state: Mutex<FlushLoopState>,
     283              : 
     284              :     /// layer_flush_start_tx can be used to wake up the layer-flushing task.
     285              :     /// - The u64 value is a counter, incremented every time a new flush cycle is requested.
     286              :     ///   The flush cycle counter is sent back on the layer_flush_done channel when
     287              :     ///   the flush finishes. You can use that to wait for the flush to finish.
     288              :     /// - The LSN is updated to max() of its current value and the latest disk_consistent_lsn
     289              :     ///   read by whoever sends an update
     290              :     layer_flush_start_tx: tokio::sync::watch::Sender<(u64, Lsn)>,
     291              :     /// to be notified when layer flushing has finished, subscribe to the layer_flush_done channel
     292              :     layer_flush_done_tx: tokio::sync::watch::Sender<(u64, Result<(), FlushLayerError>)>,
     293              : 
     294              :     // Needed to ensure that we can't create a branch at a point that was already garbage collected
     295              :     pub latest_gc_cutoff_lsn: Rcu<Lsn>,
     296              : 
     297              :     // List of child timelines and their branch points. This is needed to avoid
     298              :     // garbage collecting data that is still needed by the child timelines.
     299              :     pub gc_info: std::sync::RwLock<GcInfo>,
     300              : 
     301              :     // It may change across major versions so for simplicity
     302              :     // keep it after running initdb for a timeline.
     303              :     // It is needed in checks when we want to error on some operations
     304              :     // when they are requested for pre-initdb lsn.
     305              :     // It can be unified with latest_gc_cutoff_lsn under some "first_valid_lsn",
     306              :     // though let's keep them both for better error visibility.
     307              :     pub initdb_lsn: Lsn,
     308              : 
     309              :     /// When did we last calculate the partitioning?
     310              :     partitioning: tokio::sync::Mutex<(KeyPartitioning, Lsn)>,
     311              : 
     312              :     /// Configuration: how often should the partitioning be recalculated.
     313              :     repartition_threshold: u64,
     314              : 
     315              :     last_image_layer_creation_check_at: AtomicLsn,
     316              : 
     317              :     /// Current logical size of the "datadir", at the last LSN.
     318              :     current_logical_size: LogicalSize,
     319              : 
     320              :     /// Information about the last processed message by the WAL receiver,
     321              :     /// or None if WAL receiver has not received anything for this timeline
     322              :     /// yet.
     323              :     pub last_received_wal: Mutex<Option<WalReceiverInfo>>,
     324              :     pub walreceiver: Mutex<Option<WalReceiver>>,
     325              : 
     326              :     /// Relation size cache
     327              :     pub rel_size_cache: RwLock<HashMap<RelTag, (Lsn, BlockNumber)>>,
     328              : 
     329              :     download_all_remote_layers_task_info: RwLock<Option<DownloadRemoteLayersTaskInfo>>,
     330              : 
     331              :     state: watch::Sender<TimelineState>,
     332              : 
     333              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     334              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     335              :     pub delete_progress: Arc<tokio::sync::Mutex<DeleteTimelineFlow>>,
     336              : 
     337              :     eviction_task_timeline_state: tokio::sync::Mutex<EvictionTaskTimelineState>,
     338              : 
     339              :     /// Load or creation time information about the disk_consistent_lsn and when the loading
     340              :     /// happened. Used for consumption metrics.
     341              :     pub(crate) loaded_at: (Lsn, SystemTime),
     342              : 
     343              :     /// Gate to prevent shutdown completing while I/O is still happening to this timeline's data
     344              :     pub(crate) gate: Gate,
     345              : 
     346              :     /// Cancellation token scoped to this timeline: anything doing long-running work relating
     347              :     /// to the timeline should drop out when this token fires.
     348              :     pub(crate) cancel: CancellationToken,
     349              : 
     350              :     /// Make sure we only have one running compaction at a time in tests.
     351              :     ///
     352              :     /// Must only be taken in two places:
     353              :     /// - [`Timeline::compact`] (this file)
     354              :     /// - [`delete::delete_local_timeline_directory`]
     355              :     ///
     356              :     /// Timeline deletion will acquire both compaction and gc locks in whatever order.
     357              :     compaction_lock: tokio::sync::Mutex<()>,
     358              : 
     359              :     /// Make sure we only have one running gc at a time.
     360              :     ///
     361              :     /// Must only be taken in two places:
     362              :     /// - [`Timeline::gc`] (this file)
     363              :     /// - [`delete::delete_local_timeline_directory`]
     364              :     ///
     365              :     /// Timeline deletion will acquire both compaction and gc locks in whatever order.
     366              :     gc_lock: tokio::sync::Mutex<()>,
     367              : 
     368              :     /// Cloned from [`super::Tenant::timeline_get_throttle`] on construction.
     369              :     timeline_get_throttle: Arc<
     370              :         crate::tenant::throttle::Throttle<&'static crate::metrics::tenant_throttling::TimelineGet>,
     371              :     >,
     372              : 
     373              :     /// Keep aux directory cache to avoid it's reconstruction on each update
     374              :     pub(crate) aux_files: tokio::sync::Mutex<AuxFilesState>,
     375              : }
     376              : 
     377              : pub struct WalReceiverInfo {
     378              :     pub wal_source_connconf: PgConnectionConfig,
     379              :     pub last_received_msg_lsn: Lsn,
     380              :     pub last_received_msg_ts: u128,
     381              : }
     382              : 
     383              : ///
     384              : /// Information about how much history needs to be retained, needed by
     385              : /// Garbage Collection.
     386              : ///
     387              : pub struct GcInfo {
     388              :     /// Specific LSNs that are needed.
     389              :     ///
     390              :     /// Currently, this includes all points where child branches have
     391              :     /// been forked off from. In the future, could also include
     392              :     /// explicit user-defined snapshot points.
     393              :     pub retain_lsns: Vec<Lsn>,
     394              : 
     395              :     /// In addition to 'retain_lsns', keep everything newer than this
     396              :     /// point.
     397              :     ///
     398              :     /// This is calculated by subtracting 'gc_horizon' setting from
     399              :     /// last-record LSN
     400              :     ///
     401              :     /// FIXME: is this inclusive or exclusive?
     402              :     pub horizon_cutoff: Lsn,
     403              : 
     404              :     /// In addition to 'retain_lsns' and 'horizon_cutoff', keep everything newer than this
     405              :     /// point.
     406              :     ///
     407              :     /// This is calculated by finding a number such that a record is needed for PITR
     408              :     /// if only if its LSN is larger than 'pitr_cutoff'.
     409              :     pub pitr_cutoff: Lsn,
     410              : }
     411              : 
     412              : /// An error happened in a get() operation.
     413            2 : #[derive(thiserror::Error, Debug)]
     414              : pub(crate) enum PageReconstructError {
     415              :     #[error(transparent)]
     416              :     Other(#[from] anyhow::Error),
     417              : 
     418              :     #[error("Ancestor LSN wait error: {0}")]
     419              :     AncestorLsnTimeout(#[from] WaitLsnError),
     420              : 
     421              :     #[error("timeline shutting down")]
     422              :     Cancelled,
     423              : 
     424              :     /// The ancestor of this is being stopped
     425              :     #[error("ancestor timeline {0} is being stopped")]
     426              :     AncestorStopping(TimelineId),
     427              : 
     428              :     /// An error happened replaying WAL records
     429              :     #[error(transparent)]
     430              :     WalRedo(anyhow::Error),
     431              : }
     432              : 
     433              : impl PageReconstructError {
     434              :     /// Returns true if this error indicates a tenant/timeline shutdown alike situation
     435            0 :     pub(crate) fn is_stopping(&self) -> bool {
     436            0 :         use PageReconstructError::*;
     437            0 :         match self {
     438            0 :             Other(_) => false,
     439            0 :             AncestorLsnTimeout(_) => false,
     440            0 :             Cancelled | AncestorStopping(_) => true,
     441            0 :             WalRedo(_) => false,
     442              :         }
     443            0 :     }
     444              : }
     445              : 
     446            0 : #[derive(thiserror::Error, Debug)]
     447              : enum CreateImageLayersError {
     448              :     #[error("timeline shutting down")]
     449              :     Cancelled,
     450              : 
     451              :     #[error(transparent)]
     452              :     GetVectoredError(GetVectoredError),
     453              : 
     454              :     #[error(transparent)]
     455              :     PageReconstructError(PageReconstructError),
     456              : 
     457              :     #[error(transparent)]
     458              :     Other(#[from] anyhow::Error),
     459              : }
     460              : 
     461            0 : #[derive(thiserror::Error, Debug)]
     462              : enum FlushLayerError {
     463              :     /// Timeline cancellation token was cancelled
     464              :     #[error("timeline shutting down")]
     465              :     Cancelled,
     466              : 
     467              :     #[error(transparent)]
     468              :     CreateImageLayersError(CreateImageLayersError),
     469              : 
     470              :     #[error(transparent)]
     471              :     Other(#[from] anyhow::Error),
     472              : }
     473              : 
     474            0 : #[derive(thiserror::Error, Debug)]
     475              : pub(crate) enum GetVectoredError {
     476              :     #[error("timeline shutting down")]
     477              :     Cancelled,
     478              : 
     479              :     #[error("Requested too many keys: {0} > {}", Timeline::MAX_GET_VECTORED_KEYS)]
     480              :     Oversized(u64),
     481              : 
     482              :     #[error("Requested at invalid LSN: {0}")]
     483              :     InvalidLsn(Lsn),
     484              : 
     485              :     #[error("Requested key {0} not found")]
     486              :     MissingKey(Key),
     487              : 
     488              :     #[error(transparent)]
     489              :     GetReadyAncestorError(GetReadyAncestorError),
     490              : 
     491              :     #[error(transparent)]
     492              :     Other(#[from] anyhow::Error),
     493              : }
     494              : 
     495            0 : #[derive(thiserror::Error, Debug)]
     496              : pub(crate) enum GetReadyAncestorError {
     497              :     #[error("ancestor timeline {0} is being stopped")]
     498              :     AncestorStopping(TimelineId),
     499              : 
     500              :     #[error("Ancestor LSN wait error: {0}")]
     501              :     AncestorLsnTimeout(#[from] WaitLsnError),
     502              : 
     503              :     #[error("Cancelled")]
     504              :     Cancelled,
     505              : 
     506              :     #[error(transparent)]
     507              :     Other(#[from] anyhow::Error),
     508              : }
     509              : 
     510              : #[derive(Clone, Copy)]
     511              : pub enum LogicalSizeCalculationCause {
     512              :     Initial,
     513              :     ConsumptionMetricsSyntheticSize,
     514              :     EvictionTaskImitation,
     515              :     TenantSizeHandler,
     516              : }
     517              : 
     518              : pub enum GetLogicalSizePriority {
     519              :     User,
     520              :     Background,
     521              : }
     522              : 
     523            0 : #[derive(enumset::EnumSetType)]
     524              : pub(crate) enum CompactFlags {
     525              :     ForceRepartition,
     526              :     ForceImageLayerCreation,
     527              : }
     528              : 
     529              : impl std::fmt::Debug for Timeline {
     530            0 :     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
     531            0 :         write!(f, "Timeline<{}>", self.timeline_id)
     532            0 :     }
     533              : }
     534              : 
     535            0 : #[derive(thiserror::Error, Debug)]
     536              : pub(crate) enum WaitLsnError {
     537              :     // Called on a timeline which is shutting down
     538              :     #[error("Shutdown")]
     539              :     Shutdown,
     540              : 
     541              :     // Called on an timeline not in active state or shutting down
     542              :     #[error("Bad state (not active)")]
     543              :     BadState,
     544              : 
     545              :     // Timeout expired while waiting for LSN to catch up with goal.
     546              :     #[error("{0}")]
     547              :     Timeout(String),
     548              : }
     549              : 
     550              : // The impls below achieve cancellation mapping for errors.
     551              : // Perhaps there's a way of achieving this with less cruft.
     552              : 
     553              : impl From<CreateImageLayersError> for CompactionError {
     554            0 :     fn from(e: CreateImageLayersError) -> Self {
     555            0 :         match e {
     556            0 :             CreateImageLayersError::Cancelled => CompactionError::ShuttingDown,
     557            0 :             _ => CompactionError::Other(e.into()),
     558              :         }
     559            0 :     }
     560              : }
     561              : 
     562              : impl From<CreateImageLayersError> for FlushLayerError {
     563            0 :     fn from(e: CreateImageLayersError) -> Self {
     564            0 :         match e {
     565            0 :             CreateImageLayersError::Cancelled => FlushLayerError::Cancelled,
     566            0 :             any => FlushLayerError::CreateImageLayersError(any),
     567              :         }
     568            0 :     }
     569              : }
     570              : 
     571              : impl From<PageReconstructError> for CreateImageLayersError {
     572            0 :     fn from(e: PageReconstructError) -> Self {
     573            0 :         match e {
     574            0 :             PageReconstructError::Cancelled => CreateImageLayersError::Cancelled,
     575            0 :             _ => CreateImageLayersError::PageReconstructError(e),
     576              :         }
     577            0 :     }
     578              : }
     579              : 
     580              : impl From<GetVectoredError> for CreateImageLayersError {
     581            0 :     fn from(e: GetVectoredError) -> Self {
     582            0 :         match e {
     583            0 :             GetVectoredError::Cancelled => CreateImageLayersError::Cancelled,
     584            0 :             _ => CreateImageLayersError::GetVectoredError(e),
     585              :         }
     586            0 :     }
     587              : }
     588              : 
     589              : impl From<GetReadyAncestorError> for PageReconstructError {
     590            2 :     fn from(e: GetReadyAncestorError) -> Self {
     591            2 :         use GetReadyAncestorError::*;
     592            2 :         match e {
     593            0 :             AncestorStopping(tid) => PageReconstructError::AncestorStopping(tid),
     594            0 :             AncestorLsnTimeout(wait_err) => PageReconstructError::AncestorLsnTimeout(wait_err),
     595            0 :             Cancelled => PageReconstructError::Cancelled,
     596            2 :             Other(other) => PageReconstructError::Other(other),
     597              :         }
     598            2 :     }
     599              : }
     600              : 
     601              : #[derive(
     602              :     Eq,
     603              :     PartialEq,
     604              :     Debug,
     605              :     Copy,
     606              :     Clone,
     607          138 :     strum_macros::EnumString,
     608            0 :     strum_macros::Display,
     609            0 :     serde_with::DeserializeFromStr,
     610              :     serde_with::SerializeDisplay,
     611              : )]
     612              : #[strum(serialize_all = "kebab-case")]
     613              : pub enum GetVectoredImpl {
     614              :     Sequential,
     615              :     Vectored,
     616              : }
     617              : 
     618              : pub(crate) enum WaitLsnWaiter<'a> {
     619              :     Timeline(&'a Timeline),
     620              :     Tenant,
     621              :     PageService,
     622              : }
     623              : 
     624              : /// Argument to [`Timeline::shutdown`].
     625              : #[derive(Debug, Clone, Copy)]
     626              : pub(crate) enum ShutdownMode {
     627              :     /// Graceful shutdown, may do a lot of I/O as we flush any open layers to disk and then
     628              :     /// also to remote storage.  This method can easily take multiple seconds for a busy timeline.
     629              :     ///
     630              :     /// While we are flushing, we continue to accept read I/O for LSNs ingested before
     631              :     /// the call to [`Timeline::shutdown`].
     632              :     FreezeAndFlush,
     633              :     /// Shut down immediately, without waiting for any open layers to flush.
     634              :     Hard,
     635              : }
     636              : 
     637              : /// Public interface functions
     638              : impl Timeline {
     639              :     /// Get the LSN where this branch was created
     640            8 :     pub(crate) fn get_ancestor_lsn(&self) -> Lsn {
     641            8 :         self.ancestor_lsn
     642            8 :     }
     643              : 
     644              :     /// Get the ancestor's timeline id
     645           14 :     pub(crate) fn get_ancestor_timeline_id(&self) -> Option<TimelineId> {
     646           14 :         self.ancestor_timeline
     647           14 :             .as_ref()
     648           14 :             .map(|ancestor| ancestor.timeline_id)
     649           14 :     }
     650              : 
     651              :     /// Lock and get timeline's GC cutoff
     652          724 :     pub(crate) fn get_latest_gc_cutoff_lsn(&self) -> RcuReadGuard<Lsn> {
     653          724 :         self.latest_gc_cutoff_lsn.read()
     654          724 :     }
     655              : 
     656              :     /// Look up given page version.
     657              :     ///
     658              :     /// If a remote layer file is needed, it is downloaded as part of this
     659              :     /// call.
     660              :     ///
     661              :     /// This method enforces [`Self::timeline_get_throttle`] internally.
     662              :     ///
     663              :     /// NOTE: It is considered an error to 'get' a key that doesn't exist. The
     664              :     /// abstraction above this needs to store suitable metadata to track what
     665              :     /// data exists with what keys, in separate metadata entries. If a
     666              :     /// non-existent key is requested, we may incorrectly return a value from
     667              :     /// an ancestor branch, for example, or waste a lot of cycles chasing the
     668              :     /// non-existing key.
     669              :     ///
     670              :     /// # Cancel-Safety
     671              :     ///
     672              :     /// This method is cancellation-safe.
     673              :     #[inline(always)]
     674       501761 :     pub(crate) async fn get(
     675       501761 :         &self,
     676       501761 :         key: Key,
     677       501761 :         lsn: Lsn,
     678       501761 :         ctx: &RequestContext,
     679       501761 :     ) -> Result<Bytes, PageReconstructError> {
     680       501761 :         self.timeline_get_throttle.throttle(ctx, 1).await;
     681       501761 :         self.get_impl(key, lsn, ctx).await
     682       501761 :     }
     683              :     /// Not subject to [`Self::timeline_get_throttle`].
     684       502833 :     async fn get_impl(
     685       502833 :         &self,
     686       502833 :         key: Key,
     687       502833 :         lsn: Lsn,
     688       502833 :         ctx: &RequestContext,
     689       502833 :     ) -> Result<Bytes, PageReconstructError> {
     690       502833 :         if !lsn.is_valid() {
     691            0 :             return Err(PageReconstructError::Other(anyhow::anyhow!("Invalid LSN")));
     692       502833 :         }
     693       502833 : 
     694       502833 :         // This check is debug-only because of the cost of hashing, and because it's a double-check: we
     695       502833 :         // already checked the key against the shard_identity when looking up the Timeline from
     696       502833 :         // page_service.
     697       502833 :         debug_assert!(!self.shard_identity.is_key_disposable(&key));
     698              : 
     699              :         // XXX: structured stats collection for layer eviction here.
     700       502833 :         trace!(
     701            0 :             "get page request for {}@{} from task kind {:?}",
     702            0 :             key,
     703            0 :             lsn,
     704            0 :             ctx.task_kind()
     705            0 :         );
     706              : 
     707              :         // Check the page cache. We will get back the most recent page with lsn <= `lsn`.
     708              :         // The cached image can be returned directly if there is no WAL between the cached image
     709              :         // and requested LSN. The cached image can also be used to reduce the amount of WAL needed
     710              :         // for redo.
     711       502833 :         let cached_page_img = match self.lookup_cached_page(&key, lsn, ctx).await {
     712            0 :             Some((cached_lsn, cached_img)) => {
     713            0 :                 match cached_lsn.cmp(&lsn) {
     714            0 :                     Ordering::Less => {} // there might be WAL between cached_lsn and lsn, we need to check
     715              :                     Ordering::Equal => {
     716            0 :                         MATERIALIZED_PAGE_CACHE_HIT_DIRECT.inc();
     717            0 :                         return Ok(cached_img); // exact LSN match, return the image
     718              :                     }
     719              :                     Ordering::Greater => {
     720            0 :                         unreachable!("the returned lsn should never be after the requested lsn")
     721              :                     }
     722              :                 }
     723            0 :                 Some((cached_lsn, cached_img))
     724              :             }
     725       502833 :             None => None,
     726              :         };
     727              : 
     728       502833 :         let mut reconstruct_state = ValueReconstructState {
     729       502833 :             records: Vec::new(),
     730       502833 :             img: cached_page_img,
     731       502833 :         };
     732       502833 : 
     733       502833 :         let timer = crate::metrics::GET_RECONSTRUCT_DATA_TIME.start_timer();
     734       502833 :         let path = self
     735       502833 :             .get_reconstruct_data(key, lsn, &mut reconstruct_state, ctx)
     736        34104 :             .await?;
     737       502723 :         timer.stop_and_record();
     738       502723 : 
     739       502723 :         let start = Instant::now();
     740       502723 :         let res = self.reconstruct_value(key, lsn, reconstruct_state).await;
     741       502723 :         let elapsed = start.elapsed();
     742       502723 :         crate::metrics::RECONSTRUCT_TIME
     743       502723 :             .for_result(&res)
     744       502723 :             .observe(elapsed.as_secs_f64());
     745       502723 : 
     746       502723 :         if cfg!(feature = "testing") && res.is_err() {
     747              :             // it can only be walredo issue
     748              :             use std::fmt::Write;
     749              : 
     750            0 :             let mut msg = String::new();
     751            0 : 
     752            0 :             path.into_iter().for_each(|(res, cont_lsn, layer)| {
     753            0 :                 writeln!(
     754            0 :                     msg,
     755            0 :                     "- layer traversal: result {res:?}, cont_lsn {cont_lsn}, layer: {}",
     756            0 :                     layer(),
     757            0 :                 )
     758            0 :                 .expect("string grows")
     759            0 :             });
     760            0 : 
     761            0 :             // this is to rule out or provide evidence that we could in some cases read a duplicate
     762            0 :             // walrecord
     763            0 :             tracing::info!("walredo failed, path:\n{msg}");
     764       502723 :         }
     765              : 
     766       502723 :         res
     767       502833 :     }
     768              : 
     769              :     pub(crate) const MAX_GET_VECTORED_KEYS: u64 = 32;
     770              : 
     771              :     /// Look up multiple page versions at a given LSN
     772              :     ///
     773              :     /// This naive implementation will be replaced with a more efficient one
     774              :     /// which actually vectorizes the read path.
     775          568 :     pub(crate) async fn get_vectored(
     776          568 :         &self,
     777          568 :         keyspace: KeySpace,
     778          568 :         lsn: Lsn,
     779          568 :         ctx: &RequestContext,
     780          568 :     ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
     781          568 :         if !lsn.is_valid() {
     782            0 :             return Err(GetVectoredError::InvalidLsn(lsn));
     783          568 :         }
     784          568 : 
     785          568 :         let key_count = keyspace.total_size().try_into().unwrap();
     786          568 :         if key_count > Timeline::MAX_GET_VECTORED_KEYS {
     787            0 :             return Err(GetVectoredError::Oversized(key_count));
     788          568 :         }
     789              : 
     790         1136 :         for range in &keyspace.ranges {
     791          568 :             let mut key = range.start;
     792         1320 :             while key != range.end {
     793          752 :                 assert!(!self.shard_identity.is_key_disposable(&key));
     794          752 :                 key = key.next();
     795              :             }
     796              :         }
     797              : 
     798          568 :         trace!(
     799            0 :             "get vectored request for {:?}@{} from task kind {:?} will use {} implementation",
     800            0 :             keyspace,
     801            0 :             lsn,
     802            0 :             ctx.task_kind(),
     803            0 :             self.conf.get_vectored_impl
     804            0 :         );
     805              : 
     806          568 :         let start = crate::metrics::GET_VECTORED_LATENCY
     807          568 :             .for_task_kind(ctx.task_kind())
     808          568 :             .map(|metric| (metric, Instant::now()));
     809              : 
     810              :         // start counting after throttle so that throttle time
     811              :         // is always less than observation time
     812          568 :         let throttled = self
     813          568 :             .timeline_get_throttle
     814          568 :             .throttle(ctx, key_count as usize)
     815            0 :             .await;
     816              : 
     817          568 :         let res = match self.conf.get_vectored_impl {
     818              :             GetVectoredImpl::Sequential => {
     819          568 :                 self.get_vectored_sequential_impl(keyspace, lsn, ctx).await
     820              :             }
     821              :             GetVectoredImpl::Vectored => {
     822            0 :                 let vectored_res = self.get_vectored_impl(keyspace.clone(), lsn, ctx).await;
     823              : 
     824            0 :                 if self.conf.validate_vectored_get {
     825            0 :                     self.validate_get_vectored_impl(&vectored_res, keyspace, lsn, ctx)
     826            0 :                         .await;
     827            0 :                 }
     828              : 
     829            0 :                 vectored_res
     830              :             }
     831              :         };
     832              : 
     833          568 :         if let Some((metric, start)) = start {
     834            0 :             let elapsed = start.elapsed();
     835            0 :             let ex_throttled = if let Some(throttled) = throttled {
     836            0 :                 elapsed.checked_sub(throttled)
     837              :             } else {
     838            0 :                 Some(elapsed)
     839              :             };
     840              : 
     841            0 :             if let Some(ex_throttled) = ex_throttled {
     842            0 :                 metric.observe(ex_throttled.as_secs_f64());
     843            0 :             } else {
     844            0 :                 use utils::rate_limit::RateLimit;
     845            0 :                 static LOGGED: Lazy<Mutex<RateLimit>> =
     846            0 :                     Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(10))));
     847            0 :                 let mut rate_limit = LOGGED.lock().unwrap();
     848            0 :                 rate_limit.call(|| {
     849            0 :                     warn!("error deducting time spent throttled; this message is logged at a global rate limit");
     850            0 :                 });
     851            0 :             }
     852          568 :         }
     853              : 
     854          568 :         res
     855          568 :     }
     856              : 
     857              :     /// Not subject to [`Self::timeline_get_throttle`].
     858          578 :     pub(super) async fn get_vectored_sequential_impl(
     859          578 :         &self,
     860          578 :         keyspace: KeySpace,
     861          578 :         lsn: Lsn,
     862          578 :         ctx: &RequestContext,
     863          578 :     ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
     864          578 :         let mut values = BTreeMap::new();
     865         1156 :         for range in keyspace.ranges {
     866          578 :             let mut key = range.start;
     867         1650 :             while key != range.end {
     868         1072 :                 let block = self.get_impl(key, lsn, ctx).await;
     869              : 
     870              :                 use PageReconstructError::*;
     871            0 :                 match block {
     872              :                     Err(Cancelled | AncestorStopping(_)) => {
     873            0 :                         return Err(GetVectoredError::Cancelled)
     874              :                     }
     875            0 :                     Err(Other(err)) if err.to_string().contains("could not find data for key") => {
     876            0 :                         return Err(GetVectoredError::MissingKey(key))
     877              :                     }
     878         1072 :                     _ => {
     879         1072 :                         values.insert(key, block);
     880         1072 :                         key = key.next();
     881         1072 :                     }
     882              :                 }
     883              :             }
     884              :         }
     885              : 
     886          578 :         Ok(values)
     887          578 :     }
     888              : 
     889           12 :     pub(super) async fn get_vectored_impl(
     890           12 :         &self,
     891           12 :         keyspace: KeySpace,
     892           12 :         lsn: Lsn,
     893           12 :         ctx: &RequestContext,
     894           12 :     ) -> Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError> {
     895           12 :         let mut reconstruct_state = ValuesReconstructState::new();
     896           12 : 
     897           12 :         self.get_vectored_reconstruct_data(keyspace, lsn, &mut reconstruct_state, ctx)
     898           41 :             .await?;
     899              : 
     900           12 :         let mut results: BTreeMap<Key, Result<Bytes, PageReconstructError>> = BTreeMap::new();
     901          374 :         for (key, res) in reconstruct_state.keys {
     902          362 :             match res {
     903            0 :                 Err(err) => {
     904            0 :                     results.insert(key, Err(err));
     905            0 :                 }
     906          362 :                 Ok(state) => {
     907          362 :                     let state = ValueReconstructState::from(state);
     908              : 
     909          362 :                     let reconstruct_res = self.reconstruct_value(key, lsn, state).await;
     910          362 :                     results.insert(key, reconstruct_res);
     911              :                 }
     912              :             }
     913              :         }
     914              : 
     915           12 :         Ok(results)
     916           12 :     }
     917              : 
     918              :     /// Not subject to [`Self::timeline_get_throttle`].
     919           10 :     pub(super) async fn validate_get_vectored_impl(
     920           10 :         &self,
     921           10 :         vectored_res: &Result<BTreeMap<Key, Result<Bytes, PageReconstructError>>, GetVectoredError>,
     922           10 :         keyspace: KeySpace,
     923           10 :         lsn: Lsn,
     924           10 :         ctx: &RequestContext,
     925           10 :     ) {
     926           10 :         let sequential_res = self
     927           10 :             .get_vectored_sequential_impl(keyspace.clone(), lsn, ctx)
     928           20 :             .await;
     929              : 
     930            0 :         fn errors_match(lhs: &GetVectoredError, rhs: &GetVectoredError) -> bool {
     931            0 :             use GetVectoredError::*;
     932            0 :             match (lhs, rhs) {
     933            0 :                 (Oversized(l), Oversized(r)) => l == r,
     934            0 :                 (InvalidLsn(l), InvalidLsn(r)) => l == r,
     935            0 :                 (MissingKey(l), MissingKey(r)) => l == r,
     936            0 :                 (GetReadyAncestorError(_), GetReadyAncestorError(_)) => true,
     937            0 :                 (Other(_), Other(_)) => true,
     938            0 :                 _ => false,
     939              :             }
     940            0 :         }
     941              : 
     942           10 :         match (&sequential_res, vectored_res) {
     943            0 :             (Err(GetVectoredError::Cancelled), _) => {},
     944            0 :             (_, Err(GetVectoredError::Cancelled)) => {},
     945            0 :             (Err(seq_err), Ok(_)) => {
     946            0 :                 panic!(concat!("Sequential get failed with {}, but vectored get did not",
     947            0 :                                " - keyspace={:?} lsn={}"),
     948            0 :                        seq_err, keyspace, lsn) },
     949            0 :             (Ok(_), Err(vec_err)) => {
     950            0 :                 panic!(concat!("Vectored get failed with {}, but sequential get did not",
     951            0 :                                " - keyspace={:?} lsn={}"),
     952            0 :                        vec_err, keyspace, lsn) },
     953            0 :             (Err(seq_err), Err(vec_err)) => {
     954            0 :                 assert!(errors_match(seq_err, vec_err),
     955            0 :                         "Mismatched errors: {seq_err} != {vec_err} - keyspace={keyspace:?} lsn={lsn}")},
     956           10 :             (Ok(seq_values), Ok(vec_values)) => {
     957          320 :                 seq_values.iter().zip(vec_values.iter()).for_each(|((seq_key, seq_res), (vec_key, vec_res))| {
     958          320 :                     assert_eq!(seq_key, vec_key);
     959          320 :                     match (seq_res, vec_res) {
     960          320 :                         (Ok(seq_blob), Ok(vec_blob)) => {
     961          320 :                             Self::validate_key_equivalence(seq_key, &keyspace, lsn, seq_blob, vec_blob);
     962          320 :                         },
     963            0 :                         (Err(err), Ok(_)) => {
     964            0 :                             panic!(
     965            0 :                                 concat!("Sequential get failed with {} for key {}, but vectored get did not",
     966            0 :                                         " - keyspace={:?} lsn={}"),
     967            0 :                                 err, seq_key, keyspace, lsn) },
     968            0 :                         (Ok(_), Err(err)) => {
     969            0 :                             panic!(
     970            0 :                                 concat!("Vectored get failed with {} for key {}, but sequential get did not",
     971            0 :                                         " - keyspace={:?} lsn={}"),
     972            0 :                                 err, seq_key, keyspace, lsn) },
     973            0 :                         (Err(_), Err(_)) => {}
     974              :                     }
     975          320 :                 })
     976              :             }
     977              :         }
     978           10 :     }
     979              : 
     980          320 :     fn validate_key_equivalence(
     981          320 :         key: &Key,
     982          320 :         keyspace: &KeySpace,
     983          320 :         lsn: Lsn,
     984          320 :         seq: &Bytes,
     985          320 :         vec: &Bytes,
     986          320 :     ) {
     987          320 :         if *key == AUX_FILES_KEY {
     988              :             // The value reconstruct of AUX_FILES_KEY from records is not deterministic
     989              :             // since it uses a hash map under the hood. Hence, deserialise both results
     990              :             // before comparing.
     991            0 :             let seq_aux_dir_res = AuxFilesDirectory::des(seq);
     992            0 :             let vec_aux_dir_res = AuxFilesDirectory::des(vec);
     993            0 :             match (&seq_aux_dir_res, &vec_aux_dir_res) {
     994            0 :                 (Ok(seq_aux_dir), Ok(vec_aux_dir)) => {
     995            0 :                     assert_eq!(
     996              :                         seq_aux_dir, vec_aux_dir,
     997            0 :                         "Mismatch for key {} - keyspace={:?} lsn={}",
     998              :                         key, keyspace, lsn
     999              :                     );
    1000              :                 }
    1001            0 :                 (Err(_), Err(_)) => {}
    1002              :                 _ => {
    1003            0 :                     panic!("Mismatch for {key}: {seq_aux_dir_res:?} != {vec_aux_dir_res:?}");
    1004              :                 }
    1005              :             }
    1006              :         } else {
    1007              :             // All other keys should reconstruct deterministically, so we simply compare the blobs.
    1008          320 :             assert_eq!(
    1009              :                 seq, vec,
    1010            0 :                 "Image mismatch for key {key} - keyspace={keyspace:?} lsn={lsn}"
    1011              :             );
    1012              :         }
    1013          320 :     }
    1014              : 
    1015              :     /// Get last or prev record separately. Same as get_last_record_rlsn().last/prev.
    1016      3921526 :     pub(crate) fn get_last_record_lsn(&self) -> Lsn {
    1017      3921526 :         self.last_record_lsn.load().last
    1018      3921526 :     }
    1019              : 
    1020            0 :     pub(crate) fn get_prev_record_lsn(&self) -> Lsn {
    1021            0 :         self.last_record_lsn.load().prev
    1022            0 :     }
    1023              : 
    1024              :     /// Atomically get both last and prev.
    1025          214 :     pub(crate) fn get_last_record_rlsn(&self) -> RecordLsn {
    1026          214 :         self.last_record_lsn.load()
    1027          214 :     }
    1028              : 
    1029         1330 :     pub(crate) fn get_disk_consistent_lsn(&self) -> Lsn {
    1030         1330 :         self.disk_consistent_lsn.load()
    1031         1330 :     }
    1032              : 
    1033              :     /// remote_consistent_lsn from the perspective of the tenant's current generation,
    1034              :     /// not validated with control plane yet.
    1035              :     /// See [`Self::get_remote_consistent_lsn_visible`].
    1036            0 :     pub(crate) fn get_remote_consistent_lsn_projected(&self) -> Option<Lsn> {
    1037            0 :         if let Some(remote_client) = &self.remote_client {
    1038            0 :             remote_client.remote_consistent_lsn_projected()
    1039              :         } else {
    1040            0 :             None
    1041              :         }
    1042            0 :     }
    1043              : 
    1044              :     /// remote_consistent_lsn which the tenant is guaranteed not to go backward from,
    1045              :     /// i.e. a value of remote_consistent_lsn_projected which has undergone
    1046              :     /// generation validation in the deletion queue.
    1047            0 :     pub(crate) fn get_remote_consistent_lsn_visible(&self) -> Option<Lsn> {
    1048            0 :         if let Some(remote_client) = &self.remote_client {
    1049            0 :             remote_client.remote_consistent_lsn_visible()
    1050              :         } else {
    1051            0 :             None
    1052              :         }
    1053            0 :     }
    1054              : 
    1055              :     /// The sum of the file size of all historic layers in the layer map.
    1056              :     /// This method makes no distinction between local and remote layers.
    1057              :     /// Hence, the result **does not represent local filesystem usage**.
    1058            0 :     pub(crate) async fn layer_size_sum(&self) -> u64 {
    1059            0 :         let guard = self.layers.read().await;
    1060            0 :         let layer_map = guard.layer_map();
    1061            0 :         let mut size = 0;
    1062            0 :         for l in layer_map.iter_historic_layers() {
    1063            0 :             size += l.file_size();
    1064            0 :         }
    1065            0 :         size
    1066            0 :     }
    1067              : 
    1068            0 :     pub(crate) fn resident_physical_size(&self) -> u64 {
    1069            0 :         self.metrics.resident_physical_size_get()
    1070            0 :     }
    1071              : 
    1072            0 :     pub(crate) fn get_directory_metrics(&self) -> [u64; DirectoryKind::KINDS_NUM] {
    1073            0 :         array::from_fn(|idx| self.directory_metrics[idx].load(AtomicOrdering::Relaxed))
    1074            0 :     }
    1075              : 
    1076              :     ///
    1077              :     /// Wait until WAL has been received and processed up to this LSN.
    1078              :     ///
    1079              :     /// You should call this before any of the other get_* or list_* functions. Calling
    1080              :     /// those functions with an LSN that has been processed yet is an error.
    1081              :     ///
    1082       226805 :     pub(crate) async fn wait_lsn(
    1083       226805 :         &self,
    1084       226805 :         lsn: Lsn,
    1085       226805 :         who_is_waiting: WaitLsnWaiter<'_>,
    1086       226805 :         ctx: &RequestContext, /* Prepare for use by cancellation */
    1087       226805 :     ) -> Result<(), WaitLsnError> {
    1088       226805 :         if self.cancel.is_cancelled() {
    1089            0 :             return Err(WaitLsnError::Shutdown);
    1090       226805 :         } else if !self.is_active() {
    1091            0 :             return Err(WaitLsnError::BadState);
    1092       226805 :         }
    1093       226805 : 
    1094       226805 :         if cfg!(debug_assertions) {
    1095       226805 :             match ctx.task_kind() {
    1096              :                 TaskKind::WalReceiverManager
    1097              :                 | TaskKind::WalReceiverConnectionHandler
    1098              :                 | TaskKind::WalReceiverConnectionPoller => {
    1099            0 :                     let is_myself = match who_is_waiting {
    1100            0 :                         WaitLsnWaiter::Timeline(waiter) => Weak::ptr_eq(&waiter.myself, &self.myself),
    1101            0 :                         WaitLsnWaiter::Tenant | WaitLsnWaiter::PageService => unreachable!("tenant or page_service context are not expected to have task kind {:?}", ctx.task_kind()),
    1102              :                     };
    1103            0 :                     if is_myself {
    1104            0 :                         if let Err(current) = self.last_record_lsn.would_wait_for(lsn) {
    1105              :                             // walingest is the only one that can advance last_record_lsn; it should make sure to never reach here
    1106            0 :                             panic!("this timeline's walingest task is calling wait_lsn({lsn}) but we only have last_record_lsn={current}; would deadlock");
    1107            0 :                         }
    1108            0 :                     } else {
    1109            0 :                         // if another  timeline's  is waiting for us, there's no deadlock risk because
    1110            0 :                         // our walreceiver task can make progress independent of theirs
    1111            0 :                     }
    1112              :                 }
    1113       226805 :                 _ => {}
    1114              :             }
    1115            0 :         }
    1116              : 
    1117       226805 :         let _timer = crate::metrics::WAIT_LSN_TIME.start_timer();
    1118       226805 : 
    1119       226805 :         match self
    1120       226805 :             .last_record_lsn
    1121       226805 :             .wait_for_timeout(lsn, self.conf.wait_lsn_timeout)
    1122            0 :             .await
    1123              :         {
    1124       226805 :             Ok(()) => Ok(()),
    1125            0 :             Err(e) => {
    1126            0 :                 use utils::seqwait::SeqWaitError::*;
    1127            0 :                 match e {
    1128            0 :                     Shutdown => Err(WaitLsnError::Shutdown),
    1129              :                     Timeout => {
    1130              :                         // don't count the time spent waiting for lock below, and also in walreceiver.status(), towards the wait_lsn_time_histo
    1131            0 :                         drop(_timer);
    1132            0 :                         let walreceiver_status = self.walreceiver_status();
    1133            0 :                         Err(WaitLsnError::Timeout(format!(
    1134            0 :                         "Timed out while waiting for WAL record at LSN {} to arrive, last_record_lsn {} disk consistent LSN={}, WalReceiver status: {}",
    1135            0 :                         lsn,
    1136            0 :                         self.get_last_record_lsn(),
    1137            0 :                         self.get_disk_consistent_lsn(),
    1138            0 :                         walreceiver_status,
    1139            0 :                     )))
    1140              :                     }
    1141              :                 }
    1142              :             }
    1143              :         }
    1144       226805 :     }
    1145              : 
    1146            0 :     pub(crate) fn walreceiver_status(&self) -> String {
    1147            0 :         match &*self.walreceiver.lock().unwrap() {
    1148            0 :             None => "stopping or stopped".to_string(),
    1149            0 :             Some(walreceiver) => match walreceiver.status() {
    1150            0 :                 Some(status) => status.to_human_readable_string(),
    1151            0 :                 None => "Not active".to_string(),
    1152              :             },
    1153              :         }
    1154            0 :     }
    1155              : 
    1156              :     /// Check that it is valid to request operations with that lsn.
    1157          218 :     pub(crate) fn check_lsn_is_in_scope(
    1158          218 :         &self,
    1159          218 :         lsn: Lsn,
    1160          218 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    1161          218 :     ) -> anyhow::Result<()> {
    1162          218 :         ensure!(
    1163          218 :             lsn >= **latest_gc_cutoff_lsn,
    1164            4 :             "LSN {} is earlier than latest GC horizon {} (we might've already garbage collected needed data)",
    1165            4 :             lsn,
    1166            4 :             **latest_gc_cutoff_lsn,
    1167              :         );
    1168          214 :         Ok(())
    1169          218 :     }
    1170              : 
    1171              :     /// Flush to disk all data that was written with the put_* functions
    1172         1396 :     #[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))]
    1173              :     pub(crate) async fn freeze_and_flush(&self) -> anyhow::Result<()> {
    1174              :         let to_lsn = self.freeze_inmem_layer(false).await;
    1175              :         self.flush_frozen_layers_and_wait(to_lsn).await
    1176              :     }
    1177              : 
    1178              :     /// If there is no writer, and conditions for rolling the latest layer are met, then freeze it.
    1179              :     ///
    1180              :     /// This is for use in background housekeeping, to provide guarantees of layers closing eventually
    1181              :     /// even if there are no ongoing writes to drive that.
    1182          510 :     async fn maybe_freeze_ephemeral_layer(&self) {
    1183          510 :         let Ok(_write_guard) = self.write_lock.try_lock() else {
    1184              :             // If the write lock is held, there is an active wal receiver: rolling open layers
    1185              :             // is their responsibility while they hold this lock.
    1186            0 :             return;
    1187              :         };
    1188              : 
    1189          510 :         let Ok(layers_guard) = self.layers.try_read() else {
    1190              :             // Don't block if the layer lock is busy
    1191            0 :             return;
    1192              :         };
    1193              : 
    1194          510 :         let Some(open_layer) = &layers_guard.layer_map().open_layer else {
    1195              :             // If there is no open layer, we have no layer freezing to do.  However, we might need to generate
    1196              :             // some updates to disk_consistent_lsn and remote_consistent_lsn, in case we ingested some WAL regions
    1197              :             // that didn't result in writes to this shard.
    1198              : 
    1199              :             // Must not hold the layers lock while waiting for a flush.
    1200          510 :             drop(layers_guard);
    1201          510 : 
    1202          510 :             let last_record_lsn = self.get_last_record_lsn();
    1203          510 :             let disk_consistent_lsn = self.get_disk_consistent_lsn();
    1204          510 :             if last_record_lsn > disk_consistent_lsn {
    1205              :                 // We have no open layer, but disk_consistent_lsn is behind the last record: this indicates
    1206              :                 // we are a sharded tenant and have skipped some WAL
    1207            0 :                 let last_freeze_ts = *self.last_freeze_ts.read().unwrap();
    1208            0 :                 if last_freeze_ts.elapsed() >= self.get_checkpoint_timeout() {
    1209              :                     // This should be somewhat rare, so we log it at INFO level.
    1210              :                     //
    1211              :                     // We checked for checkpoint timeout so that a shard without any
    1212              :                     // data ingested (yet) doesn't write a remote index as soon as it
    1213              :                     // sees its LSN advance: we only do this if we've been layer-less
    1214              :                     // for some time.
    1215            0 :                     tracing::info!(
    1216            0 :                         "Advancing disk_consistent_lsn past WAL ingest gap {} -> {}",
    1217            0 :                         disk_consistent_lsn,
    1218            0 :                         last_record_lsn
    1219            0 :                     );
    1220              : 
    1221              :                     // The flush loop will update remote consistent LSN as well as disk consistent LSN.
    1222            0 :                     self.flush_frozen_layers_and_wait(last_record_lsn)
    1223            0 :                         .await
    1224            0 :                         .ok();
    1225            0 :                 }
    1226          510 :             }
    1227              : 
    1228          510 :             return;
    1229              :         };
    1230              : 
    1231            0 :         let Some(current_size) = open_layer.try_len() else {
    1232              :             // Unexpected: since we hold the write guard, nobody else should be writing to this layer, so
    1233              :             // read lock to get size should always succeed.
    1234            0 :             tracing::warn!("Lock conflict while reading size of open layer");
    1235            0 :             return;
    1236              :         };
    1237              : 
    1238            0 :         let current_lsn = self.get_last_record_lsn();
    1239              : 
    1240            0 :         let checkpoint_distance_override = open_layer.tick().await;
    1241              : 
    1242            0 :         if let Some(size_override) = checkpoint_distance_override {
    1243            0 :             if current_size > size_override {
    1244              :                 // This is not harmful, but it only happens in relatively rare cases where
    1245              :                 // time-based checkpoints are not happening fast enough to keep the amount of
    1246              :                 // ephemeral data within configured limits.  It's a sign of stress on the system.
    1247            0 :                 tracing::info!("Early-rolling open layer at size {current_size} (limit {size_override}) due to dirty data pressure");
    1248            0 :             }
    1249            0 :         }
    1250              : 
    1251            0 :         let checkpoint_distance =
    1252            0 :             checkpoint_distance_override.unwrap_or(self.get_checkpoint_distance());
    1253            0 : 
    1254            0 :         if self.should_roll(
    1255            0 :             current_size,
    1256            0 :             current_size,
    1257            0 :             checkpoint_distance,
    1258            0 :             self.get_last_record_lsn(),
    1259            0 :             self.last_freeze_at.load(),
    1260            0 :             open_layer.get_opened_at(),
    1261            0 :         ) {
    1262            0 :             match open_layer.info() {
    1263            0 :                 InMemoryLayerInfo::Frozen { lsn_start, lsn_end } => {
    1264            0 :                     // We may reach this point if the layer was already frozen by not yet flushed: flushing
    1265            0 :                     // happens asynchronously in the background.
    1266            0 :                     tracing::debug!(
    1267            0 :                         "Not freezing open layer, it's already frozen ({lsn_start}..{lsn_end})"
    1268            0 :                     );
    1269              :                 }
    1270              :                 InMemoryLayerInfo::Open { .. } => {
    1271              :                     // Upgrade to a write lock and freeze the layer
    1272            0 :                     drop(layers_guard);
    1273            0 :                     let mut layers_guard = self.layers.write().await;
    1274            0 :                     layers_guard
    1275            0 :                         .try_freeze_in_memory_layer(current_lsn, &self.last_freeze_at)
    1276            0 :                         .await;
    1277              :                 }
    1278              :             }
    1279            0 :             self.flush_frozen_layers();
    1280            0 :         }
    1281          510 :     }
    1282              : 
    1283              :     /// Outermost timeline compaction operation; downloads needed layers.
    1284          510 :     pub(crate) async fn compact(
    1285          510 :         self: &Arc<Self>,
    1286          510 :         cancel: &CancellationToken,
    1287          510 :         flags: EnumSet<CompactFlags>,
    1288          510 :         ctx: &RequestContext,
    1289          510 :     ) -> Result<(), CompactionError> {
    1290          510 :         // most likely the cancellation token is from background task, but in tests it could be the
    1291          510 :         // request task as well.
    1292          510 : 
    1293          510 :         let prepare = async move {
    1294          510 :             let guard = self.compaction_lock.lock().await;
    1295              : 
    1296          510 :             let permit = super::tasks::concurrent_background_tasks_rate_limit_permit(
    1297          510 :                 BackgroundLoopKind::Compaction,
    1298          510 :                 ctx,
    1299          510 :             )
    1300            0 :             .await;
    1301              : 
    1302          510 :             (guard, permit)
    1303          510 :         };
    1304              : 
    1305              :         // Prior to compaction, check if an open ephemeral layer should be closed: this provides
    1306              :         // background enforcement of checkpoint interval if there is no active WAL receiver, to avoid keeping
    1307              :         // an ephemeral layer open forever when idle.
    1308          510 :         self.maybe_freeze_ephemeral_layer().await;
    1309              : 
    1310              :         // this wait probably never needs any "long time spent" logging, because we already nag if
    1311              :         // compaction task goes over it's period (20s) which is quite often in production.
    1312          510 :         let (_guard, _permit) = tokio::select! {
    1313          510 :             tuple = prepare => { tuple },
    1314              :             _ = self.cancel.cancelled() => return Ok(()),
    1315              :             _ = cancel.cancelled() => return Ok(()),
    1316              :         };
    1317              : 
    1318          510 :         let last_record_lsn = self.get_last_record_lsn();
    1319          510 : 
    1320          510 :         // Last record Lsn could be zero in case the timeline was just created
    1321          510 :         if !last_record_lsn.is_valid() {
    1322            0 :             warn!("Skipping compaction for potentially just initialized timeline, it has invalid last record lsn: {last_record_lsn}");
    1323            0 :             return Ok(());
    1324          510 :         }
    1325          510 : 
    1326          510 :         match self.get_compaction_algorithm() {
    1327            0 :             CompactionAlgorithm::Tiered => self.compact_tiered(cancel, ctx).await,
    1328        89659 :             CompactionAlgorithm::Legacy => self.compact_legacy(cancel, flags, ctx).await,
    1329              :         }
    1330          510 :     }
    1331              : 
    1332              :     /// Mutate the timeline with a [`TimelineWriter`].
    1333      3977036 :     pub(crate) async fn writer(&self) -> TimelineWriter<'_> {
    1334      3977036 :         TimelineWriter {
    1335      3977036 :             tl: self,
    1336      3977036 :             write_guard: self.write_lock.lock().await,
    1337              :         }
    1338      3977036 :     }
    1339              : 
    1340            0 :     pub(crate) fn activate(
    1341            0 :         self: &Arc<Self>,
    1342            0 :         parent: Arc<crate::tenant::Tenant>,
    1343            0 :         broker_client: BrokerClientChannel,
    1344            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    1345            0 :         ctx: &RequestContext,
    1346            0 :     ) {
    1347            0 :         if self.tenant_shard_id.is_shard_zero() {
    1348            0 :             // Logical size is only maintained accurately on shard zero.
    1349            0 :             self.spawn_initial_logical_size_computation_task(ctx);
    1350            0 :         }
    1351            0 :         self.launch_wal_receiver(ctx, broker_client);
    1352            0 :         self.set_state(TimelineState::Active);
    1353            0 :         self.launch_eviction_task(parent, background_jobs_can_start);
    1354            0 :     }
    1355              : 
    1356              :     /// After this function returns, there are no timeline-scoped tasks are left running.
    1357              :     ///
    1358              :     /// The preferred pattern for is:
    1359              :     /// - in any spawned tasks, keep Timeline::guard open + Timeline::cancel / child token
    1360              :     /// - if early shutdown (not just cancellation) of a sub-tree of tasks is required,
    1361              :     ///   go the extra mile and keep track of JoinHandles
    1362              :     /// - Keep track of JoinHandles using a passed-down `Arc<Mutex<Option<JoinSet>>>` or similar,
    1363              :     ///   instead of spawning directly on a runtime. It is a more composable / testable pattern.
    1364              :     ///
    1365              :     /// For legacy reasons, we still have multiple tasks spawned using
    1366              :     /// `task_mgr::spawn(X, Some(tenant_id), Some(timeline_id))`.
    1367              :     /// We refer to these as "timeline-scoped task_mgr tasks".
    1368              :     /// Some of these tasks are already sensitive to Timeline::cancel while others are
    1369              :     /// not sensitive to Timeline::cancel and instead respect [`task_mgr::shutdown_token`]
    1370              :     /// or [`task_mgr::shutdown_watcher`].
    1371              :     /// We want to gradually convert the code base away from these.
    1372              :     ///
    1373              :     /// Here is an inventory of timeline-scoped task_mgr tasks that are still sensitive to
    1374              :     /// `task_mgr::shutdown_{token,watcher}` (there are also tenant-scoped and global-scoped
    1375              :     /// ones that aren't mentioned here):
    1376              :     /// - [`TaskKind::TimelineDeletionWorker`]
    1377              :     ///    - NB: also used for tenant deletion
    1378              :     /// - [`TaskKind::RemoteUploadTask`]`
    1379              :     /// - [`TaskKind::InitialLogicalSizeCalculation`]
    1380              :     /// - [`TaskKind::DownloadAllRemoteLayers`] (can we get rid of it?)
    1381              :     // Inventory of timeline-scoped task_mgr tasks that use spawn but aren't sensitive:
    1382              :     /// - [`TaskKind::Eviction`]
    1383              :     /// - [`TaskKind::LayerFlushTask`]
    1384              :     /// - [`TaskKind::OndemandLogicalSizeCalculation`]
    1385              :     /// - [`TaskKind::GarbageCollector`] (immediate_gc is timeline-scoped)
    1386            8 :     pub(crate) async fn shutdown(&self, mode: ShutdownMode) {
    1387            8 :         debug_assert_current_span_has_tenant_and_timeline_id();
    1388              : 
    1389            8 :         let try_freeze_and_flush = match mode {
    1390            6 :             ShutdownMode::FreezeAndFlush => true,
    1391            2 :             ShutdownMode::Hard => false,
    1392              :         };
    1393              : 
    1394              :         // Regardless of whether we're going to try_freeze_and_flush
    1395              :         // or not, stop ingesting any more data. Walreceiver only provides
    1396              :         // cancellation but no "wait until gone", because it uses the Timeline::gate.
    1397              :         // So, only after the self.gate.close() below will we know for sure that
    1398              :         // no walreceiver tasks are left.
    1399              :         // For `try_freeze_and_flush=true`, this means that we might still be ingesting
    1400              :         // data during the call to `self.freeze_and_flush()` below.
    1401              :         // That's not ideal, but, we don't have the concept of a ChildGuard,
    1402              :         // which is what we'd need to properly model early shutdown of the walreceiver
    1403              :         // task sub-tree before the other Timeline task sub-trees.
    1404            8 :         let walreceiver = self.walreceiver.lock().unwrap().take();
    1405            8 :         tracing::debug!(
    1406            0 :             is_some = walreceiver.is_some(),
    1407            0 :             "Waiting for WalReceiverManager..."
    1408            0 :         );
    1409            8 :         if let Some(walreceiver) = walreceiver {
    1410            0 :             walreceiver.cancel();
    1411            8 :         }
    1412              :         // ... and inform any waiters for newer LSNs that there won't be any.
    1413            8 :         self.last_record_lsn.shutdown();
    1414            8 : 
    1415            8 :         if try_freeze_and_flush {
    1416              :             // we shut down walreceiver above, so, we won't add anything more
    1417              :             // to the InMemoryLayer; freeze it and wait for all frozen layers
    1418              :             // to reach the disk & upload queue, then shut the upload queue and
    1419              :             // wait for it to drain.
    1420            6 :             match self.freeze_and_flush().await {
    1421              :                 Ok(_) => {
    1422              :                     // drain the upload queue
    1423            6 :                     if let Some(client) = self.remote_client.as_ref() {
    1424              :                         // if we did not wait for completion here, it might be our shutdown process
    1425              :                         // didn't wait for remote uploads to complete at all, as new tasks can forever
    1426              :                         // be spawned.
    1427              :                         //
    1428              :                         // what is problematic is the shutting down of RemoteTimelineClient, because
    1429              :                         // obviously it does not make sense to stop while we wait for it, but what
    1430              :                         // about corner cases like s3 suddenly hanging up?
    1431            6 :                         client.shutdown().await;
    1432            0 :                     }
    1433              :                 }
    1434            0 :                 Err(e) => {
    1435            0 :                     // Non-fatal.  Shutdown is infallible.  Failures to flush just mean that
    1436            0 :                     // we have some extra WAL replay to do next time the timeline starts.
    1437            0 :                     warn!("failed to freeze and flush: {e:#}");
    1438              :                 }
    1439              :             }
    1440            2 :         }
    1441              : 
    1442              :         // Signal any subscribers to our cancellation token to drop out
    1443            8 :         tracing::debug!("Cancelling CancellationToken");
    1444            8 :         self.cancel.cancel();
    1445              : 
    1446              :         // Transition the remote_client into a state where it's only useful for timeline deletion.
    1447              :         // (The deletion use case is why we can't just hook up remote_client to Self::cancel).)
    1448            8 :         if let Some(remote_client) = self.remote_client.as_ref() {
    1449            8 :             remote_client.stop();
    1450            8 :             // As documented in remote_client.stop()'s doc comment, it's our responsibility
    1451            8 :             // to shut down the upload queue tasks.
    1452            8 :             // TODO: fix that, task management should be encapsulated inside remote_client.
    1453            8 :             task_mgr::shutdown_tasks(
    1454            8 :                 Some(TaskKind::RemoteUploadTask),
    1455            8 :                 Some(self.tenant_shard_id),
    1456            8 :                 Some(self.timeline_id),
    1457            8 :             )
    1458            0 :             .await;
    1459            0 :         }
    1460              : 
    1461              :         // TODO: work toward making this a no-op. See this funciton's doc comment for more context.
    1462            8 :         tracing::debug!("Waiting for tasks...");
    1463            8 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), Some(self.timeline_id)).await;
    1464              : 
    1465              :         // Finally wait until any gate-holders are complete.
    1466              :         //
    1467              :         // TODO: once above shutdown_tasks is a no-op, we can close the gate before calling shutdown_tasks
    1468              :         // and use a TBD variant of shutdown_tasks that asserts that there were no tasks left.
    1469            8 :         self.gate.close().await;
    1470              : 
    1471            8 :         self.metrics.shutdown();
    1472            8 :     }
    1473              : 
    1474          322 :     pub(crate) fn set_state(&self, new_state: TimelineState) {
    1475          322 :         match (self.current_state(), new_state) {
    1476          322 :             (equal_state_1, equal_state_2) if equal_state_1 == equal_state_2 => {
    1477            2 :                 info!("Ignoring new state, equal to the existing one: {equal_state_2:?}");
    1478              :             }
    1479            0 :             (st, TimelineState::Loading) => {
    1480            0 :                 error!("ignoring transition from {st:?} into Loading state");
    1481              :             }
    1482            0 :             (TimelineState::Broken { .. }, new_state) => {
    1483            0 :                 error!("Ignoring state update {new_state:?} for broken timeline");
    1484              :             }
    1485              :             (TimelineState::Stopping, TimelineState::Active) => {
    1486            0 :                 error!("Not activating a Stopping timeline");
    1487              :             }
    1488          320 :             (_, new_state) => {
    1489          320 :                 self.state.send_replace(new_state);
    1490          320 :             }
    1491              :         }
    1492          322 :     }
    1493              : 
    1494            2 :     pub(crate) fn set_broken(&self, reason: String) {
    1495            2 :         let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
    1496            2 :         let broken_state = TimelineState::Broken {
    1497            2 :             reason,
    1498            2 :             backtrace: backtrace_str,
    1499            2 :         };
    1500            2 :         self.set_state(broken_state);
    1501            2 : 
    1502            2 :         // Although the Broken state is not equivalent to shutdown() (shutdown will be called
    1503            2 :         // later when this tenant is detach or the process shuts down), firing the cancellation token
    1504            2 :         // here avoids the need for other tasks to watch for the Broken state explicitly.
    1505            2 :         self.cancel.cancel();
    1506            2 :     }
    1507              : 
    1508       228361 :     pub(crate) fn current_state(&self) -> TimelineState {
    1509       228361 :         self.state.borrow().clone()
    1510       228361 :     }
    1511              : 
    1512            6 :     pub(crate) fn is_broken(&self) -> bool {
    1513            6 :         matches!(&*self.state.borrow(), TimelineState::Broken { .. })
    1514            6 :     }
    1515              : 
    1516       227023 :     pub(crate) fn is_active(&self) -> bool {
    1517       227023 :         self.current_state() == TimelineState::Active
    1518       227023 :     }
    1519              : 
    1520         1016 :     pub(crate) fn is_stopping(&self) -> bool {
    1521         1016 :         self.current_state() == TimelineState::Stopping
    1522         1016 :     }
    1523              : 
    1524            0 :     pub(crate) fn subscribe_for_state_updates(&self) -> watch::Receiver<TimelineState> {
    1525            0 :         self.state.subscribe()
    1526            0 :     }
    1527              : 
    1528       226807 :     pub(crate) async fn wait_to_become_active(
    1529       226807 :         &self,
    1530       226807 :         _ctx: &RequestContext, // Prepare for use by cancellation
    1531       226807 :     ) -> Result<(), TimelineState> {
    1532       226807 :         let mut receiver = self.state.subscribe();
    1533       226807 :         loop {
    1534       226807 :             let current_state = receiver.borrow().clone();
    1535       226807 :             match current_state {
    1536              :                 TimelineState::Loading => {
    1537            0 :                     receiver
    1538            0 :                         .changed()
    1539            0 :                         .await
    1540            0 :                         .expect("holding a reference to self");
    1541              :                 }
    1542              :                 TimelineState::Active { .. } => {
    1543       226805 :                     return Ok(());
    1544              :                 }
    1545              :                 TimelineState::Broken { .. } | TimelineState::Stopping => {
    1546              :                     // There's no chance the timeline can transition back into ::Active
    1547            2 :                     return Err(current_state);
    1548              :                 }
    1549              :             }
    1550              :         }
    1551       226807 :     }
    1552              : 
    1553            0 :     pub(crate) async fn layer_map_info(&self, reset: LayerAccessStatsReset) -> LayerMapInfo {
    1554            0 :         let guard = self.layers.read().await;
    1555            0 :         let layer_map = guard.layer_map();
    1556            0 :         let mut in_memory_layers = Vec::with_capacity(layer_map.frozen_layers.len() + 1);
    1557            0 :         if let Some(open_layer) = &layer_map.open_layer {
    1558            0 :             in_memory_layers.push(open_layer.info());
    1559            0 :         }
    1560            0 :         for frozen_layer in &layer_map.frozen_layers {
    1561            0 :             in_memory_layers.push(frozen_layer.info());
    1562            0 :         }
    1563              : 
    1564            0 :         let mut historic_layers = Vec::new();
    1565            0 :         for historic_layer in layer_map.iter_historic_layers() {
    1566            0 :             let historic_layer = guard.get_from_desc(&historic_layer);
    1567            0 :             historic_layers.push(historic_layer.info(reset));
    1568            0 :         }
    1569              : 
    1570            0 :         LayerMapInfo {
    1571            0 :             in_memory_layers,
    1572            0 :             historic_layers,
    1573            0 :         }
    1574            0 :     }
    1575              : 
    1576            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))]
    1577              :     pub(crate) async fn download_layer(
    1578              :         &self,
    1579              :         layer_file_name: &str,
    1580              :     ) -> anyhow::Result<Option<bool>> {
    1581              :         let Some(layer) = self.find_layer(layer_file_name).await else {
    1582              :             return Ok(None);
    1583              :         };
    1584              : 
    1585              :         if self.remote_client.is_none() {
    1586              :             return Ok(Some(false));
    1587              :         }
    1588              : 
    1589              :         layer.download().await?;
    1590              : 
    1591              :         Ok(Some(true))
    1592              :     }
    1593              : 
    1594              :     /// Evict just one layer.
    1595              :     ///
    1596              :     /// Returns `Ok(None)` in the case where the layer could not be found by its `layer_file_name`.
    1597            0 :     pub(crate) async fn evict_layer(&self, layer_file_name: &str) -> anyhow::Result<Option<bool>> {
    1598            0 :         let _gate = self
    1599            0 :             .gate
    1600            0 :             .enter()
    1601            0 :             .map_err(|_| anyhow::anyhow!("Shutting down"))?;
    1602              : 
    1603            0 :         let Some(local_layer) = self.find_layer(layer_file_name).await else {
    1604            0 :             return Ok(None);
    1605              :         };
    1606              : 
    1607              :         // curl has this by default
    1608            0 :         let timeout = std::time::Duration::from_secs(120);
    1609            0 : 
    1610            0 :         match local_layer.evict_and_wait(timeout).await {
    1611            0 :             Ok(()) => Ok(Some(true)),
    1612            0 :             Err(EvictionError::NotFound) => Ok(Some(false)),
    1613            0 :             Err(EvictionError::Downloaded) => Ok(Some(false)),
    1614            0 :             Err(EvictionError::Timeout) => Ok(Some(false)),
    1615              :         }
    1616            0 :     }
    1617              : 
    1618           56 :     fn should_roll(
    1619           56 :         &self,
    1620           56 :         layer_size: u64,
    1621           56 :         projected_layer_size: u64,
    1622           56 :         checkpoint_distance: u64,
    1623           56 :         projected_lsn: Lsn,
    1624           56 :         last_freeze_at: Lsn,
    1625           56 :         opened_at: Instant,
    1626           56 :     ) -> bool {
    1627           56 :         let distance = projected_lsn.widening_sub(last_freeze_at);
    1628           56 : 
    1629           56 :         // Rolling the open layer can be triggered by:
    1630           56 :         // 1. The distance from the last LSN we rolled at. This bounds the amount of WAL that
    1631           56 :         //    the safekeepers need to store.  For sharded tenants, we multiply by shard count to
    1632           56 :         //    account for how writes are distributed across shards: we expect each node to consume
    1633           56 :         //    1/count of the LSN on average.
    1634           56 :         // 2. The size of the currently open layer.
    1635           56 :         // 3. The time since the last roll. It helps safekeepers to regard pageserver as caught
    1636           56 :         //    up and suspend activity.
    1637           56 :         if distance >= checkpoint_distance as i128 * self.shard_identity.count.count() as i128 {
    1638            0 :             info!(
    1639            0 :                 "Will roll layer at {} with layer size {} due to LSN distance ({})",
    1640            0 :                 projected_lsn, layer_size, distance
    1641            0 :             );
    1642              : 
    1643            0 :             true
    1644           56 :         } else if projected_layer_size >= checkpoint_distance {
    1645            0 :             info!(
    1646            0 :                 "Will roll layer at {} with layer size {} due to layer size ({})",
    1647            0 :                 projected_lsn, layer_size, projected_layer_size
    1648            0 :             );
    1649              : 
    1650            0 :             true
    1651           56 :         } else if distance > 0 && opened_at.elapsed() >= self.get_checkpoint_timeout() {
    1652            0 :             info!(
    1653            0 :                     "Will roll layer at {} with layer size {} due to time since first write to the layer ({:?})",
    1654            0 :                     projected_lsn,
    1655            0 :                     layer_size,
    1656            0 :                     opened_at.elapsed()
    1657            0 :                 );
    1658              : 
    1659            0 :             true
    1660              :         } else {
    1661           56 :             false
    1662              :         }
    1663           56 :     }
    1664              : }
    1665              : 
    1666              : /// Number of times we will compute partition within a checkpoint distance.
    1667              : const REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE: u64 = 10;
    1668              : 
    1669              : // Private functions
    1670              : impl Timeline {
    1671            0 :     pub(crate) fn get_lazy_slru_download(&self) -> bool {
    1672            0 :         let tenant_conf = self.tenant_conf.load();
    1673            0 :         tenant_conf
    1674            0 :             .tenant_conf
    1675            0 :             .lazy_slru_download
    1676            0 :             .unwrap_or(self.conf.default_tenant_conf.lazy_slru_download)
    1677            0 :     }
    1678              : 
    1679         1408 :     fn get_checkpoint_distance(&self) -> u64 {
    1680         1408 :         let tenant_conf = self.tenant_conf.load();
    1681         1408 :         tenant_conf
    1682         1408 :             .tenant_conf
    1683         1408 :             .checkpoint_distance
    1684         1408 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    1685         1408 :     }
    1686              : 
    1687           56 :     fn get_checkpoint_timeout(&self) -> Duration {
    1688           56 :         let tenant_conf = self.tenant_conf.load();
    1689           56 :         tenant_conf
    1690           56 :             .tenant_conf
    1691           56 :             .checkpoint_timeout
    1692           56 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    1693           56 :     }
    1694              : 
    1695          604 :     fn get_compaction_target_size(&self) -> u64 {
    1696          604 :         let tenant_conf = self.tenant_conf.load();
    1697          604 :         tenant_conf
    1698          604 :             .tenant_conf
    1699          604 :             .compaction_target_size
    1700          604 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    1701          604 :     }
    1702              : 
    1703          510 :     fn get_compaction_threshold(&self) -> usize {
    1704          510 :         let tenant_conf = self.tenant_conf.load();
    1705          510 :         tenant_conf
    1706          510 :             .tenant_conf
    1707          510 :             .compaction_threshold
    1708          510 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    1709          510 :     }
    1710              : 
    1711            2 :     fn get_image_creation_threshold(&self) -> usize {
    1712            2 :         let tenant_conf = self.tenant_conf.load();
    1713            2 :         tenant_conf
    1714            2 :             .tenant_conf
    1715            2 :             .image_creation_threshold
    1716            2 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    1717            2 :     }
    1718              : 
    1719          510 :     fn get_compaction_algorithm(&self) -> CompactionAlgorithm {
    1720          510 :         let tenant_conf = &self.tenant_conf.load();
    1721          510 :         tenant_conf
    1722          510 :             .tenant_conf
    1723          510 :             .compaction_algorithm
    1724          510 :             .unwrap_or(self.conf.default_tenant_conf.compaction_algorithm)
    1725          510 :     }
    1726              : 
    1727            0 :     fn get_eviction_policy(&self) -> EvictionPolicy {
    1728            0 :         let tenant_conf = self.tenant_conf.load();
    1729            0 :         tenant_conf
    1730            0 :             .tenant_conf
    1731            0 :             .eviction_policy
    1732            0 :             .unwrap_or(self.conf.default_tenant_conf.eviction_policy)
    1733            0 :     }
    1734              : 
    1735          320 :     fn get_evictions_low_residence_duration_metric_threshold(
    1736          320 :         tenant_conf: &TenantConfOpt,
    1737          320 :         default_tenant_conf: &TenantConf,
    1738          320 :     ) -> Duration {
    1739          320 :         tenant_conf
    1740          320 :             .evictions_low_residence_duration_metric_threshold
    1741          320 :             .unwrap_or(default_tenant_conf.evictions_low_residence_duration_metric_threshold)
    1742          320 :     }
    1743              : 
    1744          522 :     fn get_image_layer_creation_check_threshold(&self) -> u8 {
    1745          522 :         let tenant_conf = self.tenant_conf.load();
    1746          522 :         tenant_conf
    1747          522 :             .tenant_conf
    1748          522 :             .image_layer_creation_check_threshold
    1749          522 :             .unwrap_or(
    1750          522 :                 self.conf
    1751          522 :                     .default_tenant_conf
    1752          522 :                     .image_layer_creation_check_threshold,
    1753          522 :             )
    1754          522 :     }
    1755              : 
    1756            0 :     pub(super) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
    1757            0 :         // NB: Most tenant conf options are read by background loops, so,
    1758            0 :         // changes will automatically be picked up.
    1759            0 : 
    1760            0 :         // The threshold is embedded in the metric. So, we need to update it.
    1761            0 :         {
    1762            0 :             let new_threshold = Self::get_evictions_low_residence_duration_metric_threshold(
    1763            0 :                 new_conf,
    1764            0 :                 &self.conf.default_tenant_conf,
    1765            0 :             );
    1766            0 : 
    1767            0 :             let tenant_id_str = self.tenant_shard_id.tenant_id.to_string();
    1768            0 :             let shard_id_str = format!("{}", self.tenant_shard_id.shard_slug());
    1769            0 : 
    1770            0 :             let timeline_id_str = self.timeline_id.to_string();
    1771            0 :             self.metrics
    1772            0 :                 .evictions_with_low_residence_duration
    1773            0 :                 .write()
    1774            0 :                 .unwrap()
    1775            0 :                 .change_threshold(
    1776            0 :                     &tenant_id_str,
    1777            0 :                     &shard_id_str,
    1778            0 :                     &timeline_id_str,
    1779            0 :                     new_threshold,
    1780            0 :                 );
    1781            0 :         }
    1782            0 :     }
    1783              : 
    1784              :     /// Open a Timeline handle.
    1785              :     ///
    1786              :     /// Loads the metadata for the timeline into memory, but not the layer map.
    1787              :     #[allow(clippy::too_many_arguments)]
    1788          320 :     pub(super) fn new(
    1789          320 :         conf: &'static PageServerConf,
    1790          320 :         tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
    1791          320 :         metadata: &TimelineMetadata,
    1792          320 :         ancestor: Option<Arc<Timeline>>,
    1793          320 :         timeline_id: TimelineId,
    1794          320 :         tenant_shard_id: TenantShardId,
    1795          320 :         generation: Generation,
    1796          320 :         shard_identity: ShardIdentity,
    1797          320 :         walredo_mgr: Option<Arc<super::WalRedoManager>>,
    1798          320 :         resources: TimelineResources,
    1799          320 :         pg_version: u32,
    1800          320 :         state: TimelineState,
    1801          320 :         cancel: CancellationToken,
    1802          320 :     ) -> Arc<Self> {
    1803          320 :         let disk_consistent_lsn = metadata.disk_consistent_lsn();
    1804          320 :         let (state, _) = watch::channel(state);
    1805          320 : 
    1806          320 :         let (layer_flush_start_tx, _) = tokio::sync::watch::channel((0, disk_consistent_lsn));
    1807          320 :         let (layer_flush_done_tx, _) = tokio::sync::watch::channel((0, Ok(())));
    1808          320 : 
    1809          320 :         let evictions_low_residence_duration_metric_threshold = {
    1810          320 :             let loaded_tenant_conf = tenant_conf.load();
    1811          320 :             Self::get_evictions_low_residence_duration_metric_threshold(
    1812          320 :                 &loaded_tenant_conf.tenant_conf,
    1813          320 :                 &conf.default_tenant_conf,
    1814          320 :             )
    1815          320 :         };
    1816          320 : 
    1817          320 :         Arc::new_cyclic(|myself| {
    1818          320 :             let mut result = Timeline {
    1819          320 :                 conf,
    1820          320 :                 tenant_conf,
    1821          320 :                 myself: myself.clone(),
    1822          320 :                 timeline_id,
    1823          320 :                 tenant_shard_id,
    1824          320 :                 generation,
    1825          320 :                 shard_identity,
    1826          320 :                 pg_version,
    1827          320 :                 layers: Default::default(),
    1828          320 : 
    1829          320 :                 walredo_mgr,
    1830          320 :                 walreceiver: Mutex::new(None),
    1831          320 : 
    1832          320 :                 remote_client: resources.remote_client.map(Arc::new),
    1833          320 : 
    1834          320 :                 // initialize in-memory 'last_record_lsn' from 'disk_consistent_lsn'.
    1835          320 :                 last_record_lsn: SeqWait::new(RecordLsn {
    1836          320 :                     last: disk_consistent_lsn,
    1837          320 :                     prev: metadata.prev_record_lsn().unwrap_or(Lsn(0)),
    1838          320 :                 }),
    1839          320 :                 disk_consistent_lsn: AtomicLsn::new(disk_consistent_lsn.0),
    1840          320 : 
    1841          320 :                 last_freeze_at: AtomicLsn::new(disk_consistent_lsn.0),
    1842          320 :                 last_freeze_ts: RwLock::new(Instant::now()),
    1843          320 : 
    1844          320 :                 loaded_at: (disk_consistent_lsn, SystemTime::now()),
    1845          320 : 
    1846          320 :                 ancestor_timeline: ancestor,
    1847          320 :                 ancestor_lsn: metadata.ancestor_lsn(),
    1848          320 : 
    1849          320 :                 metrics: TimelineMetrics::new(
    1850          320 :                     &tenant_shard_id,
    1851          320 :                     &timeline_id,
    1852          320 :                     crate::metrics::EvictionsWithLowResidenceDurationBuilder::new(
    1853          320 :                         "mtime",
    1854          320 :                         evictions_low_residence_duration_metric_threshold,
    1855          320 :                     ),
    1856          320 :                 ),
    1857          320 : 
    1858          320 :                 query_metrics: crate::metrics::SmgrQueryTimePerTimeline::new(
    1859          320 :                     &tenant_shard_id,
    1860          320 :                     &timeline_id,
    1861          320 :                 ),
    1862          320 : 
    1863         2240 :                 directory_metrics: array::from_fn(|_| AtomicU64::new(0)),
    1864          320 : 
    1865          320 :                 flush_loop_state: Mutex::new(FlushLoopState::NotStarted),
    1866          320 : 
    1867          320 :                 layer_flush_start_tx,
    1868          320 :                 layer_flush_done_tx,
    1869          320 : 
    1870          320 :                 write_lock: tokio::sync::Mutex::new(None),
    1871          320 : 
    1872          320 :                 gc_info: std::sync::RwLock::new(GcInfo {
    1873          320 :                     retain_lsns: Vec::new(),
    1874          320 :                     horizon_cutoff: Lsn(0),
    1875          320 :                     pitr_cutoff: Lsn(0),
    1876          320 :                 }),
    1877          320 : 
    1878          320 :                 latest_gc_cutoff_lsn: Rcu::new(metadata.latest_gc_cutoff_lsn()),
    1879          320 :                 initdb_lsn: metadata.initdb_lsn(),
    1880          320 : 
    1881          320 :                 current_logical_size: if disk_consistent_lsn.is_valid() {
    1882              :                     // we're creating timeline data with some layer files existing locally,
    1883              :                     // need to recalculate timeline's logical size based on data in the layers.
    1884          220 :                     LogicalSize::deferred_initial(disk_consistent_lsn)
    1885              :                 } else {
    1886              :                     // we're creating timeline data without any layers existing locally,
    1887              :                     // initial logical size is 0.
    1888          100 :                     LogicalSize::empty_initial()
    1889              :                 },
    1890          320 :                 partitioning: tokio::sync::Mutex::new((KeyPartitioning::new(), Lsn(0))),
    1891          320 :                 repartition_threshold: 0,
    1892          320 :                 last_image_layer_creation_check_at: AtomicLsn::new(0),
    1893          320 : 
    1894          320 :                 last_received_wal: Mutex::new(None),
    1895          320 :                 rel_size_cache: RwLock::new(HashMap::new()),
    1896          320 : 
    1897          320 :                 download_all_remote_layers_task_info: RwLock::new(None),
    1898          320 : 
    1899          320 :                 state,
    1900          320 : 
    1901          320 :                 eviction_task_timeline_state: tokio::sync::Mutex::new(
    1902          320 :                     EvictionTaskTimelineState::default(),
    1903          320 :                 ),
    1904          320 :                 delete_progress: Arc::new(tokio::sync::Mutex::new(DeleteTimelineFlow::default())),
    1905          320 : 
    1906          320 :                 cancel,
    1907          320 :                 gate: Gate::default(),
    1908          320 : 
    1909          320 :                 compaction_lock: tokio::sync::Mutex::default(),
    1910          320 :                 gc_lock: tokio::sync::Mutex::default(),
    1911          320 : 
    1912          320 :                 timeline_get_throttle: resources.timeline_get_throttle,
    1913          320 : 
    1914          320 :                 aux_files: tokio::sync::Mutex::new(AuxFilesState {
    1915          320 :                     dir: None,
    1916          320 :                     n_deltas: 0,
    1917          320 :                 }),
    1918          320 :             };
    1919          320 :             result.repartition_threshold =
    1920          320 :                 result.get_checkpoint_distance() / REPARTITION_FREQ_IN_CHECKPOINT_DISTANCE;
    1921          320 : 
    1922          320 :             result
    1923          320 :                 .metrics
    1924          320 :                 .last_record_gauge
    1925          320 :                 .set(disk_consistent_lsn.0 as i64);
    1926          320 :             result
    1927          320 :         })
    1928          320 :     }
    1929              : 
    1930          410 :     pub(super) fn maybe_spawn_flush_loop(self: &Arc<Self>) {
    1931          410 :         let Ok(guard) = self.gate.enter() else {
    1932            0 :             info!("cannot start flush loop when the timeline gate has already been closed");
    1933            0 :             return;
    1934              :         };
    1935          410 :         let mut flush_loop_state = self.flush_loop_state.lock().unwrap();
    1936          410 :         match *flush_loop_state {
    1937          316 :             FlushLoopState::NotStarted => (),
    1938              :             FlushLoopState::Running { .. } => {
    1939           94 :                 info!(
    1940           94 :                     "skipping attempt to start flush_loop twice {}/{}",
    1941           94 :                     self.tenant_shard_id, self.timeline_id
    1942           94 :                 );
    1943           94 :                 return;
    1944              :             }
    1945              :             FlushLoopState::Exited => {
    1946            0 :                 warn!(
    1947            0 :                     "ignoring attempt to restart exited flush_loop {}/{}",
    1948            0 :                     self.tenant_shard_id, self.timeline_id
    1949            0 :                 );
    1950            0 :                 return;
    1951              :             }
    1952              :         }
    1953              : 
    1954          316 :         let layer_flush_start_rx = self.layer_flush_start_tx.subscribe();
    1955          316 :         let self_clone = Arc::clone(self);
    1956          316 : 
    1957          316 :         debug!("spawning flush loop");
    1958          316 :         *flush_loop_state = FlushLoopState::Running {
    1959          316 :             #[cfg(test)]
    1960          316 :             expect_initdb_optimization: false,
    1961          316 :             #[cfg(test)]
    1962          316 :             initdb_optimization_count: 0,
    1963          316 :         };
    1964          316 :         task_mgr::spawn(
    1965          316 :             task_mgr::BACKGROUND_RUNTIME.handle(),
    1966          316 :             task_mgr::TaskKind::LayerFlushTask,
    1967          316 :             Some(self.tenant_shard_id),
    1968          316 :             Some(self.timeline_id),
    1969          316 :             "layer flush task",
    1970              :             false,
    1971          316 :             async move {
    1972          316 :                 let _guard = guard;
    1973          316 :                 let background_ctx = RequestContext::todo_child(TaskKind::LayerFlushTask, DownloadBehavior::Error);
    1974        61914 :                 self_clone.flush_loop(layer_flush_start_rx, &background_ctx).await;
    1975            8 :                 let mut flush_loop_state = self_clone.flush_loop_state.lock().unwrap();
    1976            8 :                 assert!(matches!(*flush_loop_state, FlushLoopState::Running{ ..}));
    1977            8 :                 *flush_loop_state  = FlushLoopState::Exited;
    1978            8 :                 Ok(())
    1979            8 :             }
    1980          316 :             .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))
    1981              :         );
    1982          410 :     }
    1983              : 
    1984              :     /// Creates and starts the wal receiver.
    1985              :     ///
    1986              :     /// This function is expected to be called at most once per Timeline's lifecycle
    1987              :     /// when the timeline is activated.
    1988            0 :     fn launch_wal_receiver(
    1989            0 :         self: &Arc<Self>,
    1990            0 :         ctx: &RequestContext,
    1991            0 :         broker_client: BrokerClientChannel,
    1992            0 :     ) {
    1993            0 :         info!(
    1994            0 :             "launching WAL receiver for timeline {} of tenant {}",
    1995            0 :             self.timeline_id, self.tenant_shard_id
    1996            0 :         );
    1997              : 
    1998            0 :         let tenant_conf = self.tenant_conf.load();
    1999            0 :         let wal_connect_timeout = tenant_conf
    2000            0 :             .tenant_conf
    2001            0 :             .walreceiver_connect_timeout
    2002            0 :             .unwrap_or(self.conf.default_tenant_conf.walreceiver_connect_timeout);
    2003            0 :         let lagging_wal_timeout = tenant_conf
    2004            0 :             .tenant_conf
    2005            0 :             .lagging_wal_timeout
    2006            0 :             .unwrap_or(self.conf.default_tenant_conf.lagging_wal_timeout);
    2007            0 :         let max_lsn_wal_lag = tenant_conf
    2008            0 :             .tenant_conf
    2009            0 :             .max_lsn_wal_lag
    2010            0 :             .unwrap_or(self.conf.default_tenant_conf.max_lsn_wal_lag);
    2011            0 : 
    2012            0 :         let mut guard = self.walreceiver.lock().unwrap();
    2013            0 :         assert!(
    2014            0 :             guard.is_none(),
    2015            0 :             "multiple launches / re-launches of WAL receiver are not supported"
    2016              :         );
    2017            0 :         *guard = Some(WalReceiver::start(
    2018            0 :             Arc::clone(self),
    2019            0 :             WalReceiverConf {
    2020            0 :                 wal_connect_timeout,
    2021            0 :                 lagging_wal_timeout,
    2022            0 :                 max_lsn_wal_lag,
    2023            0 :                 auth_token: crate::config::SAFEKEEPER_AUTH_TOKEN.get().cloned(),
    2024            0 :                 availability_zone: self.conf.availability_zone.clone(),
    2025            0 :                 ingest_batch_size: self.conf.ingest_batch_size,
    2026            0 :             },
    2027            0 :             broker_client,
    2028            0 :             ctx,
    2029            0 :         ));
    2030            0 :     }
    2031              : 
    2032              :     /// Initialize with an empty layer map. Used when creating a new timeline.
    2033          314 :     pub(super) fn init_empty_layer_map(&self, start_lsn: Lsn) {
    2034          314 :         let mut layers = self.layers.try_write().expect(
    2035          314 :             "in the context where we call this function, no other task has access to the object",
    2036          314 :         );
    2037          314 :         layers.initialize_empty(Lsn(start_lsn.0));
    2038          314 :     }
    2039              : 
    2040              :     /// Scan the timeline directory, cleanup, populate the layer map, and schedule uploads for local-only
    2041              :     /// files.
    2042            6 :     pub(super) async fn load_layer_map(
    2043            6 :         &self,
    2044            6 :         disk_consistent_lsn: Lsn,
    2045            6 :         index_part: Option<IndexPart>,
    2046            6 :     ) -> anyhow::Result<()> {
    2047              :         use init::{Decision::*, Discovered, DismissedLayer};
    2048              :         use LayerFileName::*;
    2049              : 
    2050            6 :         let mut guard = self.layers.write().await;
    2051              : 
    2052            6 :         let timer = self.metrics.load_layer_map_histo.start_timer();
    2053            6 : 
    2054            6 :         // Scan timeline directory and create ImageFileName and DeltaFilename
    2055            6 :         // structs representing all files on disk
    2056            6 :         let timeline_path = self
    2057            6 :             .conf
    2058            6 :             .timeline_path(&self.tenant_shard_id, &self.timeline_id);
    2059            6 :         let conf = self.conf;
    2060            6 :         let span = tracing::Span::current();
    2061            6 : 
    2062            6 :         // Copy to move into the task we're about to spawn
    2063            6 :         let generation = self.generation;
    2064            6 :         let shard = self.get_shard_index();
    2065            6 :         let this = self.myself.upgrade().expect("&self method holds the arc");
    2066              : 
    2067            6 :         let (loaded_layers, needs_cleanup, total_physical_size) = tokio::task::spawn_blocking({
    2068            6 :             move || {
    2069            6 :                 let _g = span.entered();
    2070            6 :                 let discovered = init::scan_timeline_dir(&timeline_path)?;
    2071            6 :                 let mut discovered_layers = Vec::with_capacity(discovered.len());
    2072            6 :                 let mut unrecognized_files = Vec::new();
    2073            6 : 
    2074            6 :                 let mut path = timeline_path;
    2075              : 
    2076           22 :                 for discovered in discovered {
    2077           16 :                     let (name, kind) = match discovered {
    2078           16 :                         Discovered::Layer(file_name, file_size) => {
    2079           16 :                             discovered_layers.push((file_name, file_size));
    2080           16 :                             continue;
    2081              :                         }
    2082              :                         Discovered::Metadata => {
    2083            0 :                             warn!("found legacy metadata file, these should have been removed in load_tenant_config");
    2084            0 :                             continue;
    2085              :                         }
    2086              :                         Discovered::IgnoredBackup => {
    2087            0 :                             continue;
    2088              :                         }
    2089            0 :                         Discovered::Unknown(file_name) => {
    2090            0 :                             // we will later error if there are any
    2091            0 :                             unrecognized_files.push(file_name);
    2092            0 :                             continue;
    2093              :                         }
    2094            0 :                         Discovered::Ephemeral(name) => (name, "old ephemeral file"),
    2095            0 :                         Discovered::Temporary(name) => (name, "temporary timeline file"),
    2096            0 :                         Discovered::TemporaryDownload(name) => (name, "temporary download"),
    2097              :                     };
    2098            0 :                     path.push(Utf8Path::new(&name));
    2099            0 :                     init::cleanup(&path, kind)?;
    2100            0 :                     path.pop();
    2101              :                 }
    2102              : 
    2103            6 :                 if !unrecognized_files.is_empty() {
    2104              :                     // assume that if there are any there are many many.
    2105            0 :                     let n = unrecognized_files.len();
    2106            0 :                     let first = &unrecognized_files[..n.min(10)];
    2107            0 :                     anyhow::bail!(
    2108            0 :                         "unrecognized files in timeline dir (total {n}), first 10: {first:?}"
    2109            0 :                     );
    2110            6 :                 }
    2111            6 : 
    2112            6 :                 let decided = init::reconcile(
    2113            6 :                     discovered_layers,
    2114            6 :                     index_part.as_ref(),
    2115            6 :                     disk_consistent_lsn,
    2116            6 :                     generation,
    2117            6 :                     shard,
    2118            6 :                 );
    2119            6 : 
    2120            6 :                 let mut loaded_layers = Vec::new();
    2121            6 :                 let mut needs_cleanup = Vec::new();
    2122            6 :                 let mut total_physical_size = 0;
    2123              : 
    2124           22 :                 for (name, decision) in decided {
    2125           16 :                     let decision = match decision {
    2126            0 :                         Ok(UseRemote { local, remote }) => {
    2127            0 :                             // Remote is authoritative, but we may still choose to retain
    2128            0 :                             // the local file if the contents appear to match
    2129            0 :                             if local.file_size() == remote.file_size() {
    2130              :                                 // Use the local file, but take the remote metadata so that we pick up
    2131              :                                 // the correct generation.
    2132            0 :                                 UseLocal(remote)
    2133              :                             } else {
    2134            0 :                                 path.push(name.file_name());
    2135            0 :                                 init::cleanup_local_file_for_remote(&path, &local, &remote)?;
    2136            0 :                                 path.pop();
    2137            0 :                                 UseRemote { local, remote }
    2138              :                             }
    2139              :                         }
    2140           16 :                         Ok(decision) => decision,
    2141            0 :                         Err(DismissedLayer::Future { local }) => {
    2142            0 :                             if local.is_some() {
    2143            0 :                                 path.push(name.file_name());
    2144            0 :                                 init::cleanup_future_layer(&path, &name, disk_consistent_lsn)?;
    2145            0 :                                 path.pop();
    2146            0 :                             }
    2147            0 :                             needs_cleanup.push(name);
    2148            0 :                             continue;
    2149              :                         }
    2150            0 :                         Err(DismissedLayer::LocalOnly(local)) => {
    2151            0 :                             path.push(name.file_name());
    2152            0 :                             init::cleanup_local_only_file(&path, &name, &local)?;
    2153            0 :                             path.pop();
    2154            0 :                             // this file never existed remotely, we will have to do rework
    2155            0 :                             continue;
    2156              :                         }
    2157              :                     };
    2158              : 
    2159           16 :                     match &name {
    2160           12 :                         Delta(d) => assert!(d.lsn_range.end <= disk_consistent_lsn + 1),
    2161            4 :                         Image(i) => assert!(i.lsn <= disk_consistent_lsn),
    2162              :                     }
    2163              : 
    2164           16 :                     tracing::debug!(layer=%name, ?decision, "applied");
    2165              : 
    2166           16 :                     let layer = match decision {
    2167           16 :                         UseLocal(m) => {
    2168           16 :                             total_physical_size += m.file_size();
    2169           16 :                             Layer::for_resident(conf, &this, name, m).drop_eviction_guard()
    2170              :                         }
    2171            0 :                         Evicted(remote) | UseRemote { remote, .. } => {
    2172            0 :                             Layer::for_evicted(conf, &this, name, remote)
    2173              :                         }
    2174              :                     };
    2175              : 
    2176           16 :                     loaded_layers.push(layer);
    2177              :                 }
    2178            6 :                 Ok((loaded_layers, needs_cleanup, total_physical_size))
    2179            6 :             }
    2180            6 :         })
    2181            6 :         .await
    2182            6 :         .map_err(anyhow::Error::new)
    2183            6 :         .and_then(|x| x)?;
    2184              : 
    2185            6 :         let num_layers = loaded_layers.len();
    2186            6 : 
    2187            6 :         guard.initialize_local_layers(loaded_layers, disk_consistent_lsn + 1);
    2188              : 
    2189            6 :         if let Some(rtc) = self.remote_client.as_ref() {
    2190            6 :             rtc.schedule_layer_file_deletion(&needs_cleanup)?;
    2191            6 :             rtc.schedule_index_upload_for_file_changes()?;
    2192              :             // This barrier orders above DELETEs before any later operations.
    2193              :             // This is critical because code executing after the barrier might
    2194              :             // create again objects with the same key that we just scheduled for deletion.
    2195              :             // For example, if we just scheduled deletion of an image layer "from the future",
    2196              :             // later compaction might run again and re-create the same image layer.
    2197              :             // "from the future" here means an image layer whose LSN is > IndexPart::disk_consistent_lsn.
    2198              :             // "same" here means same key range and LSN.
    2199              :             //
    2200              :             // Without a barrier between above DELETEs and the re-creation's PUTs,
    2201              :             // the upload queue may execute the PUT first, then the DELETE.
    2202              :             // In our example, we will end up with an IndexPart referencing a non-existent object.
    2203              :             //
    2204              :             // 1. a future image layer is created and uploaded
    2205              :             // 2. ps restart
    2206              :             // 3. the future layer from (1) is deleted during load layer map
    2207              :             // 4. image layer is re-created and uploaded
    2208              :             // 5. deletion queue would like to delete (1) but actually deletes (4)
    2209              :             // 6. delete by name works as expected, but it now deletes the wrong (later) version
    2210              :             //
    2211              :             // See https://github.com/neondatabase/neon/issues/5878
    2212              :             //
    2213              :             // NB: generation numbers naturally protect against this because they disambiguate
    2214              :             //     (1) and (4)
    2215            6 :             rtc.schedule_barrier()?;
    2216              :             // Tenant::create_timeline will wait for these uploads to happen before returning, or
    2217              :             // on retry.
    2218            0 :         }
    2219              : 
    2220            6 :         info!(
    2221            6 :             "loaded layer map with {} layers at {}, total physical size: {}",
    2222            6 :             num_layers, disk_consistent_lsn, total_physical_size
    2223            6 :         );
    2224              : 
    2225            6 :         timer.stop_and_record();
    2226            6 :         Ok(())
    2227            6 :     }
    2228              : 
    2229              :     /// Retrieve current logical size of the timeline.
    2230              :     ///
    2231              :     /// The size could be lagging behind the actual number, in case
    2232              :     /// the initial size calculation has not been run (gets triggered on the first size access).
    2233              :     ///
    2234              :     /// return size and boolean flag that shows if the size is exact
    2235            0 :     pub(crate) fn get_current_logical_size(
    2236            0 :         self: &Arc<Self>,
    2237            0 :         priority: GetLogicalSizePriority,
    2238            0 :         ctx: &RequestContext,
    2239            0 :     ) -> logical_size::CurrentLogicalSize {
    2240            0 :         if !self.tenant_shard_id.is_shard_zero() {
    2241              :             // Logical size is only accurately maintained on shard zero: when called elsewhere, for example
    2242              :             // when HTTP API is serving a GET for timeline zero, return zero
    2243            0 :             return logical_size::CurrentLogicalSize::Approximate(logical_size::Approximate::zero());
    2244            0 :         }
    2245            0 : 
    2246            0 :         let current_size = self.current_logical_size.current_size();
    2247            0 :         debug!("Current size: {current_size:?}");
    2248              : 
    2249            0 :         match (current_size.accuracy(), priority) {
    2250            0 :             (logical_size::Accuracy::Exact, _) => (), // nothing to do
    2251            0 :             (logical_size::Accuracy::Approximate, GetLogicalSizePriority::Background) => {
    2252            0 :                 // background task will eventually deliver an exact value, we're in no rush
    2253            0 :             }
    2254              :             (logical_size::Accuracy::Approximate, GetLogicalSizePriority::User) => {
    2255              :                 // background task is not ready, but user is asking for it now;
    2256              :                 // => make the background task skip the line
    2257              :                 // (The alternative would be to calculate the size here, but,
    2258              :                 //  it can actually take a long time if the user has a lot of rels.
    2259              :                 //  And we'll inevitable need it again; So, let the background task do the work.)
    2260            0 :                 match self
    2261            0 :                     .current_logical_size
    2262            0 :                     .cancel_wait_for_background_loop_concurrency_limit_semaphore
    2263            0 :                     .get()
    2264              :                 {
    2265            0 :                     Some(cancel) => cancel.cancel(),
    2266              :                     None => {
    2267            0 :                         let state = self.current_state();
    2268            0 :                         if matches!(
    2269            0 :                             state,
    2270              :                             TimelineState::Broken { .. } | TimelineState::Stopping
    2271            0 :                         ) {
    2272            0 : 
    2273            0 :                             // Can happen when timeline detail endpoint is used when deletion is ongoing (or its broken).
    2274            0 :                             // Don't make noise.
    2275            0 :                         } else {
    2276            0 :                             warn!("unexpected: cancel_wait_for_background_loop_concurrency_limit_semaphore not set, priority-boosting of logical size calculation will not work");
    2277              :                         }
    2278              :                     }
    2279              :                 };
    2280              :             }
    2281              :         }
    2282              : 
    2283            0 :         if let CurrentLogicalSize::Approximate(_) = &current_size {
    2284            0 :             if ctx.task_kind() == TaskKind::WalReceiverConnectionHandler {
    2285            0 :                 let first = self
    2286            0 :                     .current_logical_size
    2287            0 :                     .did_return_approximate_to_walreceiver
    2288            0 :                     .compare_exchange(
    2289            0 :                         false,
    2290            0 :                         true,
    2291            0 :                         AtomicOrdering::Relaxed,
    2292            0 :                         AtomicOrdering::Relaxed,
    2293            0 :                     )
    2294            0 :                     .is_ok();
    2295            0 :                 if first {
    2296            0 :                     crate::metrics::initial_logical_size::TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE.inc();
    2297            0 :                 }
    2298            0 :             }
    2299            0 :         }
    2300              : 
    2301            0 :         current_size
    2302            0 :     }
    2303              : 
    2304            0 :     fn spawn_initial_logical_size_computation_task(self: &Arc<Self>, ctx: &RequestContext) {
    2305            0 :         let Some(initial_part_end) = self.current_logical_size.initial_part_end else {
    2306              :             // nothing to do for freshly created timelines;
    2307            0 :             assert_eq!(
    2308            0 :                 self.current_logical_size.current_size().accuracy(),
    2309            0 :                 logical_size::Accuracy::Exact,
    2310            0 :             );
    2311            0 :             self.current_logical_size.initialized.add_permits(1);
    2312            0 :             return;
    2313              :         };
    2314              : 
    2315            0 :         let cancel_wait_for_background_loop_concurrency_limit_semaphore = CancellationToken::new();
    2316            0 :         let token = cancel_wait_for_background_loop_concurrency_limit_semaphore.clone();
    2317            0 :         self.current_logical_size
    2318            0 :             .cancel_wait_for_background_loop_concurrency_limit_semaphore.set(token)
    2319            0 :             .expect("initial logical size calculation task must be spawned exactly once per Timeline object");
    2320            0 : 
    2321            0 :         let self_clone = Arc::clone(self);
    2322            0 :         let background_ctx = ctx.detached_child(
    2323            0 :             TaskKind::InitialLogicalSizeCalculation,
    2324            0 :             DownloadBehavior::Download,
    2325            0 :         );
    2326            0 :         task_mgr::spawn(
    2327            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
    2328            0 :             task_mgr::TaskKind::InitialLogicalSizeCalculation,
    2329            0 :             Some(self.tenant_shard_id),
    2330            0 :             Some(self.timeline_id),
    2331            0 :             "initial size calculation",
    2332              :             false,
    2333              :             // NB: don't log errors here, task_mgr will do that.
    2334            0 :             async move {
    2335            0 :                 let cancel = task_mgr::shutdown_token();
    2336            0 :                 self_clone
    2337            0 :                     .initial_logical_size_calculation_task(
    2338            0 :                         initial_part_end,
    2339            0 :                         cancel_wait_for_background_loop_concurrency_limit_semaphore,
    2340            0 :                         cancel,
    2341            0 :                         background_ctx,
    2342            0 :                     )
    2343            0 :                     .await;
    2344            0 :                 Ok(())
    2345            0 :             }
    2346            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)),
    2347              :         );
    2348            0 :     }
    2349              : 
    2350            0 :     async fn initial_logical_size_calculation_task(
    2351            0 :         self: Arc<Self>,
    2352            0 :         initial_part_end: Lsn,
    2353            0 :         skip_concurrency_limiter: CancellationToken,
    2354            0 :         cancel: CancellationToken,
    2355            0 :         background_ctx: RequestContext,
    2356            0 :     ) {
    2357            0 :         scopeguard::defer! {
    2358            0 :             // Irrespective of the outcome of this operation, we should unblock anyone waiting for it.
    2359            0 :             self.current_logical_size.initialized.add_permits(1);
    2360            0 :         }
    2361              : 
    2362              :         enum BackgroundCalculationError {
    2363              :             Cancelled,
    2364              :             Other(anyhow::Error),
    2365              :         }
    2366              : 
    2367            0 :         let try_once = |attempt: usize| {
    2368            0 :             let background_ctx = &background_ctx;
    2369            0 :             let self_ref = &self;
    2370            0 :             let skip_concurrency_limiter = &skip_concurrency_limiter;
    2371            0 :             async move {
    2372            0 :                 let cancel = task_mgr::shutdown_token();
    2373            0 :                 let wait_for_permit = super::tasks::concurrent_background_tasks_rate_limit_permit(
    2374            0 :                     BackgroundLoopKind::InitialLogicalSizeCalculation,
    2375            0 :                     background_ctx,
    2376            0 :                 );
    2377              : 
    2378              :                 use crate::metrics::initial_logical_size::StartCircumstances;
    2379            0 :                 let (_maybe_permit, circumstances) = tokio::select! {
    2380            0 :                     permit = wait_for_permit => {
    2381              :                         (Some(permit), StartCircumstances::AfterBackgroundTasksRateLimit)
    2382              :                     }
    2383              :                     _ = self_ref.cancel.cancelled() => {
    2384              :                         return Err(BackgroundCalculationError::Cancelled);
    2385              :                     }
    2386              :                     _ = cancel.cancelled() => {
    2387              :                         return Err(BackgroundCalculationError::Cancelled);
    2388              :                     },
    2389              :                     () = skip_concurrency_limiter.cancelled() => {
    2390              :                         // Some action that is part of a end user interaction requested logical size
    2391              :                         // => break out of the rate limit
    2392              :                         // TODO: ideally we'd not run on BackgroundRuntime but the requester's runtime;
    2393              :                         // but then again what happens if they cancel; also, we should just be using
    2394              :                         // one runtime across the entire process, so, let's leave this for now.
    2395              :                         (None, StartCircumstances::SkippedConcurrencyLimiter)
    2396              :                     }
    2397              :                 };
    2398              : 
    2399            0 :                 let metrics_guard = if attempt == 1 {
    2400            0 :                     crate::metrics::initial_logical_size::START_CALCULATION.first(circumstances)
    2401              :                 } else {
    2402            0 :                     crate::metrics::initial_logical_size::START_CALCULATION.retry(circumstances)
    2403              :                 };
    2404              : 
    2405            0 :                 match self_ref
    2406            0 :                     .logical_size_calculation_task(
    2407            0 :                         initial_part_end,
    2408            0 :                         LogicalSizeCalculationCause::Initial,
    2409            0 :                         background_ctx,
    2410            0 :                     )
    2411            0 :                     .await
    2412              :                 {
    2413            0 :                     Ok(calculated_size) => Ok((calculated_size, metrics_guard)),
    2414              :                     Err(CalculateLogicalSizeError::Cancelled) => {
    2415            0 :                         Err(BackgroundCalculationError::Cancelled)
    2416              :                     }
    2417            0 :                     Err(CalculateLogicalSizeError::Other(err)) => {
    2418            0 :                         if let Some(PageReconstructError::AncestorStopping(_)) =
    2419            0 :                             err.root_cause().downcast_ref()
    2420              :                         {
    2421            0 :                             Err(BackgroundCalculationError::Cancelled)
    2422              :                         } else {
    2423            0 :                             Err(BackgroundCalculationError::Other(err))
    2424              :                         }
    2425              :                     }
    2426              :                 }
    2427            0 :             }
    2428            0 :         };
    2429              : 
    2430            0 :         let retrying = async {
    2431            0 :             let mut attempt = 0;
    2432            0 :             loop {
    2433            0 :                 attempt += 1;
    2434            0 : 
    2435            0 :                 match try_once(attempt).await {
    2436            0 :                     Ok(res) => return ControlFlow::Continue(res),
    2437            0 :                     Err(BackgroundCalculationError::Cancelled) => return ControlFlow::Break(()),
    2438            0 :                     Err(BackgroundCalculationError::Other(e)) => {
    2439            0 :                         warn!(attempt, "initial size calculation failed: {e:?}");
    2440              :                         // exponential back-off doesn't make sense at these long intervals;
    2441              :                         // use fixed retry interval with generous jitter instead
    2442            0 :                         let sleep_duration = Duration::from_secs(
    2443            0 :                             u64::try_from(
    2444            0 :                                 // 1hour base
    2445            0 :                                 (60_i64 * 60_i64)
    2446            0 :                                     // 10min jitter
    2447            0 :                                     + rand::thread_rng().gen_range(-10 * 60..10 * 60),
    2448            0 :                             )
    2449            0 :                             .expect("10min < 1hour"),
    2450            0 :                         );
    2451            0 :                         tokio::time::sleep(sleep_duration).await;
    2452              :                     }
    2453              :                 }
    2454              :             }
    2455            0 :         };
    2456              : 
    2457            0 :         let (calculated_size, metrics_guard) = tokio::select! {
    2458            0 :             res = retrying  => {
    2459              :                 match res {
    2460              :                     ControlFlow::Continue(calculated_size) => calculated_size,
    2461              :                     ControlFlow::Break(()) => return,
    2462              :                 }
    2463              :             }
    2464              :             _ = cancel.cancelled() => {
    2465              :                 return;
    2466              :             }
    2467              :         };
    2468              : 
    2469              :         // we cannot query current_logical_size.current_size() to know the current
    2470              :         // *negative* value, only truncated to u64.
    2471            0 :         let added = self
    2472            0 :             .current_logical_size
    2473            0 :             .size_added_after_initial
    2474            0 :             .load(AtomicOrdering::Relaxed);
    2475            0 : 
    2476            0 :         let sum = calculated_size.saturating_add_signed(added);
    2477            0 : 
    2478            0 :         // set the gauge value before it can be set in `update_current_logical_size`.
    2479            0 :         self.metrics.current_logical_size_gauge.set(sum);
    2480            0 : 
    2481            0 :         self.current_logical_size
    2482            0 :             .initial_logical_size
    2483            0 :             .set((calculated_size, metrics_guard.calculation_result_saved()))
    2484            0 :             .ok()
    2485            0 :             .expect("only this task sets it");
    2486            0 :     }
    2487              : 
    2488            0 :     pub(crate) fn spawn_ondemand_logical_size_calculation(
    2489            0 :         self: &Arc<Self>,
    2490            0 :         lsn: Lsn,
    2491            0 :         cause: LogicalSizeCalculationCause,
    2492            0 :         ctx: RequestContext,
    2493            0 :     ) -> oneshot::Receiver<Result<u64, CalculateLogicalSizeError>> {
    2494            0 :         let (sender, receiver) = oneshot::channel();
    2495            0 :         let self_clone = Arc::clone(self);
    2496            0 :         // XXX if our caller loses interest, i.e., ctx is cancelled,
    2497            0 :         // we should stop the size calculation work and return an error.
    2498            0 :         // That would require restructuring this function's API to
    2499            0 :         // return the result directly, instead of a Receiver for the result.
    2500            0 :         let ctx = ctx.detached_child(
    2501            0 :             TaskKind::OndemandLogicalSizeCalculation,
    2502            0 :             DownloadBehavior::Download,
    2503            0 :         );
    2504            0 :         task_mgr::spawn(
    2505            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
    2506            0 :             task_mgr::TaskKind::OndemandLogicalSizeCalculation,
    2507            0 :             Some(self.tenant_shard_id),
    2508            0 :             Some(self.timeline_id),
    2509            0 :             "ondemand logical size calculation",
    2510            0 :             false,
    2511            0 :             async move {
    2512            0 :                 let res = self_clone
    2513            0 :                     .logical_size_calculation_task(lsn, cause, &ctx)
    2514            0 :                     .await;
    2515            0 :                 let _ = sender.send(res).ok();
    2516            0 :                 Ok(()) // Receiver is responsible for handling errors
    2517            0 :             }
    2518            0 :             .in_current_span(),
    2519            0 :         );
    2520            0 :         receiver
    2521            0 :     }
    2522              : 
    2523              :     /// # Cancel-Safety
    2524              :     ///
    2525              :     /// This method is cancellation-safe.
    2526            0 :     #[instrument(skip_all)]
    2527              :     async fn logical_size_calculation_task(
    2528              :         self: &Arc<Self>,
    2529              :         lsn: Lsn,
    2530              :         cause: LogicalSizeCalculationCause,
    2531              :         ctx: &RequestContext,
    2532              :     ) -> Result<u64, CalculateLogicalSizeError> {
    2533              :         crate::span::debug_assert_current_span_has_tenant_and_timeline_id();
    2534              :         // We should never be calculating logical sizes on shard !=0, because these shards do not have
    2535              :         // accurate relation sizes, and they do not emit consumption metrics.
    2536              :         debug_assert!(self.tenant_shard_id.is_shard_zero());
    2537              : 
    2538              :         let guard = self
    2539              :             .gate
    2540              :             .enter()
    2541            0 :             .map_err(|_| CalculateLogicalSizeError::Cancelled)?;
    2542              : 
    2543              :         let self_calculation = Arc::clone(self);
    2544              : 
    2545            0 :         let mut calculation = pin!(async {
    2546            0 :             let ctx = ctx.attached_child();
    2547            0 :             self_calculation
    2548            0 :                 .calculate_logical_size(lsn, cause, &guard, &ctx)
    2549            0 :                 .await
    2550            0 :         });
    2551              : 
    2552            0 :         tokio::select! {
    2553            0 :             res = &mut calculation => { res }
    2554              :             _ = self.cancel.cancelled() => {
    2555            0 :                 debug!("cancelling logical size calculation for timeline shutdown");
    2556              :                 calculation.await
    2557              :             }
    2558              :         }
    2559              :     }
    2560              : 
    2561              :     /// Calculate the logical size of the database at the latest LSN.
    2562              :     ///
    2563              :     /// NOTE: counted incrementally, includes ancestors. This can be a slow operation,
    2564              :     /// especially if we need to download remote layers.
    2565              :     ///
    2566              :     /// # Cancel-Safety
    2567              :     ///
    2568              :     /// This method is cancellation-safe.
    2569            0 :     async fn calculate_logical_size(
    2570            0 :         &self,
    2571            0 :         up_to_lsn: Lsn,
    2572            0 :         cause: LogicalSizeCalculationCause,
    2573            0 :         _guard: &GateGuard,
    2574            0 :         ctx: &RequestContext,
    2575            0 :     ) -> Result<u64, CalculateLogicalSizeError> {
    2576            0 :         info!(
    2577            0 :             "Calculating logical size for timeline {} at {}",
    2578            0 :             self.timeline_id, up_to_lsn
    2579            0 :         );
    2580              : 
    2581            0 :         pausable_failpoint!("timeline-calculate-logical-size-pause");
    2582              : 
    2583              :         // See if we've already done the work for initial size calculation.
    2584              :         // This is a short-cut for timelines that are mostly unused.
    2585            0 :         if let Some(size) = self.current_logical_size.initialized_size(up_to_lsn) {
    2586            0 :             return Ok(size);
    2587            0 :         }
    2588            0 :         let storage_time_metrics = match cause {
    2589              :             LogicalSizeCalculationCause::Initial
    2590              :             | LogicalSizeCalculationCause::ConsumptionMetricsSyntheticSize
    2591            0 :             | LogicalSizeCalculationCause::TenantSizeHandler => &self.metrics.logical_size_histo,
    2592              :             LogicalSizeCalculationCause::EvictionTaskImitation => {
    2593            0 :                 &self.metrics.imitate_logical_size_histo
    2594              :             }
    2595              :         };
    2596            0 :         let timer = storage_time_metrics.start_timer();
    2597            0 :         let logical_size = self
    2598            0 :             .get_current_logical_size_non_incremental(up_to_lsn, ctx)
    2599            0 :             .await?;
    2600            0 :         debug!("calculated logical size: {logical_size}");
    2601            0 :         timer.stop_and_record();
    2602            0 :         Ok(logical_size)
    2603            0 :     }
    2604              : 
    2605              :     /// Update current logical size, adding `delta' to the old value.
    2606       270570 :     fn update_current_logical_size(&self, delta: i64) {
    2607       270570 :         let logical_size = &self.current_logical_size;
    2608       270570 :         logical_size.increment_size(delta);
    2609       270570 : 
    2610       270570 :         // Also set the value in the prometheus gauge. Note that
    2611       270570 :         // there is a race condition here: if this is is called by two
    2612       270570 :         // threads concurrently, the prometheus gauge might be set to
    2613       270570 :         // one value while current_logical_size is set to the
    2614       270570 :         // other.
    2615       270570 :         match logical_size.current_size() {
    2616       270570 :             CurrentLogicalSize::Exact(ref new_current_size) => self
    2617       270570 :                 .metrics
    2618       270570 :                 .current_logical_size_gauge
    2619       270570 :                 .set(new_current_size.into()),
    2620            0 :             CurrentLogicalSize::Approximate(_) => {
    2621            0 :                 // don't update the gauge yet, this allows us not to update the gauge back and
    2622            0 :                 // forth between the initial size calculation task.
    2623            0 :             }
    2624              :         }
    2625       270570 :     }
    2626              : 
    2627         2544 :     pub(crate) fn update_directory_entries_count(&self, kind: DirectoryKind, count: u64) {
    2628         2544 :         self.directory_metrics[kind.offset()].store(count, AtomicOrdering::Relaxed);
    2629         2544 :         let aux_metric =
    2630         2544 :             self.directory_metrics[DirectoryKind::AuxFiles.offset()].load(AtomicOrdering::Relaxed);
    2631         2544 : 
    2632         2544 :         let sum_of_entries = self
    2633         2544 :             .directory_metrics
    2634         2544 :             .iter()
    2635        17808 :             .map(|v| v.load(AtomicOrdering::Relaxed))
    2636         2544 :             .sum();
    2637         2544 :         // Set a high general threshold and a lower threshold for the auxiliary files,
    2638         2544 :         // as we can have large numbers of relations in the db directory.
    2639         2544 :         const SUM_THRESHOLD: u64 = 5000;
    2640         2544 :         const AUX_THRESHOLD: u64 = 1000;
    2641         2544 :         if sum_of_entries >= SUM_THRESHOLD || aux_metric >= AUX_THRESHOLD {
    2642            0 :             self.metrics
    2643            0 :                 .directory_entries_count_gauge
    2644            0 :                 .set(sum_of_entries);
    2645         2544 :         } else if let Some(metric) = Lazy::get(&self.metrics.directory_entries_count_gauge) {
    2646            0 :             metric.set(sum_of_entries);
    2647         2544 :         }
    2648         2544 :     }
    2649              : 
    2650            0 :     async fn find_layer(&self, layer_file_name: &str) -> Option<Layer> {
    2651            0 :         let guard = self.layers.read().await;
    2652            0 :         for historic_layer in guard.layer_map().iter_historic_layers() {
    2653            0 :             let historic_layer_name = historic_layer.filename().file_name();
    2654            0 :             if layer_file_name == historic_layer_name {
    2655            0 :                 return Some(guard.get_from_desc(&historic_layer));
    2656            0 :             }
    2657              :         }
    2658              : 
    2659            0 :         None
    2660            0 :     }
    2661              : 
    2662              :     /// The timeline heatmap is a hint to secondary locations from the primary location,
    2663              :     /// indicating which layers are currently on-disk on the primary.
    2664              :     ///
    2665              :     /// None is returned if the Timeline is in a state where uploading a heatmap
    2666              :     /// doesn't make sense, such as shutting down or initializing.  The caller
    2667              :     /// should treat this as a cue to simply skip doing any heatmap uploading
    2668              :     /// for this timeline.
    2669            0 :     pub(crate) async fn generate_heatmap(&self) -> Option<HeatMapTimeline> {
    2670              :         // no point in heatmaps without remote client
    2671            0 :         let _remote_client = self.remote_client.as_ref()?;
    2672              : 
    2673            0 :         if !self.is_active() {
    2674            0 :             return None;
    2675            0 :         }
    2676              : 
    2677            0 :         let guard = self.layers.read().await;
    2678              : 
    2679            0 :         let resident = guard.likely_resident_layers().map(|layer| {
    2680            0 :             let last_activity_ts = layer.access_stats().latest_activity_or_now();
    2681            0 : 
    2682            0 :             HeatMapLayer::new(
    2683            0 :                 layer.layer_desc().filename(),
    2684            0 :                 layer.metadata().into(),
    2685            0 :                 last_activity_ts,
    2686            0 :             )
    2687            0 :         });
    2688            0 : 
    2689            0 :         let layers = resident.collect();
    2690            0 : 
    2691            0 :         Some(HeatMapTimeline::new(self.timeline_id, layers))
    2692            0 :     }
    2693              : }
    2694              : 
    2695              : type TraversalId = String;
    2696              : 
    2697              : trait TraversalLayerExt {
    2698              :     fn traversal_id(&self) -> TraversalId;
    2699              : }
    2700              : 
    2701              : impl TraversalLayerExt for Layer {
    2702          146 :     fn traversal_id(&self) -> TraversalId {
    2703          146 :         self.local_path().to_string()
    2704          146 :     }
    2705              : }
    2706              : 
    2707              : impl TraversalLayerExt for Arc<InMemoryLayer> {
    2708            4 :     fn traversal_id(&self) -> TraversalId {
    2709            4 :         format!("timeline {} in-memory {self}", self.get_timeline_id())
    2710            4 :     }
    2711              : }
    2712              : 
    2713              : impl Timeline {
    2714              :     ///
    2715              :     /// Get a handle to a Layer for reading.
    2716              :     ///
    2717              :     /// The returned Layer might be from an ancestor timeline, if the
    2718              :     /// segment hasn't been updated on this timeline yet.
    2719              :     ///
    2720              :     /// This function takes the current timeline's locked LayerMap as an argument,
    2721              :     /// so callers can avoid potential race conditions.
    2722              :     ///
    2723              :     /// # Cancel-Safety
    2724              :     ///
    2725              :     /// This method is cancellation-safe.
    2726       502833 :     async fn get_reconstruct_data(
    2727       502833 :         &self,
    2728       502833 :         key: Key,
    2729       502833 :         request_lsn: Lsn,
    2730       502833 :         reconstruct_state: &mut ValueReconstructState,
    2731       502833 :         ctx: &RequestContext,
    2732       502833 :     ) -> Result<Vec<TraversalPathItem>, PageReconstructError> {
    2733       502833 :         // Start from the current timeline.
    2734       502833 :         let mut timeline_owned;
    2735       502833 :         let mut timeline = self;
    2736       502833 : 
    2737       502833 :         let mut read_count = scopeguard::guard(0, |cnt| {
    2738       502833 :             crate::metrics::READ_NUM_FS_LAYERS.observe(cnt as f64)
    2739       502833 :         });
    2740       502833 : 
    2741       502833 :         // For debugging purposes, collect the path of layers that we traversed
    2742       502833 :         // through. It's included in the error message if we fail to find the key.
    2743       502833 :         let mut traversal_path = Vec::<TraversalPathItem>::new();
    2744              : 
    2745       502833 :         let cached_lsn = if let Some((cached_lsn, _)) = &reconstruct_state.img {
    2746            0 :             *cached_lsn
    2747              :         } else {
    2748       502833 :             Lsn(0)
    2749              :         };
    2750              : 
    2751              :         // 'prev_lsn' tracks the last LSN that we were at in our search. It's used
    2752              :         // to check that each iteration make some progress, to break infinite
    2753              :         // looping if something goes wrong.
    2754       502833 :         let mut prev_lsn = None;
    2755       502833 : 
    2756       502833 :         let mut result = ValueReconstructResult::Continue;
    2757       502833 :         let mut cont_lsn = Lsn(request_lsn.0 + 1);
    2758              : 
    2759      1356959 :         'outer: loop {
    2760      1356959 :             if self.cancel.is_cancelled() {
    2761            0 :                 return Err(PageReconstructError::Cancelled);
    2762      1356959 :             }
    2763      1356959 : 
    2764      1356959 :             // The function should have updated 'state'
    2765      1356959 :             //info!("CALLED for {} at {}: {:?} with {} records, cached {}", key, cont_lsn, result, reconstruct_state.records.len(), cached_lsn);
    2766      1356959 :             match result {
    2767       502723 :                 ValueReconstructResult::Complete => return Ok(traversal_path),
    2768              :                 ValueReconstructResult::Continue => {
    2769              :                     // If we reached an earlier cached page image, we're done.
    2770       854230 :                     if cont_lsn == cached_lsn + 1 {
    2771            0 :                         MATERIALIZED_PAGE_CACHE_HIT.inc_by(1);
    2772            0 :                         return Ok(traversal_path);
    2773       854230 :                     }
    2774       854230 :                     if let Some(prev) = prev_lsn {
    2775       124594 :                         if prev <= cont_lsn {
    2776              :                             // Didn't make any progress in last iteration. Error out to avoid
    2777              :                             // getting stuck in the loop.
    2778          102 :                             return Err(layer_traversal_error(format!(
    2779          102 :                                 "could not find layer with more data for key {} at LSN {}, request LSN {}, ancestor {}",
    2780          102 :                                 key,
    2781          102 :                                 Lsn(cont_lsn.0 - 1),
    2782          102 :                                 request_lsn,
    2783          102 :                                 timeline.ancestor_lsn
    2784          102 :                             ), traversal_path));
    2785       124492 :                         }
    2786       729636 :                     }
    2787       854128 :                     prev_lsn = Some(cont_lsn);
    2788              :                 }
    2789              :                 ValueReconstructResult::Missing => {
    2790              :                     return Err(layer_traversal_error(
    2791            6 :                         if cfg!(test) {
    2792            6 :                             format!(
    2793            6 :                                 "could not find data for key {} (shard {:?}) at LSN {}, for request at LSN {}\n{}",
    2794            6 :                                 key, self.shard_identity.get_shard_number(&key), cont_lsn, request_lsn, std::backtrace::Backtrace::force_capture(),
    2795            6 :                             )
    2796              :                         } else {
    2797            0 :                             format!(
    2798            0 :                                 "could not find data for key {} (shard {:?}) at LSN {}, for request at LSN {}",
    2799            0 :                                 key, self.shard_identity.get_shard_number(&key), cont_lsn, request_lsn
    2800            0 :                             )
    2801              :                         },
    2802            6 :                         traversal_path,
    2803              :                     ));
    2804              :                 }
    2805              :             }
    2806              : 
    2807              :             // Recurse into ancestor if needed
    2808       854128 :             if is_inherited_key(key) && Lsn(cont_lsn.0 - 1) <= timeline.ancestor_lsn {
    2809       226805 :                 trace!(
    2810            0 :                     "going into ancestor {}, cont_lsn is {}",
    2811            0 :                     timeline.ancestor_lsn,
    2812            0 :                     cont_lsn
    2813            0 :                 );
    2814              : 
    2815       226805 :                 timeline_owned = timeline.get_ready_ancestor_timeline(ctx).await?;
    2816       226803 :                 timeline = &*timeline_owned;
    2817       226803 :                 prev_lsn = None;
    2818       226803 :                 continue 'outer;
    2819       627323 :             }
    2820              : 
    2821       627323 :             let guard = timeline.layers.read().await;
    2822       627323 :             let layers = guard.layer_map();
    2823              : 
    2824              :             // Check the open and frozen in-memory layers first, in order from newest
    2825              :             // to oldest.
    2826       627323 :             if let Some(open_layer) = &layers.open_layer {
    2827       556003 :                 let start_lsn = open_layer.get_lsn_range().start;
    2828       556003 :                 if cont_lsn > start_lsn {
    2829              :                     //info!("CHECKING for {} at {} on open layer {}", key, cont_lsn, open_layer.filename().display());
    2830              :                     // Get all the data needed to reconstruct the page version from this layer.
    2831              :                     // But if we have an older cached page image, no need to go past that.
    2832       502139 :                     let lsn_floor = max(cached_lsn + 1, start_lsn);
    2833       502139 : 
    2834       502139 :                     let open_layer = open_layer.clone();
    2835       502139 :                     drop(guard);
    2836       502139 : 
    2837       502139 :                     result = match open_layer
    2838       502139 :                         .get_value_reconstruct_data(
    2839       502139 :                             key,
    2840       502139 :                             lsn_floor..cont_lsn,
    2841       502139 :                             reconstruct_state,
    2842       502139 :                             ctx,
    2843       502139 :                         )
    2844         7232 :                         .await
    2845              :                     {
    2846       502139 :                         Ok(result) => result,
    2847            0 :                         Err(e) => return Err(PageReconstructError::from(e)),
    2848              :                     };
    2849       502139 :                     cont_lsn = lsn_floor;
    2850       502139 :                     // metrics: open_layer does not count as fs access, so we are not updating `read_count`
    2851       502139 :                     traversal_path.push((
    2852       502139 :                         result,
    2853       502139 :                         cont_lsn,
    2854       502139 :                         Box::new(move || open_layer.traversal_id()),
    2855       502139 :                     ));
    2856       502139 :                     continue 'outer;
    2857        53864 :                 }
    2858        71320 :             }
    2859       125184 :             for frozen_layer in layers.frozen_layers.iter().rev() {
    2860         1316 :                 let start_lsn = frozen_layer.get_lsn_range().start;
    2861         1316 :                 if cont_lsn > start_lsn {
    2862              :                     //info!("CHECKING for {} at {} on frozen layer {}", key, cont_lsn, frozen_layer.filename().display());
    2863         1316 :                     let lsn_floor = max(cached_lsn + 1, start_lsn);
    2864         1316 : 
    2865         1316 :                     let frozen_layer = frozen_layer.clone();
    2866         1316 :                     drop(guard);
    2867         1316 : 
    2868         1316 :                     result = match frozen_layer
    2869         1316 :                         .get_value_reconstruct_data(
    2870         1316 :                             key,
    2871         1316 :                             lsn_floor..cont_lsn,
    2872         1316 :                             reconstruct_state,
    2873         1316 :                             ctx,
    2874         1316 :                         )
    2875            0 :                         .await
    2876              :                     {
    2877         1316 :                         Ok(result) => result,
    2878            0 :                         Err(e) => return Err(PageReconstructError::from(e)),
    2879              :                     };
    2880         1316 :                     cont_lsn = lsn_floor;
    2881         1316 :                     // metrics: open_layer does not count as fs access, so we are not updating `read_count`
    2882         1316 :                     traversal_path.push((
    2883         1316 :                         result,
    2884         1316 :                         cont_lsn,
    2885         1316 :                         Box::new(move || frozen_layer.traversal_id()),
    2886         1316 :                     ));
    2887         1316 :                     continue 'outer;
    2888            0 :                 }
    2889              :             }
    2890              : 
    2891       123868 :             if let Some(SearchResult { lsn_floor, layer }) = layers.search(key, cont_lsn) {
    2892       123764 :                 let layer = guard.get_from_desc(&layer);
    2893       123764 :                 drop(guard);
    2894       123764 : 
    2895       123764 :                 // Get all the data needed to reconstruct the page version from this layer.
    2896       123764 :                 // But if we have an older cached page image, no need to go past that.
    2897       123764 :                 let lsn_floor = max(cached_lsn + 1, lsn_floor);
    2898       123764 :                 result = match layer
    2899       123764 :                     .get_value_reconstruct_data(key, lsn_floor..cont_lsn, reconstruct_state, ctx)
    2900        23436 :                     .await
    2901              :                 {
    2902       123764 :                     Ok(result) => result,
    2903            0 :                     Err(e) => return Err(PageReconstructError::from(e)),
    2904              :                 };
    2905       123764 :                 cont_lsn = lsn_floor;
    2906       123764 :                 *read_count += 1;
    2907       123764 :                 traversal_path.push((
    2908       123764 :                     result,
    2909       123764 :                     cont_lsn,
    2910       123764 :                     Box::new({
    2911       123764 :                         let layer = layer.to_owned();
    2912       123764 :                         move || layer.traversal_id()
    2913       123764 :                     }),
    2914       123764 :                 ));
    2915       123764 :                 continue 'outer;
    2916          104 :             } else if timeline.ancestor_timeline.is_some() {
    2917              :                 // Nothing on this timeline. Traverse to parent
    2918          102 :                 result = ValueReconstructResult::Continue;
    2919          102 :                 cont_lsn = Lsn(timeline.ancestor_lsn.0 + 1);
    2920          102 :                 continue 'outer;
    2921              :             } else {
    2922              :                 // Nothing found
    2923            2 :                 result = ValueReconstructResult::Missing;
    2924            2 :                 continue 'outer;
    2925              :             }
    2926              :         }
    2927       502833 :     }
    2928              : 
    2929              :     /// Get the data needed to reconstruct all keys in the provided keyspace
    2930              :     ///
    2931              :     /// The algorithm is as follows:
    2932              :     /// 1.   While some keys are still not done and there's a timeline to visit:
    2933              :     /// 2.   Visit the timeline (see [`Timeline::get_vectored_reconstruct_data_timeline`]:
    2934              :     /// 2.1: Build the fringe for the current keyspace
    2935              :     /// 2.2  Visit the newest layer from the fringe to collect all values for the range it
    2936              :     ///      intersects
    2937              :     /// 2.3. Pop the timeline from the fringe
    2938              :     /// 2.4. If the fringe is empty, go back to 1
    2939           12 :     async fn get_vectored_reconstruct_data(
    2940           12 :         &self,
    2941           12 :         mut keyspace: KeySpace,
    2942           12 :         request_lsn: Lsn,
    2943           12 :         reconstruct_state: &mut ValuesReconstructState,
    2944           12 :         ctx: &RequestContext,
    2945           12 :     ) -> Result<(), GetVectoredError> {
    2946           12 :         let mut timeline_owned: Arc<Timeline>;
    2947           12 :         let mut timeline = self;
    2948           12 : 
    2949           12 :         let mut cont_lsn = Lsn(request_lsn.0 + 1);
    2950              : 
    2951              :         loop {
    2952           14 :             if self.cancel.is_cancelled() {
    2953            0 :                 return Err(GetVectoredError::Cancelled);
    2954           14 :             }
    2955              : 
    2956           14 :             let completed = Self::get_vectored_reconstruct_data_timeline(
    2957           14 :                 timeline,
    2958           14 :                 keyspace.clone(),
    2959           14 :                 cont_lsn,
    2960           14 :                 reconstruct_state,
    2961           14 :                 &self.cancel,
    2962           14 :                 ctx,
    2963           14 :             )
    2964           41 :             .await?;
    2965              : 
    2966           14 :             keyspace.remove_overlapping_with(&completed);
    2967           14 :             if keyspace.total_size() == 0 || timeline.ancestor_timeline.is_none() {
    2968           12 :                 break;
    2969            2 :             }
    2970            2 : 
    2971            2 :             cont_lsn = Lsn(timeline.ancestor_lsn.0 + 1);
    2972            2 :             timeline_owned = timeline
    2973            2 :                 .get_ready_ancestor_timeline(ctx)
    2974            0 :                 .await
    2975            2 :                 .map_err(GetVectoredError::GetReadyAncestorError)?;
    2976            2 :             timeline = &*timeline_owned;
    2977              :         }
    2978              : 
    2979           12 :         if keyspace.total_size() != 0 {
    2980            0 :             return Err(GetVectoredError::MissingKey(keyspace.start().unwrap()));
    2981           12 :         }
    2982           12 : 
    2983           12 :         Ok(())
    2984           12 :     }
    2985              : 
    2986              :     /// Collect the reconstruct data for a ketspace from the specified timeline.
    2987              :     ///
    2988              :     /// Maintain a fringe [`LayerFringe`] which tracks all the layers that intersect
    2989              :     /// the current keyspace. The current keyspace of the search at any given timeline
    2990              :     /// is the original keyspace minus all the keys that have been completed minus
    2991              :     /// any keys for which we couldn't find an intersecting layer. It's not tracked explicitly,
    2992              :     /// but if you merge all the keyspaces in the fringe, you get the "current keyspace".
    2993              :     ///
    2994              :     /// This is basically a depth-first search visitor implementation where a vertex
    2995              :     /// is the (layer, lsn range, key space) tuple. The fringe acts as the stack.
    2996              :     ///
    2997              :     /// At each iteration pop the top of the fringe (the layer with the highest Lsn)
    2998              :     /// and get all the required reconstruct data from the layer in one go.
    2999           14 :     async fn get_vectored_reconstruct_data_timeline(
    3000           14 :         timeline: &Timeline,
    3001           14 :         keyspace: KeySpace,
    3002           14 :         mut cont_lsn: Lsn,
    3003           14 :         reconstruct_state: &mut ValuesReconstructState,
    3004           14 :         cancel: &CancellationToken,
    3005           14 :         ctx: &RequestContext,
    3006           14 :     ) -> Result<KeySpace, GetVectoredError> {
    3007           14 :         let mut unmapped_keyspace = keyspace.clone();
    3008           14 :         let mut fringe = LayerFringe::new();
    3009           14 : 
    3010           14 :         let mut completed_keyspace = KeySpace::default();
    3011              : 
    3012           32 :         loop {
    3013           32 :             if cancel.is_cancelled() {
    3014            0 :                 return Err(GetVectoredError::Cancelled);
    3015           32 :             }
    3016           32 : 
    3017           32 :             let keys_done_last_step = reconstruct_state.consume_done_keys();
    3018           32 :             unmapped_keyspace.remove_overlapping_with(&keys_done_last_step);
    3019           32 :             completed_keyspace.merge(&keys_done_last_step);
    3020              : 
    3021           32 :             let guard = timeline.layers.read().await;
    3022           32 :             let layers = guard.layer_map();
    3023           32 : 
    3024           32 :             let in_memory_layer = layers.find_in_memory_layer(|l| {
    3025            0 :                 let start_lsn = l.get_lsn_range().start;
    3026            0 :                 cont_lsn > start_lsn
    3027           32 :             });
    3028           32 : 
    3029           32 :             match in_memory_layer {
    3030            0 :                 Some(l) => {
    3031            0 :                     let lsn_range = l.get_lsn_range().start..cont_lsn;
    3032            0 :                     fringe.update(
    3033            0 :                         ReadableLayer::InMemoryLayer(l),
    3034            0 :                         unmapped_keyspace.clone(),
    3035            0 :                         lsn_range,
    3036            0 :                     );
    3037            0 :                 }
    3038              :                 None => {
    3039           32 :                     for range in unmapped_keyspace.ranges.iter() {
    3040           18 :                         let results = layers.range_search(range.clone(), cont_lsn);
    3041           18 : 
    3042           18 :                         results
    3043           18 :                             .found
    3044           18 :                             .into_iter()
    3045           18 :                             .map(|(SearchResult { layer, lsn_floor }, keyspace_accum)| {
    3046           18 :                                 (
    3047           18 :                                     ReadableLayer::PersistentLayer(guard.get_from_desc(&layer)),
    3048           18 :                                     keyspace_accum.to_keyspace(),
    3049           18 :                                     lsn_floor..cont_lsn,
    3050           18 :                                 )
    3051           18 :                             })
    3052           18 :                             .for_each(|(layer, keyspace, lsn_range)| {
    3053           18 :                                 fringe.update(layer, keyspace, lsn_range)
    3054           18 :                             });
    3055           18 :                     }
    3056              :                 }
    3057              :             }
    3058              : 
    3059              :             // It's safe to drop the layer map lock after planning the next round of reads.
    3060              :             // The fringe keeps readable handles for the layers which are safe to read even
    3061              :             // if layers were compacted or flushed.
    3062              :             //
    3063              :             // The more interesting consideration is: "Why is the read algorithm still correct
    3064              :             // if the layer map changes while it is operating?". Doing a vectored read on a
    3065              :             // timeline boils down to pushing an imaginary lsn boundary downwards for each range
    3066              :             // covered by the read. The layer map tells us how to move the lsn downwards for a
    3067              :             // range at *a particular point in time*. It is fine for the answer to be different
    3068              :             // at two different time points.
    3069           32 :             drop(guard);
    3070              : 
    3071           32 :             if let Some((layer_to_read, keyspace_to_read, lsn_range)) = fringe.next_layer() {
    3072           18 :                 let next_cont_lsn = lsn_range.start;
    3073           18 :                 layer_to_read
    3074           18 :                     .get_values_reconstruct_data(
    3075           18 :                         keyspace_to_read.clone(),
    3076           18 :                         lsn_range,
    3077           18 :                         reconstruct_state,
    3078           18 :                         ctx,
    3079           18 :                     )
    3080           41 :                     .await?;
    3081              : 
    3082           18 :                 unmapped_keyspace = keyspace_to_read;
    3083           18 :                 cont_lsn = next_cont_lsn;
    3084              :             } else {
    3085           14 :                 break;
    3086           14 :             }
    3087           14 :         }
    3088           14 : 
    3089           14 :         Ok(completed_keyspace)
    3090           14 :     }
    3091              : 
    3092              :     /// # Cancel-safety
    3093              :     ///
    3094              :     /// This method is cancellation-safe.
    3095       502833 :     async fn lookup_cached_page(
    3096       502833 :         &self,
    3097       502833 :         key: &Key,
    3098       502833 :         lsn: Lsn,
    3099       502833 :         ctx: &RequestContext,
    3100       502833 :     ) -> Option<(Lsn, Bytes)> {
    3101       502833 :         let cache = page_cache::get();
    3102              : 
    3103              :         // FIXME: It's pointless to check the cache for things that are not 8kB pages.
    3104              :         // We should look at the key to determine if it's a cacheable object
    3105       502833 :         let (lsn, read_guard) = cache
    3106       502833 :             .lookup_materialized_page(self.tenant_shard_id, self.timeline_id, key, lsn, ctx)
    3107       502833 :             .await?;
    3108            0 :         let img = Bytes::from(read_guard.to_vec());
    3109            0 :         Some((lsn, img))
    3110       502833 :     }
    3111              : 
    3112       226807 :     async fn get_ready_ancestor_timeline(
    3113       226807 :         &self,
    3114       226807 :         ctx: &RequestContext,
    3115       226807 :     ) -> Result<Arc<Timeline>, GetReadyAncestorError> {
    3116       226807 :         let ancestor = match self.get_ancestor_timeline() {
    3117       226807 :             Ok(timeline) => timeline,
    3118            0 :             Err(e) => return Err(GetReadyAncestorError::from(e)),
    3119              :         };
    3120              : 
    3121              :         // It's possible that the ancestor timeline isn't active yet, or
    3122              :         // is active but hasn't yet caught up to the branch point. Wait
    3123              :         // for it.
    3124              :         //
    3125              :         // This cannot happen while the pageserver is running normally,
    3126              :         // because you cannot create a branch from a point that isn't
    3127              :         // present in the pageserver yet. However, we don't wait for the
    3128              :         // branch point to be uploaded to cloud storage before creating
    3129              :         // a branch. I.e., the branch LSN need not be remote consistent
    3130              :         // for the branching operation to succeed.
    3131              :         //
    3132              :         // Hence, if we try to load a tenant in such a state where
    3133              :         // 1. the existence of the branch was persisted (in IndexPart and/or locally)
    3134              :         // 2. but the ancestor state is behind branch_lsn because it was not yet persisted
    3135              :         // then we will need to wait for the ancestor timeline to
    3136              :         // re-stream WAL up to branch_lsn before we access it.
    3137              :         //
    3138              :         // How can a tenant get in such a state?
    3139              :         // - ungraceful pageserver process exit
    3140              :         // - detach+attach => this is a bug, https://github.com/neondatabase/neon/issues/4219
    3141              :         //
    3142              :         // NB: this could be avoided by requiring
    3143              :         //   branch_lsn >= remote_consistent_lsn
    3144              :         // during branch creation.
    3145       226807 :         match ancestor.wait_to_become_active(ctx).await {
    3146       226805 :             Ok(()) => {}
    3147              :             Err(TimelineState::Stopping) => {
    3148            0 :                 return Err(GetReadyAncestorError::AncestorStopping(
    3149            0 :                     ancestor.timeline_id,
    3150            0 :                 ));
    3151              :             }
    3152            2 :             Err(state) => {
    3153            2 :                 return Err(GetReadyAncestorError::Other(anyhow::anyhow!(
    3154            2 :                     "Timeline {} will not become active. Current state: {:?}",
    3155            2 :                     ancestor.timeline_id,
    3156            2 :                     &state,
    3157            2 :                 )));
    3158              :             }
    3159              :         }
    3160       226805 :         ancestor
    3161       226805 :             .wait_lsn(self.ancestor_lsn, WaitLsnWaiter::Timeline(self), ctx)
    3162            0 :             .await
    3163       226805 :             .map_err(|e| match e {
    3164            0 :                 e @ WaitLsnError::Timeout(_) => GetReadyAncestorError::AncestorLsnTimeout(e),
    3165            0 :                 WaitLsnError::Shutdown => GetReadyAncestorError::Cancelled,
    3166            0 :                 e @ WaitLsnError::BadState => GetReadyAncestorError::Other(anyhow::anyhow!(e)),
    3167       226805 :             })?;
    3168              : 
    3169       226805 :         Ok(ancestor)
    3170       226807 :     }
    3171              : 
    3172       226807 :     fn get_ancestor_timeline(&self) -> anyhow::Result<Arc<Timeline>> {
    3173       226807 :         let ancestor = self.ancestor_timeline.as_ref().with_context(|| {
    3174            0 :             format!(
    3175            0 :                 "Ancestor is missing. Timeline id: {} Ancestor id {:?}",
    3176            0 :                 self.timeline_id,
    3177            0 :                 self.get_ancestor_timeline_id(),
    3178            0 :             )
    3179       226807 :         })?;
    3180       226807 :         Ok(Arc::clone(ancestor))
    3181       226807 :     }
    3182              : 
    3183         5452 :     pub(crate) fn get_shard_identity(&self) -> &ShardIdentity {
    3184         5452 :         &self.shard_identity
    3185         5452 :     }
    3186              : 
    3187              :     ///
    3188              :     /// Get a handle to the latest layer for appending.
    3189              :     ///
    3190      3648020 :     async fn get_layer_for_write(&self, lsn: Lsn) -> anyhow::Result<Arc<InMemoryLayer>> {
    3191      3648020 :         let mut guard = self.layers.write().await;
    3192      3648020 :         let layer = guard
    3193      3648020 :             .get_layer_for_write(
    3194      3648020 :                 lsn,
    3195      3648020 :                 self.get_last_record_lsn(),
    3196      3648020 :                 self.conf,
    3197      3648020 :                 self.timeline_id,
    3198      3648020 :                 self.tenant_shard_id,
    3199      3648020 :             )
    3200          455 :             .await?;
    3201      3648020 :         Ok(layer)
    3202      3648020 :     }
    3203              : 
    3204      4122936 :     pub(crate) fn finish_write(&self, new_lsn: Lsn) {
    3205      4122936 :         assert!(new_lsn.is_aligned());
    3206              : 
    3207      4122936 :         self.metrics.last_record_gauge.set(new_lsn.0 as i64);
    3208      4122936 :         self.last_record_lsn.advance(new_lsn);
    3209      4122936 :     }
    3210              : 
    3211              :     /// Whether there was a layer to freeze or not, return the value of get_last_record_lsn
    3212              :     /// before we attempted the freeze: this guarantees that ingested data is frozen up to this lsn (inclusive).
    3213          698 :     async fn freeze_inmem_layer(&self, write_lock_held: bool) -> Lsn {
    3214              :         // Freeze the current open in-memory layer. It will be written to disk on next
    3215              :         // iteration.
    3216              : 
    3217          698 :         let _write_guard = if write_lock_held {
    3218            0 :             None
    3219              :         } else {
    3220          698 :             Some(self.write_lock.lock().await)
    3221              :         };
    3222              : 
    3223          698 :         let to_lsn = self.get_last_record_lsn();
    3224          698 :         self.freeze_inmem_layer_at(to_lsn).await;
    3225          698 :         to_lsn
    3226          698 :     }
    3227              : 
    3228          698 :     async fn freeze_inmem_layer_at(&self, at: Lsn) {
    3229          698 :         let mut guard = self.layers.write().await;
    3230          698 :         guard
    3231          698 :             .try_freeze_in_memory_layer(at, &self.last_freeze_at)
    3232            2 :             .await;
    3233          698 :     }
    3234              : 
    3235              :     /// Layer flusher task's main loop.
    3236          316 :     async fn flush_loop(
    3237          316 :         self: &Arc<Self>,
    3238          316 :         mut layer_flush_start_rx: tokio::sync::watch::Receiver<(u64, Lsn)>,
    3239          316 :         ctx: &RequestContext,
    3240          316 :     ) {
    3241          316 :         info!("started flush loop");
    3242          698 :         loop {
    3243         1630 :             tokio::select! {
    3244         1630 :                 _ = self.cancel.cancelled() => {
    3245         1630 :                     info!("shutting down layer flush task due to Timeline::cancel");
    3246         1630 :                     break;
    3247         1630 :                 },
    3248         1630 :                 _ = layer_flush_start_rx.changed() => {}
    3249         1630 :             }
    3250          698 :             trace!("waking up");
    3251          698 :             let (flush_counter, frozen_to_lsn) = *layer_flush_start_rx.borrow();
    3252          698 : 
    3253          698 :             // The highest LSN to which we flushed in the loop over frozen layers
    3254          698 :             let mut flushed_to_lsn = Lsn(0);
    3255              : 
    3256          698 :             let result = loop {
    3257         1390 :                 if self.cancel.is_cancelled() {
    3258            0 :                     info!("dropping out of flush loop for timeline shutdown");
    3259              :                     // Note: we do not bother transmitting into [`layer_flush_done_tx`], because
    3260              :                     // anyone waiting on that will respect self.cancel as well: they will stop
    3261              :                     // waiting at the same time we as drop out of this loop.
    3262            0 :                     return;
    3263         1390 :                 }
    3264         1390 : 
    3265         1390 :                 let timer = self.metrics.flush_time_histo.start_timer();
    3266              : 
    3267         1390 :                 let layer_to_flush = {
    3268         1390 :                     let guard = self.layers.read().await;
    3269         1390 :                     guard.layer_map().frozen_layers.front().cloned()
    3270              :                     // drop 'layers' lock to allow concurrent reads and writes
    3271              :                 };
    3272         1390 :                 let Some(layer_to_flush) = layer_to_flush else {
    3273          698 :                     break Ok(());
    3274              :                 };
    3275        61298 :                 match self.flush_frozen_layer(layer_to_flush, ctx).await {
    3276          692 :                     Ok(this_layer_to_lsn) => {
    3277          692 :                         flushed_to_lsn = std::cmp::max(flushed_to_lsn, this_layer_to_lsn);
    3278          692 :                     }
    3279              :                     Err(FlushLayerError::Cancelled) => {
    3280            0 :                         info!("dropping out of flush loop for timeline shutdown");
    3281            0 :                         return;
    3282              :                     }
    3283            0 :                     err @ Err(
    3284              :                         FlushLayerError::Other(_) | FlushLayerError::CreateImageLayersError(_),
    3285              :                     ) => {
    3286            0 :                         error!("could not flush frozen layer: {err:?}");
    3287            0 :                         break err.map(|_| ());
    3288              :                     }
    3289              :                 }
    3290          692 :                 timer.stop_and_record();
    3291              :             };
    3292              : 
    3293              :             // Unsharded tenants should never advance their LSN beyond the end of the
    3294              :             // highest layer they write: such gaps between layer data and the frozen LSN
    3295              :             // are only legal on sharded tenants.
    3296          698 :             debug_assert!(
    3297          698 :                 self.shard_identity.count.count() > 1
    3298          698 :                     || flushed_to_lsn >= frozen_to_lsn
    3299            6 :                     || !flushed_to_lsn.is_valid()
    3300              :             );
    3301              : 
    3302          698 :             if flushed_to_lsn < frozen_to_lsn && self.shard_identity.count.count() > 1 {
    3303              :                 // If our layer flushes didn't carry disk_consistent_lsn up to the `to_lsn` advertised
    3304              :                 // to us via layer_flush_start_rx, then advance it here.
    3305              :                 //
    3306              :                 // This path is only taken for tenants with multiple shards: single sharded tenants should
    3307              :                 // never encounter a gap in the wal.
    3308            0 :                 let old_disk_consistent_lsn = self.disk_consistent_lsn.load();
    3309            0 :                 tracing::debug!("Advancing disk_consistent_lsn across layer gap {old_disk_consistent_lsn}->{frozen_to_lsn}");
    3310            0 :                 if self.set_disk_consistent_lsn(frozen_to_lsn) {
    3311            0 :                     if let Err(e) = self.schedule_uploads(frozen_to_lsn, vec![]) {
    3312            0 :                         tracing::warn!("Failed to schedule metadata upload after updating disk_consistent_lsn: {e}");
    3313            0 :                     }
    3314            0 :                 }
    3315          698 :             }
    3316              : 
    3317              :             // Notify any listeners that we're done
    3318          698 :             let _ = self
    3319          698 :                 .layer_flush_done_tx
    3320          698 :                 .send_replace((flush_counter, result));
    3321              :         }
    3322            8 :     }
    3323              : 
    3324              :     /// Request the flush loop to write out all frozen layers up to `to_lsn` as Delta L0 files to disk.
    3325              :     /// The caller is responsible for the freezing, e.g., [`Self::freeze_inmem_layer`].
    3326              :     ///
    3327              :     /// `last_record_lsn` may be higher than the highest LSN of a frozen layer: if this is the case,
    3328              :     /// it means no data will be written between the top of the highest frozen layer and to_lsn,
    3329              :     /// e.g. because this tenant shard has ingested up to to_lsn and not written any data locally for that part of the WAL.
    3330          698 :     async fn flush_frozen_layers_and_wait(&self, last_record_lsn: Lsn) -> anyhow::Result<()> {
    3331          698 :         let mut rx = self.layer_flush_done_tx.subscribe();
    3332          698 : 
    3333          698 :         // Increment the flush cycle counter and wake up the flush task.
    3334          698 :         // Remember the new value, so that when we listen for the flush
    3335          698 :         // to finish, we know when the flush that we initiated has
    3336          698 :         // finished, instead of some other flush that was started earlier.
    3337          698 :         let mut my_flush_request = 0;
    3338          698 : 
    3339          698 :         let flush_loop_state = { *self.flush_loop_state.lock().unwrap() };
    3340          698 :         if !matches!(flush_loop_state, FlushLoopState::Running { .. }) {
    3341            0 :             anyhow::bail!("cannot flush frozen layers when flush_loop is not running, state is {flush_loop_state:?}")
    3342          698 :         }
    3343          698 : 
    3344          698 :         self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
    3345          698 :             my_flush_request = *counter + 1;
    3346          698 :             *counter = my_flush_request;
    3347          698 :             *lsn = std::cmp::max(last_record_lsn, *lsn);
    3348          698 :         });
    3349              : 
    3350         1394 :         loop {
    3351         1394 :             {
    3352         1394 :                 let (last_result_counter, last_result) = &*rx.borrow();
    3353         1394 :                 if *last_result_counter >= my_flush_request {
    3354          698 :                     if let Err(_err) = last_result {
    3355              :                         // We already logged the original error in
    3356              :                         // flush_loop. We cannot propagate it to the caller
    3357              :                         // here, because it might not be Cloneable
    3358            0 :                         anyhow::bail!(
    3359            0 :                             "Could not flush frozen layer. Request id: {}",
    3360            0 :                             my_flush_request
    3361            0 :                         );
    3362              :                     } else {
    3363          698 :                         return Ok(());
    3364              :                     }
    3365          696 :                 }
    3366          696 :             }
    3367          696 :             trace!("waiting for flush to complete");
    3368         1392 :             tokio::select! {
    3369          696 :                 rx_e = rx.changed() => {
    3370              :                     rx_e?;
    3371              :                 },
    3372              :                 // Cancellation safety: we are not leaving an I/O in-flight for the flush, we're just ignoring
    3373              :                 // the notification from [`flush_loop`] that it completed.
    3374              :                 _ = self.cancel.cancelled() => {
    3375            0 :                     tracing::info!("Cancelled layer flush due on timeline shutdown");
    3376              :                     return Ok(())
    3377              :                 }
    3378              :             };
    3379          696 :             trace!("done")
    3380              :         }
    3381          698 :     }
    3382              : 
    3383            0 :     fn flush_frozen_layers(&self) {
    3384            0 :         self.layer_flush_start_tx.send_modify(|(counter, lsn)| {
    3385            0 :             *counter += 1;
    3386            0 : 
    3387            0 :             *lsn = std::cmp::max(*lsn, Lsn(self.last_freeze_at.load().0 - 1));
    3388            0 :         });
    3389            0 :     }
    3390              : 
    3391              :     /// Flush one frozen in-memory layer to disk, as a new delta layer.
    3392              :     ///
    3393              :     /// Return value is the last lsn (inclusive) of the layer that was frozen.
    3394         1384 :     #[instrument(skip_all, fields(layer=%frozen_layer))]
    3395              :     async fn flush_frozen_layer(
    3396              :         self: &Arc<Self>,
    3397              :         frozen_layer: Arc<InMemoryLayer>,
    3398              :         ctx: &RequestContext,
    3399              :     ) -> Result<Lsn, FlushLayerError> {
    3400              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3401              : 
    3402              :         // As a special case, when we have just imported an image into the repository,
    3403              :         // instead of writing out a L0 delta layer, we directly write out image layer
    3404              :         // files instead. This is possible as long as *all* the data imported into the
    3405              :         // repository have the same LSN.
    3406              :         let lsn_range = frozen_layer.get_lsn_range();
    3407              :         let (layers_to_upload, delta_layer_to_add) =
    3408              :             if lsn_range.start == self.initdb_lsn && lsn_range.end == Lsn(self.initdb_lsn.0 + 1) {
    3409              :                 #[cfg(test)]
    3410              :                 match &mut *self.flush_loop_state.lock().unwrap() {
    3411              :                     FlushLoopState::NotStarted | FlushLoopState::Exited => {
    3412              :                         panic!("flush loop not running")
    3413              :                     }
    3414              :                     FlushLoopState::Running {
    3415              :                         initdb_optimization_count,
    3416              :                         ..
    3417              :                     } => {
    3418              :                         *initdb_optimization_count += 1;
    3419              :                     }
    3420              :                 }
    3421              :                 // Note: The 'ctx' in use here has DownloadBehavior::Error. We should not
    3422              :                 // require downloading anything during initial import.
    3423              :                 let (partitioning, _lsn) = self
    3424              :                     .repartition(
    3425              :                         self.initdb_lsn,
    3426              :                         self.get_compaction_target_size(),
    3427              :                         EnumSet::empty(),
    3428              :                         ctx,
    3429              :                     )
    3430              :                     .await?;
    3431              : 
    3432              :                 if self.cancel.is_cancelled() {
    3433              :                     return Err(FlushLayerError::Cancelled);
    3434              :                 }
    3435              : 
    3436              :                 // For image layers, we add them immediately into the layer map.
    3437              :                 (
    3438              :                     self.create_image_layers(&partitioning, self.initdb_lsn, true, ctx)
    3439              :                         .await?,
    3440              :                     None,
    3441              :                 )
    3442              :             } else {
    3443              :                 #[cfg(test)]
    3444              :                 match &mut *self.flush_loop_state.lock().unwrap() {
    3445              :                     FlushLoopState::NotStarted | FlushLoopState::Exited => {
    3446              :                         panic!("flush loop not running")
    3447              :                     }
    3448              :                     FlushLoopState::Running {
    3449              :                         expect_initdb_optimization,
    3450              :                         ..
    3451              :                     } => {
    3452              :                         assert!(!*expect_initdb_optimization, "expected initdb optimization");
    3453              :                     }
    3454              :                 }
    3455              :                 // Normal case, write out a L0 delta layer file.
    3456              :                 // `create_delta_layer` will not modify the layer map.
    3457              :                 // We will remove frozen layer and add delta layer in one atomic operation later.
    3458              :                 let layer = self.create_delta_layer(&frozen_layer, ctx).await?;
    3459              :                 (
    3460              :                     // FIXME: even though we have a single image and single delta layer assumption
    3461              :                     // we push them to vec
    3462              :                     vec![layer.clone()],
    3463              :                     Some(layer),
    3464              :                 )
    3465              :             };
    3466              : 
    3467          692 :         pausable_failpoint!("flush-layer-cancel-after-writing-layer-out-pausable");
    3468              : 
    3469              :         if self.cancel.is_cancelled() {
    3470              :             return Err(FlushLayerError::Cancelled);
    3471              :         }
    3472              : 
    3473              :         let disk_consistent_lsn = Lsn(lsn_range.end.0 - 1);
    3474              : 
    3475              :         // The new on-disk layers are now in the layer map. We can remove the
    3476              :         // in-memory layer from the map now. The flushed layer is stored in
    3477              :         // the mapping in `create_delta_layer`.
    3478              :         {
    3479              :             let mut guard = self.layers.write().await;
    3480              : 
    3481              :             if self.cancel.is_cancelled() {
    3482              :                 return Err(FlushLayerError::Cancelled);
    3483              :             }
    3484              : 
    3485              :             guard.finish_flush_l0_layer(delta_layer_to_add.as_ref(), &frozen_layer, &self.metrics);
    3486              : 
    3487              :             if self.set_disk_consistent_lsn(disk_consistent_lsn) {
    3488              :                 // Schedule remote uploads that will reflect our new disk_consistent_lsn
    3489              :                 self.schedule_uploads(disk_consistent_lsn, layers_to_upload)?;
    3490              :             }
    3491              :             // release lock on 'layers'
    3492              :         };
    3493              : 
    3494              :         // FIXME: between create_delta_layer and the scheduling of the upload in `update_metadata_file`,
    3495              :         // a compaction can delete the file and then it won't be available for uploads any more.
    3496              :         // We still schedule the upload, resulting in an error, but ideally we'd somehow avoid this
    3497              :         // race situation.
    3498              :         // See https://github.com/neondatabase/neon/issues/4526
    3499          692 :         pausable_failpoint!("flush-frozen-pausable");
    3500              : 
    3501              :         // This failpoint is used by another test case `test_pageserver_recovery`.
    3502            0 :         fail_point!("flush-frozen-exit");
    3503              : 
    3504              :         Ok(Lsn(lsn_range.end.0 - 1))
    3505              :     }
    3506              : 
    3507              :     /// Return true if the value changed
    3508              :     ///
    3509              :     /// This function must only be used from the layer flush task, and may not be called concurrently.
    3510          692 :     fn set_disk_consistent_lsn(&self, new_value: Lsn) -> bool {
    3511          692 :         // We do a simple load/store cycle: that's why this function isn't safe for concurrent use.
    3512          692 :         let old_value = self.disk_consistent_lsn.load();
    3513          692 :         if new_value != old_value {
    3514          692 :             assert!(new_value >= old_value);
    3515          692 :             self.disk_consistent_lsn.store(new_value);
    3516          692 :             true
    3517              :         } else {
    3518            0 :             false
    3519              :         }
    3520          692 :     }
    3521              : 
    3522              :     /// Update metadata file
    3523          692 :     fn schedule_uploads(
    3524          692 :         &self,
    3525          692 :         disk_consistent_lsn: Lsn,
    3526          692 :         layers_to_upload: impl IntoIterator<Item = ResidentLayer>,
    3527          692 :     ) -> anyhow::Result<TimelineMetadata> {
    3528          692 :         // We can only save a valid 'prev_record_lsn' value on disk if we
    3529          692 :         // flushed *all* in-memory changes to disk. We only track
    3530          692 :         // 'prev_record_lsn' in memory for the latest processed record, so we
    3531          692 :         // don't remember what the correct value that corresponds to some old
    3532          692 :         // LSN is. But if we flush everything, then the value corresponding
    3533          692 :         // current 'last_record_lsn' is correct and we can store it on disk.
    3534          692 :         let RecordLsn {
    3535          692 :             last: last_record_lsn,
    3536          692 :             prev: prev_record_lsn,
    3537          692 :         } = self.last_record_lsn.load();
    3538          692 :         let ondisk_prev_record_lsn = if disk_consistent_lsn == last_record_lsn {
    3539          692 :             Some(prev_record_lsn)
    3540              :         } else {
    3541            0 :             None
    3542              :         };
    3543              : 
    3544          692 :         let ancestor_timeline_id = self
    3545          692 :             .ancestor_timeline
    3546          692 :             .as_ref()
    3547          692 :             .map(|ancestor| ancestor.timeline_id);
    3548          692 : 
    3549          692 :         let metadata = TimelineMetadata::new(
    3550          692 :             disk_consistent_lsn,
    3551          692 :             ondisk_prev_record_lsn,
    3552          692 :             ancestor_timeline_id,
    3553          692 :             self.ancestor_lsn,
    3554          692 :             *self.latest_gc_cutoff_lsn.read(),
    3555          692 :             self.initdb_lsn,
    3556          692 :             self.pg_version,
    3557          692 :         );
    3558          692 : 
    3559          692 :         fail_point!("checkpoint-before-saving-metadata", |x| bail!(
    3560            0 :             "{}",
    3561            0 :             x.unwrap()
    3562          692 :         ));
    3563              : 
    3564          692 :         if let Some(remote_client) = &self.remote_client {
    3565         1398 :             for layer in layers_to_upload {
    3566          706 :                 remote_client.schedule_layer_file_upload(layer)?;
    3567              :             }
    3568          692 :             remote_client.schedule_index_upload_for_metadata_update(&metadata)?;
    3569            0 :         }
    3570              : 
    3571          692 :         Ok(metadata)
    3572          692 :     }
    3573              : 
    3574            0 :     pub(crate) async fn preserve_initdb_archive(&self) -> anyhow::Result<()> {
    3575            0 :         if let Some(remote_client) = &self.remote_client {
    3576            0 :             remote_client
    3577            0 :                 .preserve_initdb_archive(
    3578            0 :                     &self.tenant_shard_id.tenant_id,
    3579            0 :                     &self.timeline_id,
    3580            0 :                     &self.cancel,
    3581            0 :                 )
    3582            0 :                 .await?;
    3583              :         } else {
    3584            0 :             bail!("No remote storage configured, but was asked to backup the initdb archive for {} / {}", self.tenant_shard_id.tenant_id, self.timeline_id);
    3585              :         }
    3586            0 :         Ok(())
    3587            0 :     }
    3588              : 
    3589              :     // Write out the given frozen in-memory layer as a new L0 delta file. This L0 file will not be tracked
    3590              :     // in layer map immediately. The caller is responsible to put it into the layer map.
    3591          598 :     async fn create_delta_layer(
    3592          598 :         self: &Arc<Self>,
    3593          598 :         frozen_layer: &Arc<InMemoryLayer>,
    3594          598 :         ctx: &RequestContext,
    3595          598 :     ) -> anyhow::Result<ResidentLayer> {
    3596          598 :         let self_clone = Arc::clone(self);
    3597          598 :         let frozen_layer = Arc::clone(frozen_layer);
    3598          598 :         let ctx = ctx.attached_child();
    3599          598 :         let work = async move {
    3600        83340 :             let new_delta = frozen_layer.write_to_disk(&self_clone, &ctx).await?;
    3601              :             // The write_to_disk() above calls writer.finish() which already did the fsync of the inodes.
    3602              :             // We just need to fsync the directory in which these inodes are linked,
    3603              :             // which we know to be the timeline directory.
    3604              :             //
    3605              :             // We use fatal_err() below because the after write_to_disk returns with success,
    3606              :             // the in-memory state of the filesystem already has the layer file in its final place,
    3607              :             // and subsequent pageserver code could think it's durable while it really isn't.
    3608          598 :             let timeline_dir = VirtualFile::open(
    3609          598 :                 &self_clone
    3610          598 :                     .conf
    3611          598 :                     .timeline_path(&self_clone.tenant_shard_id, &self_clone.timeline_id),
    3612          598 :             )
    3613          299 :             .await
    3614          598 :             .fatal_err("VirtualFile::open for timeline dir fsync");
    3615          598 :             timeline_dir
    3616          598 :                 .sync_all()
    3617          299 :                 .await
    3618          598 :                 .fatal_err("VirtualFile::sync_all timeline dir");
    3619          598 :             anyhow::Ok(new_delta)
    3620          598 :         };
    3621              :         // Before tokio-epoll-uring, we ran write_to_disk & the sync_all inside spawn_blocking.
    3622              :         // Preserve that behavior to maintain the same behavior for `virtual_file_io_engine=std-fs`.
    3623              :         use crate::virtual_file::io_engine::IoEngine;
    3624          598 :         match crate::virtual_file::io_engine::get() {
    3625            0 :             IoEngine::NotSet => panic!("io engine not set"),
    3626              :             IoEngine::StdFs => {
    3627          299 :                 let span = tracing::info_span!("blocking");
    3628          299 :                 tokio::task::spawn_blocking({
    3629          299 :                     move || Handle::current().block_on(work.instrument(span))
    3630          299 :                 })
    3631          299 :                 .await
    3632          299 :                 .context("spawn_blocking")
    3633          299 :                 .and_then(|x| x)
    3634              :             }
    3635              :             #[cfg(target_os = "linux")]
    3636        58411 :             IoEngine::TokioEpollUring => work.await,
    3637              :         }
    3638          598 :     }
    3639              : 
    3640          604 :     async fn repartition(
    3641          604 :         &self,
    3642          604 :         lsn: Lsn,
    3643          604 :         partition_size: u64,
    3644          604 :         flags: EnumSet<CompactFlags>,
    3645          604 :         ctx: &RequestContext,
    3646          604 :     ) -> anyhow::Result<(KeyPartitioning, Lsn)> {
    3647          604 :         let Ok(mut partitioning_guard) = self.partitioning.try_lock() else {
    3648              :             // NB: there are two callers, one is the compaction task, of which there is only one per struct Tenant and hence Timeline.
    3649              :             // The other is the initdb optimization in flush_frozen_layer, used by `boostrap_timeline`, which runs before `.activate()`
    3650              :             // and hence before the compaction task starts.
    3651            0 :             anyhow::bail!("repartition() called concurrently, this should not happen");
    3652              :         };
    3653          604 :         if lsn < partitioning_guard.1 {
    3654            0 :             anyhow::bail!("repartition() called with LSN going backwards, this should not happen");
    3655          604 :         }
    3656          604 : 
    3657          604 :         let distance = lsn.0 - partitioning_guard.1 .0;
    3658          604 :         if partitioning_guard.1 != Lsn(0)
    3659          408 :             && distance <= self.repartition_threshold
    3660          408 :             && !flags.contains(CompactFlags::ForceRepartition)
    3661              :         {
    3662          408 :             debug!(
    3663            0 :                 distance,
    3664            0 :                 threshold = self.repartition_threshold,
    3665            0 :                 "no repartitioning needed"
    3666            0 :             );
    3667          408 :             return Ok((partitioning_guard.0.clone(), partitioning_guard.1));
    3668          196 :         }
    3669              : 
    3670        13300 :         let keyspace = self.collect_keyspace(lsn, ctx).await?;
    3671          196 :         let partitioning = keyspace.partition(partition_size);
    3672          196 : 
    3673          196 :         *partitioning_guard = (partitioning, lsn);
    3674          196 : 
    3675          196 :         Ok((partitioning_guard.0.clone(), partitioning_guard.1))
    3676          604 :     }
    3677              : 
    3678              :     // Is it time to create a new image layer for the given partition?
    3679          522 :     async fn time_for_new_image_layer(&self, partition: &KeySpace, lsn: Lsn) -> bool {
    3680          522 :         let last = self.last_image_layer_creation_check_at.load();
    3681          522 :         if lsn != Lsn(0) {
    3682          522 :             let distance = lsn
    3683          522 :                 .checked_sub(last)
    3684          522 :                 .expect("Attempt to compact with LSN going backwards");
    3685          522 : 
    3686          522 :             let min_distance = self.get_image_layer_creation_check_threshold() as u64
    3687          522 :                 * self.get_checkpoint_distance();
    3688          522 : 
    3689          522 :             // Skip the expensive delta layer counting below if we've not ingested
    3690          522 :             // sufficient WAL since the last check.
    3691          522 :             if distance.0 < min_distance {
    3692          520 :                 return false;
    3693            2 :             }
    3694            0 :         }
    3695              : 
    3696            2 :         self.last_image_layer_creation_check_at.store(lsn);
    3697            2 : 
    3698            2 :         let threshold = self.get_image_creation_threshold();
    3699              : 
    3700            2 :         let guard = self.layers.read().await;
    3701            2 :         let layers = guard.layer_map();
    3702            2 : 
    3703            2 :         let mut max_deltas = 0;
    3704            4 :         for part_range in &partition.ranges {
    3705            2 :             let image_coverage = layers.image_coverage(part_range, lsn);
    3706            4 :             for (img_range, last_img) in image_coverage {
    3707            2 :                 let img_lsn = if let Some(last_img) = last_img {
    3708            0 :                     last_img.get_lsn_range().end
    3709              :                 } else {
    3710            2 :                     Lsn(0)
    3711              :                 };
    3712              :                 // Let's consider an example:
    3713              :                 //
    3714              :                 // delta layer with LSN range 71-81
    3715              :                 // delta layer with LSN range 81-91
    3716              :                 // delta layer with LSN range 91-101
    3717              :                 // image layer at LSN 100
    3718              :                 //
    3719              :                 // If 'lsn' is still 100, i.e. no new WAL has been processed since the last image layer,
    3720              :                 // there's no need to create a new one. We check this case explicitly, to avoid passing
    3721              :                 // a bogus range to count_deltas below, with start > end. It's even possible that there
    3722              :                 // are some delta layers *later* than current 'lsn', if more WAL was processed and flushed
    3723              :                 // after we read last_record_lsn, which is passed here in the 'lsn' argument.
    3724            2 :                 if img_lsn < lsn {
    3725            2 :                     let num_deltas =
    3726            2 :                         layers.count_deltas(&img_range, &(img_lsn..lsn), Some(threshold));
    3727            2 : 
    3728            2 :                     max_deltas = max_deltas.max(num_deltas);
    3729            2 :                     if num_deltas >= threshold {
    3730            0 :                         debug!(
    3731            0 :                             "key range {}-{}, has {} deltas on this timeline in LSN range {}..{}",
    3732            0 :                             img_range.start, img_range.end, num_deltas, img_lsn, lsn
    3733            0 :                         );
    3734            0 :                         return true;
    3735            2 :                     }
    3736            0 :                 }
    3737              :             }
    3738              :         }
    3739              : 
    3740            2 :         debug!(
    3741            0 :             max_deltas,
    3742            0 :             "none of the partitioned ranges had >= {threshold} deltas"
    3743            0 :         );
    3744            2 :         false
    3745          522 :     }
    3746              : 
    3747         1208 :     #[tracing::instrument(skip_all, fields(%lsn, %force))]
    3748              :     async fn create_image_layers(
    3749              :         self: &Arc<Timeline>,
    3750              :         partitioning: &KeyPartitioning,
    3751              :         lsn: Lsn,
    3752              :         force: bool,
    3753              :         ctx: &RequestContext,
    3754              :     ) -> Result<Vec<ResidentLayer>, CreateImageLayersError> {
    3755              :         let timer = self.metrics.create_images_time_histo.start_timer();
    3756              :         let mut image_layers = Vec::new();
    3757              : 
    3758              :         // We need to avoid holes between generated image layers.
    3759              :         // Otherwise LayerMap::image_layer_exists will return false if key range of some layer is covered by more than one
    3760              :         // image layer with hole between them. In this case such layer can not be utilized by GC.
    3761              :         //
    3762              :         // How such hole between partitions can appear?
    3763              :         // if we have relation with relid=1 and size 100 and relation with relid=2 with size 200 then result of
    3764              :         // KeySpace::partition may contain partitions <100000000..100000099> and <200000000..200000199>.
    3765              :         // If there is delta layer <100000000..300000000> then it never be garbage collected because
    3766              :         // image layers  <100000000..100000099> and <200000000..200000199> are not completely covering it.
    3767              :         let mut start = Key::MIN;
    3768              : 
    3769              :         for partition in partitioning.parts.iter() {
    3770              :             let img_range = start..partition.ranges.last().unwrap().end;
    3771              :             if !force && !self.time_for_new_image_layer(partition, lsn).await {
    3772              :                 start = img_range.end;
    3773              :                 continue;
    3774              :             }
    3775              : 
    3776              :             let mut image_layer_writer = ImageLayerWriter::new(
    3777              :                 self.conf,
    3778              :                 self.timeline_id,
    3779              :                 self.tenant_shard_id,
    3780              :                 &img_range,
    3781              :                 lsn,
    3782              :             )
    3783              :             .await?;
    3784              : 
    3785            0 :             fail_point!("image-layer-writer-fail-before-finish", |_| {
    3786            0 :                 Err(CreateImageLayersError::Other(anyhow::anyhow!(
    3787            0 :                     "failpoint image-layer-writer-fail-before-finish"
    3788            0 :                 )))
    3789            0 :             });
    3790              : 
    3791              :             let mut wrote_keys = false;
    3792              : 
    3793              :             let mut key_request_accum = KeySpaceAccum::new();
    3794              :             for range in &partition.ranges {
    3795              :                 let mut key = range.start;
    3796              :                 while key < range.end {
    3797              :                     // Decide whether to retain this key: usually we do, but sharded tenants may
    3798              :                     // need to drop keys that don't belong to them.  If we retain the key, add it
    3799              :                     // to `key_request_accum` for later issuing a vectored get
    3800              :                     if self.shard_identity.is_key_disposable(&key) {
    3801            0 :                         debug!(
    3802            0 :                             "Dropping key {} during compaction (it belongs on shard {:?})",
    3803            0 :                             key,
    3804            0 :                             self.shard_identity.get_shard_number(&key)
    3805            0 :                         );
    3806              :                     } else {
    3807              :                         key_request_accum.add_key(key);
    3808              :                     }
    3809              : 
    3810              :                     let last_key_in_range = key.next() == range.end;
    3811              :                     key = key.next();
    3812              : 
    3813              :                     // Maybe flush `key_rest_accum`
    3814              :                     if key_request_accum.size() >= Timeline::MAX_GET_VECTORED_KEYS
    3815              :                         || last_key_in_range
    3816              :                     {
    3817              :                         let results = self
    3818              :                             .get_vectored(key_request_accum.consume_keyspace(), lsn, ctx)
    3819              :                             .await?;
    3820              : 
    3821              :                         for (img_key, img) in results {
    3822              :                             let img = match img {
    3823              :                                 Ok(img) => img,
    3824              :                                 Err(err) => {
    3825              :                                     // If we fail to reconstruct a VM or FSM page, we can zero the
    3826              :                                     // page without losing any actual user data. That seems better
    3827              :                                     // than failing repeatedly and getting stuck.
    3828              :                                     //
    3829              :                                     // We had a bug at one point, where we truncated the FSM and VM
    3830              :                                     // in the pageserver, but the Postgres didn't know about that
    3831              :                                     // and continued to generate incremental WAL records for pages
    3832              :                                     // that didn't exist in the pageserver. Trying to replay those
    3833              :                                     // WAL records failed to find the previous image of the page.
    3834              :                                     // This special case allows us to recover from that situation.
    3835              :                                     // See https://github.com/neondatabase/neon/issues/2601.
    3836              :                                     //
    3837              :                                     // Unfortunately we cannot do this for the main fork, or for
    3838              :                                     // any metadata keys, keys, as that would lead to actual data
    3839              :                                     // loss.
    3840              :                                     if is_rel_fsm_block_key(img_key) || is_rel_vm_block_key(img_key)
    3841              :                                     {
    3842            0 :                                         warn!("could not reconstruct FSM or VM key {img_key}, filling with zeros: {err:?}");
    3843              :                                         ZERO_PAGE.clone()
    3844              :                                     } else {
    3845              :                                         return Err(CreateImageLayersError::PageReconstructError(
    3846              :                                             err,
    3847              :                                         ));
    3848              :                                     }
    3849              :                                 }
    3850              :                             };
    3851              : 
    3852              :                             // Write all the keys we just read into our new image layer.
    3853              :                             image_layer_writer.put_image(img_key, img).await?;
    3854              :                             wrote_keys = true;
    3855              :                         }
    3856              :                     }
    3857              :                 }
    3858              :             }
    3859              : 
    3860              :             if wrote_keys {
    3861              :                 // Normal path: we have written some data into the new image layer for this
    3862              :                 // partition, so flush it to disk.
    3863              :                 start = img_range.end;
    3864              :                 let image_layer = image_layer_writer.finish(self).await?;
    3865              :                 image_layers.push(image_layer);
    3866              :             } else {
    3867              :                 // Special case: the image layer may be empty if this is a sharded tenant and the
    3868              :                 // partition does not cover any keys owned by this shard.  In this case, to ensure
    3869              :                 // we don't leave gaps between image layers, leave `start` where it is, so that the next
    3870              :                 // layer we write will cover the key range that we just scanned.
    3871            0 :                 tracing::debug!("no data in range {}-{}", img_range.start, img_range.end);
    3872              :             }
    3873              :         }
    3874              : 
    3875              :         // The writer.finish() above already did the fsync of the inodes.
    3876              :         // We just need to fsync the directory in which these inodes are linked,
    3877              :         // which we know to be the timeline directory.
    3878              :         if !image_layers.is_empty() {
    3879              :             // We use fatal_err() below because the after writer.finish() returns with success,
    3880              :             // the in-memory state of the filesystem already has the layer file in its final place,
    3881              :             // and subsequent pageserver code could think it's durable while it really isn't.
    3882              :             let timeline_dir = VirtualFile::open(
    3883              :                 &self
    3884              :                     .conf
    3885              :                     .timeline_path(&self.tenant_shard_id, &self.timeline_id),
    3886              :             )
    3887              :             .await
    3888              :             .fatal_err("VirtualFile::open for timeline dir fsync");
    3889              :             timeline_dir
    3890              :                 .sync_all()
    3891              :                 .await
    3892              :                 .fatal_err("VirtualFile::sync_all timeline dir");
    3893              :         }
    3894              : 
    3895              :         let mut guard = self.layers.write().await;
    3896              : 
    3897              :         // FIXME: we could add the images to be uploaded *before* returning from here, but right
    3898              :         // now they are being scheduled outside of write lock
    3899              :         guard.track_new_image_layers(&image_layers, &self.metrics);
    3900              :         drop_wlock(guard);
    3901              :         timer.stop_and_record();
    3902              : 
    3903              :         Ok(image_layers)
    3904              :     }
    3905              : 
    3906              :     /// Wait until the background initial logical size calculation is complete, or
    3907              :     /// this Timeline is shut down.  Calling this function will cause the initial
    3908              :     /// logical size calculation to skip waiting for the background jobs barrier.
    3909            0 :     pub(crate) async fn await_initial_logical_size(self: Arc<Self>) {
    3910            0 :         if let Some(await_bg_cancel) = self
    3911            0 :             .current_logical_size
    3912            0 :             .cancel_wait_for_background_loop_concurrency_limit_semaphore
    3913            0 :             .get()
    3914            0 :         {
    3915            0 :             await_bg_cancel.cancel();
    3916            0 :         } else {
    3917              :             // We should not wait if we were not able to explicitly instruct
    3918              :             // the logical size cancellation to skip the concurrency limit semaphore.
    3919              :             // TODO: this is an unexpected case.  We should restructure so that it
    3920              :             // can't happen.
    3921            0 :             tracing::info!(
    3922            0 :                 "await_initial_logical_size: can't get semaphore cancel token, skipping"
    3923            0 :             );
    3924              :         }
    3925              : 
    3926            0 :         tokio::select!(
    3927            0 :             _ = self.current_logical_size.initialized.acquire() => {},
    3928            0 :             _ = self.cancel.cancelled() => {}
    3929            0 :         )
    3930            0 :     }
    3931              : }
    3932              : 
    3933              : /// Top-level failure to compact.
    3934            0 : #[derive(Debug, thiserror::Error)]
    3935              : pub(crate) enum CompactionError {
    3936              :     #[error("The timeline or pageserver is shutting down")]
    3937              :     ShuttingDown,
    3938              :     /// Compaction cannot be done right now; page reconstruction and so on.
    3939              :     #[error(transparent)]
    3940              :     Other(#[from] anyhow::Error),
    3941              : }
    3942              : 
    3943              : impl From<CollectKeySpaceError> for CompactionError {
    3944            0 :     fn from(err: CollectKeySpaceError) -> Self {
    3945            0 :         match err {
    3946              :             CollectKeySpaceError::Cancelled
    3947              :             | CollectKeySpaceError::PageRead(PageReconstructError::Cancelled) => {
    3948            0 :                 CompactionError::ShuttingDown
    3949              :             }
    3950            0 :             e => CompactionError::Other(e.into()),
    3951              :         }
    3952            0 :     }
    3953              : }
    3954              : 
    3955              : #[serde_as]
    3956          294 : #[derive(serde::Serialize)]
    3957              : struct RecordedDuration(#[serde_as(as = "serde_with::DurationMicroSeconds")] Duration);
    3958              : 
    3959              : #[derive(Default)]
    3960              : enum DurationRecorder {
    3961              :     #[default]
    3962              :     NotStarted,
    3963              :     Recorded(RecordedDuration, tokio::time::Instant),
    3964              : }
    3965              : 
    3966              : impl DurationRecorder {
    3967          720 :     fn till_now(&self) -> DurationRecorder {
    3968          720 :         match self {
    3969              :             DurationRecorder::NotStarted => {
    3970            0 :                 panic!("must only call on recorded measurements")
    3971              :             }
    3972          720 :             DurationRecorder::Recorded(_, ended) => {
    3973          720 :                 let now = tokio::time::Instant::now();
    3974          720 :                 DurationRecorder::Recorded(RecordedDuration(now - *ended), now)
    3975          720 :             }
    3976          720 :         }
    3977          720 :     }
    3978          294 :     fn into_recorded(self) -> Option<RecordedDuration> {
    3979          294 :         match self {
    3980            0 :             DurationRecorder::NotStarted => None,
    3981          294 :             DurationRecorder::Recorded(recorded, _) => Some(recorded),
    3982              :         }
    3983          294 :     }
    3984              : }
    3985              : 
    3986              : impl Timeline {
    3987           42 :     async fn finish_compact_batch(
    3988           42 :         self: &Arc<Self>,
    3989           42 :         new_deltas: &[ResidentLayer],
    3990           42 :         new_images: &[ResidentLayer],
    3991           42 :         layers_to_remove: &[Layer],
    3992           42 :     ) -> anyhow::Result<()> {
    3993           42 :         let mut guard = self.layers.write().await;
    3994              : 
    3995           42 :         let mut duplicated_layers = HashSet::new();
    3996           42 : 
    3997           42 :         let mut insert_layers = Vec::with_capacity(new_deltas.len());
    3998              : 
    3999          284 :         for l in new_deltas {
    4000          242 :             if guard.contains(l.as_ref()) {
    4001              :                 // expected in tests
    4002            0 :                 tracing::error!(layer=%l, "duplicated L1 layer");
    4003              : 
    4004              :                 // good ways to cause a duplicate: we repeatedly error after taking the writelock
    4005              :                 // `guard`  on self.layers. as of writing this, there are no error returns except
    4006              :                 // for compact_level0_phase1 creating an L0, which does not happen in practice
    4007              :                 // because we have not implemented L0 => L0 compaction.
    4008            0 :                 duplicated_layers.insert(l.layer_desc().key());
    4009          242 :             } else if LayerMap::is_l0(l.layer_desc()) {
    4010            0 :                 bail!("compaction generates a L0 layer file as output, which will cause infinite compaction.");
    4011          242 :             } else {
    4012          242 :                 insert_layers.push(l.clone());
    4013          242 :             }
    4014              :         }
    4015              : 
    4016              :         // only remove those inputs which were not outputs
    4017           42 :         let remove_layers: Vec<Layer> = layers_to_remove
    4018           42 :             .iter()
    4019          442 :             .filter(|l| !duplicated_layers.contains(&l.layer_desc().key()))
    4020           42 :             .cloned()
    4021           42 :             .collect();
    4022           42 : 
    4023           42 :         if !new_images.is_empty() {
    4024            0 :             guard.track_new_image_layers(new_images, &self.metrics);
    4025           42 :         }
    4026              : 
    4027              :         // deletion will happen later, the layer file manager calls garbage_collect_on_drop
    4028           42 :         guard.finish_compact_l0(&remove_layers, &insert_layers, &self.metrics);
    4029              : 
    4030           42 :         if let Some(remote_client) = self.remote_client.as_ref() {
    4031           42 :             remote_client.schedule_compaction_update(&remove_layers, new_deltas)?;
    4032            0 :         }
    4033              : 
    4034           42 :         drop_wlock(guard);
    4035           42 : 
    4036           42 :         Ok(())
    4037           42 :     }
    4038              : 
    4039              :     /// Schedules the uploads of the given image layers
    4040          510 :     fn upload_new_image_layers(
    4041          510 :         self: &Arc<Self>,
    4042          510 :         new_images: impl IntoIterator<Item = ResidentLayer>,
    4043          510 :     ) -> anyhow::Result<()> {
    4044          510 :         let Some(remote_client) = &self.remote_client else {
    4045            0 :             return Ok(());
    4046              :         };
    4047          510 :         for layer in new_images {
    4048            0 :             remote_client.schedule_layer_file_upload(layer)?;
    4049              :         }
    4050              :         // should any new image layer been created, not uploading index_part will
    4051              :         // result in a mismatch between remote_physical_size and layermap calculated
    4052              :         // size, which will fail some tests, but should not be an issue otherwise.
    4053          510 :         remote_client.schedule_index_upload_for_file_changes()?;
    4054          510 :         Ok(())
    4055          510 :     }
    4056              : 
    4057              :     /// Update information about which layer files need to be retained on
    4058              :     /// garbage collection. This is separate from actually performing the GC,
    4059              :     /// and is updated more frequently, so that compaction can remove obsolete
    4060              :     /// page versions more aggressively.
    4061              :     ///
    4062              :     /// TODO: that's wishful thinking, compaction doesn't actually do that
    4063              :     /// currently.
    4064              :     ///
    4065              :     /// The caller specifies how much history is needed with the 3 arguments:
    4066              :     ///
    4067              :     /// retain_lsns: keep a version of each page at these LSNs
    4068              :     /// cutoff_horizon: also keep everything newer than this LSN
    4069              :     /// pitr: the time duration required to keep data for PITR
    4070              :     ///
    4071              :     /// The 'retain_lsns' list is currently used to prevent removing files that
    4072              :     /// are needed by child timelines. In the future, the user might be able to
    4073              :     /// name additional points in time to retain. The caller is responsible for
    4074              :     /// collecting that information.
    4075              :     ///
    4076              :     /// The 'cutoff_horizon' point is used to retain recent versions that might still be
    4077              :     /// needed by read-only nodes. (As of this writing, the caller just passes
    4078              :     /// the latest LSN subtracted by a constant, and doesn't do anything smart
    4079              :     /// to figure out what read-only nodes might actually need.)
    4080              :     ///
    4081              :     /// The 'pitr' duration is used to calculate a 'pitr_cutoff', which can be used to determine
    4082              :     /// whether a record is needed for PITR.
    4083              :     ///
    4084              :     /// NOTE: This function holds a short-lived lock to protect the 'gc_info'
    4085              :     /// field, so that the three values passed as argument are stored
    4086              :     /// atomically. But the caller is responsible for ensuring that no new
    4087              :     /// branches are created that would need to be included in 'retain_lsns',
    4088              :     /// for example. The caller should hold `Tenant::gc_cs` lock to ensure
    4089              :     /// that.
    4090              :     ///
    4091         1016 :     #[instrument(skip_all, fields(timeline_id=%self.timeline_id))]
    4092              :     pub(super) async fn update_gc_info(
    4093              :         &self,
    4094              :         retain_lsns: Vec<Lsn>,
    4095              :         cutoff_horizon: Lsn,
    4096              :         pitr: Duration,
    4097              :         cancel: &CancellationToken,
    4098              :         ctx: &RequestContext,
    4099              :     ) -> anyhow::Result<()> {
    4100              :         // First, calculate pitr_cutoff_timestamp and then convert it to LSN.
    4101              :         //
    4102              :         // Some unit tests depend on garbage-collection working even when
    4103              :         // CLOG data is missing, so that find_lsn_for_timestamp() doesn't
    4104              :         // work, so avoid calling it altogether if time-based retention is not
    4105              :         // configured. It would be pointless anyway.
    4106              :         let pitr_cutoff = if pitr != Duration::ZERO {
    4107              :             let now = SystemTime::now();
    4108              :             if let Some(pitr_cutoff_timestamp) = now.checked_sub(pitr) {
    4109              :                 let pitr_timestamp = to_pg_timestamp(pitr_cutoff_timestamp);
    4110              : 
    4111              :                 match self
    4112              :                     .find_lsn_for_timestamp(pitr_timestamp, cancel, ctx)
    4113              :                     .await?
    4114              :                 {
    4115              :                     LsnForTimestamp::Present(lsn) => lsn,
    4116              :                     LsnForTimestamp::Future(lsn) => {
    4117              :                         // The timestamp is in the future. That sounds impossible,
    4118              :                         // but what it really means is that there hasn't been
    4119              :                         // any commits since the cutoff timestamp.
    4120              :                         //
    4121              :                         // In this case we should use the LSN of the most recent commit,
    4122              :                         // which is implicitly the last LSN in the log.
    4123            0 :                         debug!("future({})", lsn);
    4124              :                         self.get_last_record_lsn()
    4125              :                     }
    4126              :                     LsnForTimestamp::Past(lsn) => {
    4127            0 :                         debug!("past({})", lsn);
    4128              :                         // conservative, safe default is to remove nothing, when we
    4129              :                         // have no commit timestamp data available
    4130              :                         *self.get_latest_gc_cutoff_lsn()
    4131              :                     }
    4132              :                     LsnForTimestamp::NoData(lsn) => {
    4133            0 :                         debug!("nodata({})", lsn);
    4134              :                         // conservative, safe default is to remove nothing, when we
    4135              :                         // have no commit timestamp data available
    4136              :                         *self.get_latest_gc_cutoff_lsn()
    4137              :                     }
    4138              :                 }
    4139              :             } else {
    4140              :                 // If we don't have enough data to convert to LSN,
    4141              :                 // play safe and don't remove any layers.
    4142              :                 *self.get_latest_gc_cutoff_lsn()
    4143              :             }
    4144              :         } else {
    4145              :             // No time-based retention was configured. Set time-based cutoff to
    4146              :             // same as LSN based.
    4147              :             cutoff_horizon
    4148              :         };
    4149              : 
    4150              :         // Grab the lock and update the values
    4151              :         *self.gc_info.write().unwrap() = GcInfo {
    4152              :             retain_lsns,
    4153              :             horizon_cutoff: cutoff_horizon,
    4154              :             pitr_cutoff,
    4155              :         };
    4156              : 
    4157              :         Ok(())
    4158              :     }
    4159              : 
    4160              :     /// Garbage collect layer files on a timeline that are no longer needed.
    4161              :     ///
    4162              :     /// Currently, we don't make any attempt at removing unneeded page versions
    4163              :     /// within a layer file. We can only remove the whole file if it's fully
    4164              :     /// obsolete.
    4165          508 :     pub(super) async fn gc(&self) -> anyhow::Result<GcResult> {
    4166          508 :         // this is most likely the background tasks, but it might be the spawned task from
    4167          508 :         // immediate_gc
    4168          508 :         let cancel = crate::task_mgr::shutdown_token();
    4169          508 :         let _g = tokio::select! {
    4170          506 :             guard = self.gc_lock.lock() => guard,
    4171              :             _ = self.cancel.cancelled() => return Ok(GcResult::default()),
    4172              :             _ = cancel.cancelled() => return Ok(GcResult::default()),
    4173              :         };
    4174          506 :         let timer = self.metrics.garbage_collect_histo.start_timer();
    4175              : 
    4176            0 :         fail_point!("before-timeline-gc");
    4177              : 
    4178              :         // Is the timeline being deleted?
    4179          506 :         if self.is_stopping() {
    4180            0 :             anyhow::bail!("timeline is Stopping");
    4181          506 :         }
    4182          506 : 
    4183          506 :         let (horizon_cutoff, pitr_cutoff, retain_lsns) = {
    4184          506 :             let gc_info = self.gc_info.read().unwrap();
    4185          506 : 
    4186          506 :             let horizon_cutoff = min(gc_info.horizon_cutoff, self.get_disk_consistent_lsn());
    4187          506 :             let pitr_cutoff = gc_info.pitr_cutoff;
    4188          506 :             let retain_lsns = gc_info.retain_lsns.clone();
    4189          506 :             (horizon_cutoff, pitr_cutoff, retain_lsns)
    4190          506 :         };
    4191          506 : 
    4192          506 :         let new_gc_cutoff = Lsn::min(horizon_cutoff, pitr_cutoff);
    4193              : 
    4194          506 :         let res = self
    4195          506 :             .gc_timeline(horizon_cutoff, pitr_cutoff, retain_lsns, new_gc_cutoff)
    4196          506 :             .instrument(
    4197          506 :                 info_span!("gc_timeline", timeline_id = %self.timeline_id, cutoff = %new_gc_cutoff),
    4198              :             )
    4199            0 :             .await?;
    4200              : 
    4201              :         // only record successes
    4202          506 :         timer.stop_and_record();
    4203          506 : 
    4204          506 :         Ok(res)
    4205          508 :     }
    4206              : 
    4207          506 :     async fn gc_timeline(
    4208          506 :         &self,
    4209          506 :         horizon_cutoff: Lsn,
    4210          506 :         pitr_cutoff: Lsn,
    4211          506 :         retain_lsns: Vec<Lsn>,
    4212          506 :         new_gc_cutoff: Lsn,
    4213          506 :     ) -> anyhow::Result<GcResult> {
    4214          506 :         let now = SystemTime::now();
    4215          506 :         let mut result: GcResult = GcResult::default();
    4216          506 : 
    4217          506 :         // Nothing to GC. Return early.
    4218          506 :         let latest_gc_cutoff = *self.get_latest_gc_cutoff_lsn();
    4219          506 :         if latest_gc_cutoff >= new_gc_cutoff {
    4220            0 :             info!(
    4221            0 :                 "Nothing to GC: new_gc_cutoff_lsn {new_gc_cutoff}, latest_gc_cutoff_lsn {latest_gc_cutoff}",
    4222            0 :             );
    4223            0 :             return Ok(result);
    4224          506 :         }
    4225              : 
    4226              :         // We need to ensure that no one tries to read page versions or create
    4227              :         // branches at a point before latest_gc_cutoff_lsn. See branch_timeline()
    4228              :         // for details. This will block until the old value is no longer in use.
    4229              :         //
    4230              :         // The GC cutoff should only ever move forwards.
    4231          506 :         let waitlist = {
    4232          506 :             let write_guard = self.latest_gc_cutoff_lsn.lock_for_write();
    4233          506 :             ensure!(
    4234          506 :                 *write_guard <= new_gc_cutoff,
    4235            0 :                 "Cannot move GC cutoff LSN backwards (was {}, new {})",
    4236            0 :                 *write_guard,
    4237              :                 new_gc_cutoff
    4238              :             );
    4239          506 :             write_guard.store_and_unlock(new_gc_cutoff)
    4240          506 :         };
    4241          506 :         waitlist.wait().await;
    4242              : 
    4243          506 :         info!("GC starting");
    4244              : 
    4245          506 :         debug!("retain_lsns: {:?}", retain_lsns);
    4246              : 
    4247          506 :         let mut layers_to_remove = Vec::new();
    4248              : 
    4249              :         // Scan all layers in the timeline (remote or on-disk).
    4250              :         //
    4251              :         // Garbage collect the layer if all conditions are satisfied:
    4252              :         // 1. it is older than cutoff LSN;
    4253              :         // 2. it is older than PITR interval;
    4254              :         // 3. it doesn't need to be retained for 'retain_lsns';
    4255              :         // 4. newer on-disk image layers cover the layer's whole key range
    4256              :         //
    4257              :         // TODO holding a write lock is too agressive and avoidable
    4258          506 :         let mut guard = self.layers.write().await;
    4259          506 :         let layers = guard.layer_map();
    4260         3158 :         'outer: for l in layers.iter_historic_layers() {
    4261         3158 :             result.layers_total += 1;
    4262         3158 : 
    4263         3158 :             // 1. Is it newer than GC horizon cutoff point?
    4264         3158 :             if l.get_lsn_range().end > horizon_cutoff {
    4265          506 :                 debug!(
    4266            0 :                     "keeping {} because it's newer than horizon_cutoff {}",
    4267            0 :                     l.filename(),
    4268            0 :                     horizon_cutoff,
    4269            0 :                 );
    4270          506 :                 result.layers_needed_by_cutoff += 1;
    4271          506 :                 continue 'outer;
    4272         2652 :             }
    4273         2652 : 
    4274         2652 :             // 2. It is newer than PiTR cutoff point?
    4275         2652 :             if l.get_lsn_range().end > pitr_cutoff {
    4276            0 :                 debug!(
    4277            0 :                     "keeping {} because it's newer than pitr_cutoff {}",
    4278            0 :                     l.filename(),
    4279            0 :                     pitr_cutoff,
    4280            0 :                 );
    4281            0 :                 result.layers_needed_by_pitr += 1;
    4282            0 :                 continue 'outer;
    4283         2652 :             }
    4284              : 
    4285              :             // 3. Is it needed by a child branch?
    4286              :             // NOTE With that we would keep data that
    4287              :             // might be referenced by child branches forever.
    4288              :             // We can track this in child timeline GC and delete parent layers when
    4289              :             // they are no longer needed. This might be complicated with long inheritance chains.
    4290              :             //
    4291              :             // TODO Vec is not a great choice for `retain_lsns`
    4292         2652 :             for retain_lsn in &retain_lsns {
    4293              :                 // start_lsn is inclusive
    4294            8 :                 if &l.get_lsn_range().start <= retain_lsn {
    4295            8 :                     debug!(
    4296            0 :                         "keeping {} because it's still might be referenced by child branch forked at {} is_dropped: xx is_incremental: {}",
    4297            0 :                         l.filename(),
    4298            0 :                         retain_lsn,
    4299            0 :                         l.is_incremental(),
    4300            0 :                     );
    4301            8 :                     result.layers_needed_by_branches += 1;
    4302            8 :                     continue 'outer;
    4303            0 :                 }
    4304              :             }
    4305              : 
    4306              :             // 4. Is there a later on-disk layer for this relation?
    4307              :             //
    4308              :             // The end-LSN is exclusive, while disk_consistent_lsn is
    4309              :             // inclusive. For example, if disk_consistent_lsn is 100, it is
    4310              :             // OK for a delta layer to have end LSN 101, but if the end LSN
    4311              :             // is 102, then it might not have been fully flushed to disk
    4312              :             // before crash.
    4313              :             //
    4314              :             // For example, imagine that the following layers exist:
    4315              :             //
    4316              :             // 1000      - image (A)
    4317              :             // 1000-2000 - delta (B)
    4318              :             // 2000      - image (C)
    4319              :             // 2000-3000 - delta (D)
    4320              :             // 3000      - image (E)
    4321              :             //
    4322              :             // If GC horizon is at 2500, we can remove layers A and B, but
    4323              :             // we cannot remove C, even though it's older than 2500, because
    4324              :             // the delta layer 2000-3000 depends on it.
    4325         2644 :             if !layers
    4326         2644 :                 .image_layer_exists(&l.get_key_range(), &(l.get_lsn_range().end..new_gc_cutoff))
    4327              :             {
    4328         2644 :                 debug!("keeping {} because it is the latest layer", l.filename());
    4329         2644 :                 result.layers_not_updated += 1;
    4330         2644 :                 continue 'outer;
    4331            0 :             }
    4332            0 : 
    4333            0 :             // We didn't find any reason to keep this file, so remove it.
    4334            0 :             debug!(
    4335            0 :                 "garbage collecting {} is_dropped: xx is_incremental: {}",
    4336            0 :                 l.filename(),
    4337            0 :                 l.is_incremental(),
    4338            0 :             );
    4339            0 :             layers_to_remove.push(l);
    4340              :         }
    4341              : 
    4342          506 :         if !layers_to_remove.is_empty() {
    4343              :             // Persist the new GC cutoff value before we actually remove anything.
    4344              :             // This unconditionally schedules also an index_part.json update, even though, we will
    4345              :             // be doing one a bit later with the unlinked gc'd layers.
    4346            0 :             let disk_consistent_lsn = self.disk_consistent_lsn.load();
    4347            0 :             self.schedule_uploads(disk_consistent_lsn, None)?;
    4348              : 
    4349            0 :             let gc_layers = layers_to_remove
    4350            0 :                 .iter()
    4351            0 :                 .map(|x| guard.get_from_desc(x))
    4352            0 :                 .collect::<Vec<Layer>>();
    4353            0 : 
    4354            0 :             result.layers_removed = gc_layers.len() as u64;
    4355              : 
    4356            0 :             if let Some(remote_client) = self.remote_client.as_ref() {
    4357            0 :                 remote_client.schedule_gc_update(&gc_layers)?;
    4358            0 :             }
    4359              : 
    4360            0 :             guard.finish_gc_timeline(&gc_layers);
    4361            0 : 
    4362            0 :             #[cfg(feature = "testing")]
    4363            0 :             {
    4364            0 :                 result.doomed_layers = gc_layers;
    4365            0 :             }
    4366          506 :         }
    4367              : 
    4368          506 :         info!(
    4369          506 :             "GC completed removing {} layers, cutoff {}",
    4370          506 :             result.layers_removed, new_gc_cutoff
    4371          506 :         );
    4372              : 
    4373          506 :         result.elapsed = now.elapsed()?;
    4374          506 :         Ok(result)
    4375          506 :     }
    4376              : 
    4377              :     /// Reconstruct a value, using the given base image and WAL records in 'data'.
    4378       503085 :     async fn reconstruct_value(
    4379       503085 :         &self,
    4380       503085 :         key: Key,
    4381       503085 :         request_lsn: Lsn,
    4382       503085 :         mut data: ValueReconstructState,
    4383       503085 :     ) -> Result<Bytes, PageReconstructError> {
    4384       503085 :         // Perform WAL redo if needed
    4385       503085 :         data.records.reverse();
    4386       503085 : 
    4387       503085 :         // If we have a page image, and no WAL, we're all set
    4388       503085 :         if data.records.is_empty() {
    4389       503079 :             if let Some((img_lsn, img)) = &data.img {
    4390       503079 :                 trace!(
    4391            0 :                     "found page image for key {} at {}, no WAL redo required, req LSN {}",
    4392            0 :                     key,
    4393            0 :                     img_lsn,
    4394            0 :                     request_lsn,
    4395            0 :                 );
    4396       503079 :                 Ok(img.clone())
    4397              :             } else {
    4398            0 :                 Err(PageReconstructError::from(anyhow!(
    4399            0 :                     "base image for {key} at {request_lsn} not found"
    4400            0 :                 )))
    4401              :             }
    4402              :         } else {
    4403              :             // We need to do WAL redo.
    4404              :             //
    4405              :             // If we don't have a base image, then the oldest WAL record better initialize
    4406              :             // the page
    4407            6 :             if data.img.is_none() && !data.records.first().unwrap().1.will_init() {
    4408            0 :                 Err(PageReconstructError::from(anyhow!(
    4409            0 :                     "Base image for {} at {} not found, but got {} WAL records",
    4410            0 :                     key,
    4411            0 :                     request_lsn,
    4412            0 :                     data.records.len()
    4413            0 :                 )))
    4414              :             } else {
    4415            6 :                 if data.img.is_some() {
    4416            6 :                     trace!(
    4417            0 :                         "found {} WAL records and a base image for {} at {}, performing WAL redo",
    4418            0 :                         data.records.len(),
    4419            0 :                         key,
    4420            0 :                         request_lsn
    4421            0 :                     );
    4422              :                 } else {
    4423            0 :                     trace!("found {} WAL records that will init the page for {} at {}, performing WAL redo", data.records.len(), key, request_lsn);
    4424              :                 };
    4425              : 
    4426            6 :                 let last_rec_lsn = data.records.last().unwrap().0;
    4427              : 
    4428            6 :                 let img = match self
    4429            6 :                     .walredo_mgr
    4430            6 :                     .as_ref()
    4431            6 :                     .context("timeline has no walredo manager")
    4432            6 :                     .map_err(PageReconstructError::WalRedo)?
    4433            6 :                     .request_redo(key, request_lsn, data.img, data.records, self.pg_version)
    4434            0 :                     .await
    4435            6 :                     .context("reconstruct a page image")
    4436              :                 {
    4437            6 :                     Ok(img) => img,
    4438            0 :                     Err(e) => return Err(PageReconstructError::WalRedo(e)),
    4439              :                 };
    4440              : 
    4441            6 :                 if img.len() == page_cache::PAGE_SZ {
    4442            0 :                     let cache = page_cache::get();
    4443            0 :                     if let Err(e) = cache
    4444            0 :                         .memorize_materialized_page(
    4445            0 :                             self.tenant_shard_id,
    4446            0 :                             self.timeline_id,
    4447            0 :                             key,
    4448            0 :                             last_rec_lsn,
    4449            0 :                             &img,
    4450            0 :                         )
    4451            0 :                         .await
    4452            0 :                         .context("Materialized page memoization failed")
    4453              :                     {
    4454            0 :                         return Err(PageReconstructError::from(e));
    4455            0 :                     }
    4456            6 :                 }
    4457              : 
    4458            6 :                 Ok(img)
    4459              :             }
    4460              :         }
    4461       503085 :     }
    4462              : 
    4463            0 :     pub(crate) async fn spawn_download_all_remote_layers(
    4464            0 :         self: Arc<Self>,
    4465            0 :         request: DownloadRemoteLayersTaskSpawnRequest,
    4466            0 :     ) -> Result<DownloadRemoteLayersTaskInfo, DownloadRemoteLayersTaskInfo> {
    4467            0 :         use pageserver_api::models::DownloadRemoteLayersTaskState;
    4468            0 : 
    4469            0 :         // this is not really needed anymore; it has tests which really check the return value from
    4470            0 :         // http api. it would be better not to maintain this anymore.
    4471            0 : 
    4472            0 :         let mut status_guard = self.download_all_remote_layers_task_info.write().unwrap();
    4473            0 :         if let Some(st) = &*status_guard {
    4474            0 :             match &st.state {
    4475              :                 DownloadRemoteLayersTaskState::Running => {
    4476            0 :                     return Err(st.clone());
    4477              :                 }
    4478              :                 DownloadRemoteLayersTaskState::ShutDown
    4479            0 :                 | DownloadRemoteLayersTaskState::Completed => {
    4480            0 :                     *status_guard = None;
    4481            0 :                 }
    4482              :             }
    4483            0 :         }
    4484              : 
    4485            0 :         let self_clone = Arc::clone(&self);
    4486            0 :         let task_id = task_mgr::spawn(
    4487            0 :             task_mgr::BACKGROUND_RUNTIME.handle(),
    4488            0 :             task_mgr::TaskKind::DownloadAllRemoteLayers,
    4489            0 :             Some(self.tenant_shard_id),
    4490            0 :             Some(self.timeline_id),
    4491            0 :             "download all remote layers task",
    4492              :             false,
    4493            0 :             async move {
    4494            0 :                 self_clone.download_all_remote_layers(request).await;
    4495            0 :                 let mut status_guard = self_clone.download_all_remote_layers_task_info.write().unwrap();
    4496            0 :                  match &mut *status_guard {
    4497              :                     None => {
    4498            0 :                         warn!("tasks status is supposed to be Some(), since we are running");
    4499              :                     }
    4500            0 :                     Some(st) => {
    4501            0 :                         let exp_task_id = format!("{}", task_mgr::current_task_id().unwrap());
    4502            0 :                         if st.task_id != exp_task_id {
    4503            0 :                             warn!("task id changed while we were still running, expecting {} but have {}", exp_task_id, st.task_id);
    4504            0 :                         } else {
    4505            0 :                             st.state = DownloadRemoteLayersTaskState::Completed;
    4506            0 :                         }
    4507              :                     }
    4508              :                 };
    4509            0 :                 Ok(())
    4510            0 :             }
    4511            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))
    4512              :         );
    4513              : 
    4514            0 :         let initial_info = DownloadRemoteLayersTaskInfo {
    4515            0 :             task_id: format!("{task_id}"),
    4516            0 :             state: DownloadRemoteLayersTaskState::Running,
    4517            0 :             total_layer_count: 0,
    4518            0 :             successful_download_count: 0,
    4519            0 :             failed_download_count: 0,
    4520            0 :         };
    4521            0 :         *status_guard = Some(initial_info.clone());
    4522            0 : 
    4523            0 :         Ok(initial_info)
    4524            0 :     }
    4525              : 
    4526            0 :     async fn download_all_remote_layers(
    4527            0 :         self: &Arc<Self>,
    4528            0 :         request: DownloadRemoteLayersTaskSpawnRequest,
    4529            0 :     ) {
    4530              :         use pageserver_api::models::DownloadRemoteLayersTaskState;
    4531              : 
    4532            0 :         let remaining = {
    4533            0 :             let guard = self.layers.read().await;
    4534            0 :             guard
    4535            0 :                 .layer_map()
    4536            0 :                 .iter_historic_layers()
    4537            0 :                 .map(|desc| guard.get_from_desc(&desc))
    4538            0 :                 .collect::<Vec<_>>()
    4539            0 :         };
    4540            0 :         let total_layer_count = remaining.len();
    4541            0 : 
    4542            0 :         macro_rules! lock_status {
    4543            0 :             ($st:ident) => {
    4544            0 :                 let mut st = self.download_all_remote_layers_task_info.write().unwrap();
    4545            0 :                 let st = st
    4546            0 :                     .as_mut()
    4547            0 :                     .expect("this function is only called after the task has been spawned");
    4548            0 :                 assert_eq!(
    4549            0 :                     st.task_id,
    4550            0 :                     format!(
    4551            0 :                         "{}",
    4552            0 :                         task_mgr::current_task_id().expect("we run inside a task_mgr task")
    4553            0 :                     )
    4554            0 :                 );
    4555            0 :                 let $st = st;
    4556            0 :             };
    4557            0 :         }
    4558            0 : 
    4559            0 :         {
    4560            0 :             lock_status!(st);
    4561            0 :             st.total_layer_count = total_layer_count as u64;
    4562            0 :         }
    4563            0 : 
    4564            0 :         let mut remaining = remaining.into_iter();
    4565            0 :         let mut have_remaining = true;
    4566            0 :         let mut js = tokio::task::JoinSet::new();
    4567            0 : 
    4568            0 :         let cancel = task_mgr::shutdown_token();
    4569            0 : 
    4570            0 :         let limit = request.max_concurrent_downloads;
    4571              : 
    4572              :         loop {
    4573            0 :             while js.len() < limit.get() && have_remaining && !cancel.is_cancelled() {
    4574            0 :                 let Some(next) = remaining.next() else {
    4575            0 :                     have_remaining = false;
    4576            0 :                     break;
    4577              :                 };
    4578              : 
    4579            0 :                 let span = tracing::info_span!("download", layer = %next);
    4580              : 
    4581            0 :                 js.spawn(
    4582            0 :                     async move {
    4583            0 :                         let res = next.download().await;
    4584            0 :                         (next, res)
    4585            0 :                     }
    4586            0 :                     .instrument(span),
    4587            0 :                 );
    4588              :             }
    4589              : 
    4590            0 :             while let Some(res) = js.join_next().await {
    4591            0 :                 match res {
    4592              :                     Ok((_, Ok(_))) => {
    4593            0 :                         lock_status!(st);
    4594            0 :                         st.successful_download_count += 1;
    4595              :                     }
    4596            0 :                     Ok((layer, Err(e))) => {
    4597            0 :                         tracing::error!(%layer, "download failed: {e:#}");
    4598            0 :                         lock_status!(st);
    4599            0 :                         st.failed_download_count += 1;
    4600              :                     }
    4601            0 :                     Err(je) if je.is_cancelled() => unreachable!("not used here"),
    4602            0 :                     Err(je) if je.is_panic() => {
    4603            0 :                         lock_status!(st);
    4604            0 :                         st.failed_download_count += 1;
    4605              :                     }
    4606            0 :                     Err(je) => tracing::warn!("unknown joinerror: {je:?}"),
    4607              :                 }
    4608              :             }
    4609              : 
    4610            0 :             if js.is_empty() && (!have_remaining || cancel.is_cancelled()) {
    4611            0 :                 break;
    4612            0 :             }
    4613              :         }
    4614              : 
    4615              :         {
    4616            0 :             lock_status!(st);
    4617            0 :             st.state = DownloadRemoteLayersTaskState::Completed;
    4618            0 :         }
    4619            0 :     }
    4620              : 
    4621            0 :     pub(crate) fn get_download_all_remote_layers_task_info(
    4622            0 :         &self,
    4623            0 :     ) -> Option<DownloadRemoteLayersTaskInfo> {
    4624            0 :         self.download_all_remote_layers_task_info
    4625            0 :             .read()
    4626            0 :             .unwrap()
    4627            0 :             .clone()
    4628            0 :     }
    4629              : }
    4630              : 
    4631              : impl Timeline {
    4632              :     /// Returns non-remote layers for eviction.
    4633            0 :     pub(crate) async fn get_local_layers_for_disk_usage_eviction(&self) -> DiskUsageEvictionInfo {
    4634            0 :         let guard = self.layers.read().await;
    4635            0 :         let mut max_layer_size: Option<u64> = None;
    4636            0 : 
    4637            0 :         let resident_layers = guard
    4638            0 :             .likely_resident_layers()
    4639            0 :             .map(|layer| {
    4640            0 :                 let file_size = layer.layer_desc().file_size;
    4641            0 :                 max_layer_size = max_layer_size.map_or(Some(file_size), |m| Some(m.max(file_size)));
    4642            0 : 
    4643            0 :                 let last_activity_ts = layer.access_stats().latest_activity_or_now();
    4644            0 : 
    4645            0 :                 EvictionCandidate {
    4646            0 :                     layer: layer.into(),
    4647            0 :                     last_activity_ts,
    4648            0 :                     relative_last_activity: finite_f32::FiniteF32::ZERO,
    4649            0 :                 }
    4650            0 :             })
    4651            0 :             .collect();
    4652            0 : 
    4653            0 :         DiskUsageEvictionInfo {
    4654            0 :             max_layer_size,
    4655            0 :             resident_layers,
    4656            0 :         }
    4657            0 :     }
    4658              : 
    4659          966 :     pub(crate) fn get_shard_index(&self) -> ShardIndex {
    4660          966 :         ShardIndex {
    4661          966 :             shard_number: self.tenant_shard_id.shard_number,
    4662          966 :             shard_count: self.tenant_shard_id.shard_count,
    4663          966 :         }
    4664          966 :     }
    4665              : }
    4666              : 
    4667              : type TraversalPathItem = (
    4668              :     ValueReconstructResult,
    4669              :     Lsn,
    4670              :     Box<dyn Send + FnOnce() -> TraversalId>,
    4671              : );
    4672              : 
    4673              : /// Helper function for get_reconstruct_data() to add the path of layers traversed
    4674              : /// to an error, as anyhow context information.
    4675          108 : fn layer_traversal_error(msg: String, path: Vec<TraversalPathItem>) -> PageReconstructError {
    4676          108 :     // We want the original 'msg' to be the outermost context. The outermost context
    4677          108 :     // is the most high-level information, which also gets propagated to the client.
    4678          108 :     let mut msg_iter = path
    4679          108 :         .into_iter()
    4680          150 :         .map(|(r, c, l)| {
    4681          150 :             format!(
    4682          150 :                 "layer traversal: result {:?}, cont_lsn {}, layer: {}",
    4683          150 :                 r,
    4684          150 :                 c,
    4685          150 :                 l(),
    4686          150 :             )
    4687          150 :         })
    4688          108 :         .chain(std::iter::once(msg));
    4689          108 :     // Construct initial message from the first traversed layer
    4690          108 :     let err = anyhow!(msg_iter.next().unwrap());
    4691          108 : 
    4692          108 :     // Append all subsequent traversals, and the error message 'msg', as contexts.
    4693          150 :     let msg = msg_iter.fold(err, |err, msg| err.context(msg));
    4694          108 :     PageReconstructError::from(msg)
    4695          108 : }
    4696              : 
    4697              : struct TimelineWriterState {
    4698              :     open_layer: Arc<InMemoryLayer>,
    4699              :     current_size: u64,
    4700              :     // Previous Lsn which passed through
    4701              :     prev_lsn: Option<Lsn>,
    4702              :     // Largest Lsn which passed through the current writer
    4703              :     max_lsn: Option<Lsn>,
    4704              :     // Cached details of the last freeze. Avoids going trough the atomic/lock on every put.
    4705              :     cached_last_freeze_at: Lsn,
    4706              : }
    4707              : 
    4708              : impl TimelineWriterState {
    4709      3648020 :     fn new(open_layer: Arc<InMemoryLayer>, current_size: u64, last_freeze_at: Lsn) -> Self {
    4710      3648020 :         Self {
    4711      3648020 :             open_layer,
    4712      3648020 :             current_size,
    4713      3648020 :             prev_lsn: None,
    4714      3648020 :             max_lsn: None,
    4715      3648020 :             cached_last_freeze_at: last_freeze_at,
    4716      3648020 :         }
    4717      3648020 :     }
    4718              : }
    4719              : 
    4720              : /// Various functions to mutate the timeline.
    4721              : // TODO Currently, Deref is used to allow easy access to read methods from this trait.
    4722              : // This is probably considered a bad practice in Rust and should be fixed eventually,
    4723              : // but will cause large code changes.
    4724              : pub(crate) struct TimelineWriter<'a> {
    4725              :     tl: &'a Timeline,
    4726              :     write_guard: tokio::sync::MutexGuard<'a, Option<TimelineWriterState>>,
    4727              : }
    4728              : 
    4729              : impl Deref for TimelineWriter<'_> {
    4730              :     type Target = Timeline;
    4731              : 
    4732      3650620 :     fn deref(&self) -> &Self::Target {
    4733      3650620 :         self.tl
    4734      3650620 :     }
    4735              : }
    4736              : 
    4737              : impl Drop for TimelineWriter<'_> {
    4738      3977036 :     fn drop(&mut self) {
    4739      3977036 :         self.write_guard.take();
    4740      3977036 :     }
    4741              : }
    4742              : 
    4743              : #[derive(PartialEq)]
    4744              : enum OpenLayerAction {
    4745              :     Roll,
    4746              :     Open,
    4747              :     None,
    4748              : }
    4749              : 
    4750              : impl<'a> TimelineWriter<'a> {
    4751              :     /// Put a new page version that can be constructed from a WAL record
    4752              :     ///
    4753              :     /// This will implicitly extend the relation, if the page is beyond the
    4754              :     /// current end-of-file.
    4755      3933972 :     pub(crate) async fn put(
    4756      3933972 :         &mut self,
    4757      3933972 :         key: Key,
    4758      3933972 :         lsn: Lsn,
    4759      3933972 :         value: &Value,
    4760      3933972 :         ctx: &RequestContext,
    4761      3933972 :     ) -> anyhow::Result<()> {
    4762      3933972 :         // Avoid doing allocations for "small" values.
    4763      3933972 :         // In the regression test suite, the limit of 256 avoided allocations in 95% of cases:
    4764      3933972 :         // https://github.com/neondatabase/neon/pull/5056#discussion_r1301975061
    4765      3933972 :         let mut buf = smallvec::SmallVec::<[u8; 256]>::new();
    4766      3933972 :         value.ser_into(&mut buf)?;
    4767      3933972 :         let buf_size: u64 = buf.len().try_into().expect("oversized value buf");
    4768      3933972 : 
    4769      3933972 :         let action = self.get_open_layer_action(lsn, buf_size);
    4770      3933972 :         let layer = self.handle_open_layer_action(lsn, action).await?;
    4771      3933972 :         let res = layer.put_value(key, lsn, &buf, ctx).await;
    4772              : 
    4773      3933972 :         if res.is_ok() {
    4774      3933972 :             // Update the current size only when the entire write was ok.
    4775      3933972 :             // In case of failures, we may have had partial writes which
    4776      3933972 :             // render the size tracking out of sync. That's ok because
    4777      3933972 :             // the checkpoint distance should be significantly smaller
    4778      3933972 :             // than the S3 single shot upload limit of 5GiB.
    4779      3933972 :             let state = self.write_guard.as_mut().unwrap();
    4780      3933972 : 
    4781      3933972 :             state.current_size += buf_size;
    4782      3933972 :             state.prev_lsn = Some(lsn);
    4783      3933972 :             state.max_lsn = std::cmp::max(state.max_lsn, Some(lsn));
    4784      3933972 :         }
    4785              : 
    4786      3933972 :         res
    4787      3933972 :     }
    4788              : 
    4789      3933974 :     async fn handle_open_layer_action(
    4790      3933974 :         &mut self,
    4791      3933974 :         at: Lsn,
    4792      3933974 :         action: OpenLayerAction,
    4793      3933974 :     ) -> anyhow::Result<&Arc<InMemoryLayer>> {
    4794      3933974 :         match action {
    4795              :             OpenLayerAction::Roll => {
    4796            0 :                 let freeze_at = self.write_guard.as_ref().unwrap().max_lsn.unwrap();
    4797            0 :                 self.roll_layer(freeze_at).await?;
    4798            0 :                 self.open_layer(at).await?;
    4799              :             }
    4800      3648020 :             OpenLayerAction::Open => self.open_layer(at).await?,
    4801              :             OpenLayerAction::None => {
    4802       285954 :                 assert!(self.write_guard.is_some());
    4803              :             }
    4804              :         }
    4805              : 
    4806      3933974 :         Ok(&self.write_guard.as_ref().unwrap().open_layer)
    4807      3933974 :     }
    4808              : 
    4809      3648020 :     async fn open_layer(&mut self, at: Lsn) -> anyhow::Result<()> {
    4810      3648020 :         let layer = self.tl.get_layer_for_write(at).await?;
    4811      3648020 :         let initial_size = layer.size().await?;
    4812              : 
    4813      3648020 :         let last_freeze_at = self.last_freeze_at.load();
    4814      3648020 :         self.write_guard.replace(TimelineWriterState::new(
    4815      3648020 :             layer,
    4816      3648020 :             initial_size,
    4817      3648020 :             last_freeze_at,
    4818      3648020 :         ));
    4819      3648020 : 
    4820      3648020 :         Ok(())
    4821      3648020 :     }
    4822              : 
    4823            0 :     async fn roll_layer(&mut self, freeze_at: Lsn) -> anyhow::Result<()> {
    4824            0 :         assert!(self.write_guard.is_some());
    4825              : 
    4826            0 :         self.tl.freeze_inmem_layer_at(freeze_at).await;
    4827              : 
    4828            0 :         let now = Instant::now();
    4829            0 :         *(self.last_freeze_ts.write().unwrap()) = now;
    4830            0 : 
    4831            0 :         self.tl.flush_frozen_layers();
    4832            0 : 
    4833            0 :         let current_size = self.write_guard.as_ref().unwrap().current_size;
    4834            0 :         if current_size > self.get_checkpoint_distance() {
    4835            0 :             warn!("Flushed oversized open layer with size {}", current_size)
    4836            0 :         }
    4837              : 
    4838            0 :         Ok(())
    4839            0 :     }
    4840              : 
    4841      3933974 :     fn get_open_layer_action(&self, lsn: Lsn, new_value_size: u64) -> OpenLayerAction {
    4842      3933974 :         let state = &*self.write_guard;
    4843      3933974 :         let Some(state) = &state else {
    4844      3648020 :             return OpenLayerAction::Open;
    4845              :         };
    4846              : 
    4847       285954 :         if state.prev_lsn == Some(lsn) {
    4848              :             // Rolling mid LSN is not supported by downstream code.
    4849              :             // Hence, only roll at LSN boundaries.
    4850       285898 :             return OpenLayerAction::None;
    4851           56 :         }
    4852           56 : 
    4853           56 :         if state.current_size == 0 {
    4854              :             // Don't roll empty layers
    4855            0 :             return OpenLayerAction::None;
    4856           56 :         }
    4857           56 : 
    4858           56 :         if self.tl.should_roll(
    4859           56 :             state.current_size,
    4860           56 :             state.current_size + new_value_size,
    4861           56 :             self.get_checkpoint_distance(),
    4862           56 :             lsn,
    4863           56 :             state.cached_last_freeze_at,
    4864           56 :             state.open_layer.get_opened_at(),
    4865           56 :         ) {
    4866            0 :             OpenLayerAction::Roll
    4867              :         } else {
    4868           56 :             OpenLayerAction::None
    4869              :         }
    4870      3933974 :     }
    4871              : 
    4872              :     /// Put a batch of keys at the specified Lsns.
    4873              :     ///
    4874              :     /// The batch is sorted by Lsn (enforced by usage of [`utils::vec_map::VecMap`].
    4875       413960 :     pub(crate) async fn put_batch(
    4876       413960 :         &mut self,
    4877       413960 :         batch: VecMap<Lsn, (Key, Value)>,
    4878       413960 :         ctx: &RequestContext,
    4879       413960 :     ) -> anyhow::Result<()> {
    4880      1113816 :         for (lsn, (key, val)) in batch {
    4881       699856 :             self.put(key, lsn, &val, ctx).await?
    4882              :         }
    4883              : 
    4884       413960 :         Ok(())
    4885       413960 :     }
    4886              : 
    4887            2 :     pub(crate) async fn delete_batch(&mut self, batch: &[(Range<Key>, Lsn)]) -> anyhow::Result<()> {
    4888            2 :         if let Some((_, lsn)) = batch.first() {
    4889            2 :             let action = self.get_open_layer_action(*lsn, 0);
    4890            2 :             let layer = self.handle_open_layer_action(*lsn, action).await?;
    4891            2 :             layer.put_tombstones(batch).await?;
    4892            0 :         }
    4893              : 
    4894            2 :         Ok(())
    4895            2 :     }
    4896              : 
    4897              :     /// Track the end of the latest digested WAL record.
    4898              :     /// Remember the (end of) last valid WAL record remembered in the timeline.
    4899              :     ///
    4900              :     /// Call this after you have finished writing all the WAL up to 'lsn'.
    4901              :     ///
    4902              :     /// 'lsn' must be aligned. This wakes up any wait_lsn() callers waiting for
    4903              :     /// the 'lsn' or anything older. The previous last record LSN is stored alongside
    4904              :     /// the latest and can be read.
    4905      4122936 :     pub(crate) fn finish_write(&self, new_lsn: Lsn) {
    4906      4122936 :         self.tl.finish_write(new_lsn);
    4907      4122936 :     }
    4908              : 
    4909       270570 :     pub(crate) fn update_current_logical_size(&self, delta: i64) {
    4910       270570 :         self.tl.update_current_logical_size(delta)
    4911       270570 :     }
    4912              : }
    4913              : 
    4914              : // We need TimelineWriter to be send in upcoming conversion of
    4915              : // Timeline::layers to tokio::sync::RwLock.
    4916              : #[test]
    4917            2 : fn is_send() {
    4918            2 :     fn _assert_send<T: Send>() {}
    4919            2 :     _assert_send::<TimelineWriter<'_>>();
    4920            2 : }
    4921              : 
    4922              : /// Add a suffix to a layer file's name: .{num}.old
    4923              : /// Uses the first available num (starts at 0)
    4924            0 : fn rename_to_backup(path: &Utf8Path) -> anyhow::Result<()> {
    4925            0 :     let filename = path
    4926            0 :         .file_name()
    4927            0 :         .ok_or_else(|| anyhow!("Path {path} don't have a file name"))?;
    4928            0 :     let mut new_path = path.to_owned();
    4929              : 
    4930            0 :     for i in 0u32.. {
    4931            0 :         new_path.set_file_name(format!("{filename}.{i}.old"));
    4932            0 :         if !new_path.exists() {
    4933            0 :             std::fs::rename(path, &new_path)
    4934            0 :                 .with_context(|| format!("rename {path:?} to {new_path:?}"))?;
    4935            0 :             return Ok(());
    4936            0 :         }
    4937              :     }
    4938              : 
    4939            0 :     bail!("couldn't find an unused backup number for {:?}", path)
    4940            0 : }
    4941              : 
    4942              : #[cfg(test)]
    4943              : mod tests {
    4944              :     use utils::{id::TimelineId, lsn::Lsn};
    4945              : 
    4946              :     use crate::tenant::{
    4947              :         harness::TenantHarness, storage_layer::Layer, timeline::EvictionError, Timeline,
    4948              :     };
    4949              : 
    4950              :     #[tokio::test]
    4951            2 :     async fn two_layer_eviction_attempts_at_the_same_time() {
    4952            2 :         let harness =
    4953            2 :             TenantHarness::create("two_layer_eviction_attempts_at_the_same_time").unwrap();
    4954            2 : 
    4955            2 :         let (tenant, ctx) = harness.load().await;
    4956            2 :         let timeline = tenant
    4957            2 :             .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
    4958            5 :             .await
    4959            2 :             .unwrap();
    4960            2 : 
    4961            2 :         let layer = find_some_layer(&timeline).await;
    4962            2 :         let layer = layer
    4963            2 :             .keep_resident()
    4964            2 :             .await
    4965            2 :             .expect("no download => no downloading errors")
    4966            2 :             .drop_eviction_guard();
    4967            2 : 
    4968            2 :         let forever = std::time::Duration::from_secs(120);
    4969            2 : 
    4970            2 :         let first = layer.evict_and_wait(forever);
    4971            2 :         let second = layer.evict_and_wait(forever);
    4972            2 : 
    4973            4 :         let (first, second) = tokio::join!(first, second);
    4974            2 : 
    4975            2 :         let res = layer.keep_resident().await;
    4976            2 :         assert!(res.is_none(), "{res:?}");
    4977            2 : 
    4978            2 :         match (first, second) {
    4979            2 :             (Ok(()), Ok(())) => {
    4980            2 :                 // because there are no more timeline locks being taken on eviction path, we can
    4981            2 :                 // witness all three outcomes here.
    4982            2 :             }
    4983            2 :             (Ok(()), Err(EvictionError::NotFound)) | (Err(EvictionError::NotFound), Ok(())) => {
    4984            0 :                 // if one completes before the other, this is fine just as well.
    4985            0 :             }
    4986            2 :             other => unreachable!("unexpected {:?}", other),
    4987            2 :         }
    4988            2 :     }
    4989              : 
    4990            2 :     async fn find_some_layer(timeline: &Timeline) -> Layer {
    4991            2 :         let layers = timeline.layers.read().await;
    4992            2 :         let desc = layers
    4993            2 :             .layer_map()
    4994            2 :             .iter_historic_layers()
    4995            2 :             .next()
    4996            2 :             .expect("must find one layer to evict");
    4997            2 : 
    4998            2 :         layers.get_from_desc(&desc)
    4999            2 :     }
    5000              : }
        

Generated by: LCOV version 2.1-beta