LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 727bdccc1d7d53837da843959afb612f56da4e79.info Lines: 62.6 % 3720 2330
Test Date: 2025-01-30 15:18:43 Functions: 59.8 % 326 195

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

Generated by: LCOV version 2.1-beta