LCOV - code coverage report
Current view: top level - pageserver/src/tenant - timeline.rs (source / functions) Coverage Total Hit
Test: 71d97c4519b9017c5903db4dfe4edf4a84645500.info Lines: 63.5 % 3503 2223
Test Date: 2024-12-19 16:48:20 Functions: 59.6 % 324 193

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

Generated by: LCOV version 2.1-beta